{"nl": {"description": "Salem gave you $$$n$$$ sticks with integer positive lengths $$$a_1, a_2, \\ldots, a_n$$$.For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $$$a$$$ to $$$b$$$ is $$$|a - b|$$$, where $$$|x|$$$ means the absolute value of $$$x$$$.A stick length $$$a_i$$$ is called almost good for some integer $$$t$$$ if $$$|a_i - t| \\le 1$$$.Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer $$$t$$$ and the total cost of changing is minimum possible. The value of $$$t$$$ is not fixed in advance and you can choose it as any positive integer. As an answer, print the value of $$$t$$$ and the minimum cost. If there are multiple optimal choices for $$$t$$$, print any of them.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) — the number of sticks. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 100$$$) — the lengths of the sticks.", "output_spec": "Print the value of $$$t$$$ and the minimum possible cost. If there are multiple optimal choices for $$$t$$$, print any of them.", "sample_inputs": ["3\n10 1 4", "5\n1 1 2 2 3"], "sample_outputs": ["3 7", "2 0"], "notes": "NoteIn the first example, we can change $$$1$$$ into $$$2$$$ and $$$10$$$ into $$$4$$$ with cost $$$|1 - 2| + |10 - 4| = 1 + 6 = 7$$$ and the resulting lengths $$$[2, 4, 4]$$$ are almost good for $$$t = 3$$$.In the second example, the sticks lengths are already almost good for $$$t = 2$$$, so we don't have to do anything."}, "positive_code": [{"source_code": "function ansa(n,arr){\n\n var ans = []\n ans[0] = Infinity\n for(var i = 1 ; i < 101 ; i++){\n\n ans[i] = 0\n\n for(var j = 0 ; j < n ; j++){\n\n ans[i] += Math.abs(arr[j] - i);\n if(Math.abs(arr[j] - i) !== 0) ans[i]--\n\n }\n }\n var min = Math.min(...ans);\n print(ans.indexOf(min) + \" \" + min)\n}\n\nvar line = readline().split(' ')\nvar arr = readline().split(' ')\nfor(var i = 0 ; i < arr.length ; i++)arr[i] = parseInt(arr[i]);\nansa(parseInt(line[0]),arr)\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet l = 0;\nrl.on('line', (input) => {\n if (l === 0) {} else {\n rl.close();\n let hm = {}\n let arr = input.split(\" \").map(x=>parseInt(x))\n let mn1 = 9999999\n let nr = 0\n for(let i=1;i<=100;i++){\n let s=0\n for(let j=0;j {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\n\nfunction main() {\n const len = +readLine();\n const arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n let [min, t] = [Infinity, 1];\n\n for (let i = 1; i <= 1000; i++) {\n const target = i;\n let count = 0;\n for (let j = 0; j < len; j++) {\n const current = arr[j];\n const diff = Math.abs(target - current);\n if (diff > 1) {\n count += diff - 1;\n }\n }\n if (count < min) {\n min = count;\n t = target;\n }\n }\n\n console.log(`${t} ${min}`);\n}\n"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\n\nfunction main() {\n const len = +readLine();\n const arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n let [min, t] = [Infinity, 1];\n\n for (let i = 0; i < len; i++) {\n const target = arr[i];\n let count = 0;\n for (let j = 0; j < len; j++) {\n const current = arr[j];\n const diff = Math.abs(target - current);\n if (diff > 1) {\n count += diff - 1;\n }\n }\n if (count < min) {\n min = count;\n t = target;\n }\n }\n\n console.log(`${t} ${min}`);\n}\n"}], "src_uid": "bce9ebad1dc8bd5aae516c4ca9e551c0"} {"nl": {"description": "Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.More formally, let's define as maximum value of over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know for all x from 0 to |s| where |s| denotes the length of string s.", "input_spec": "The first line of the input contains the string s (1 ≤ |s| ≤ 2 000). The second line of the input contains the string p (1 ≤ |p| ≤ 500). Both strings will only consist of lower case English letters.", "output_spec": "Print |s| + 1 space-separated integers in a single line representing the for all x from 0 to |s|.", "sample_inputs": ["aaaaa\naa", "axbaxxb\nab"], "sample_outputs": ["2 2 1 1 0 0", "0 1 1 2 1 1 0 0"], "notes": "NoteFor the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {\"aaaaa\", \"aaaa\", \"aaa\", \"aa\", \"a\", \"\"}. For the second sample, possible corresponding optimal values of s' are {\"axbaxxb\", \"abaxxb\", \"axbab\", \"abab\", \"aba\", \"ab\", \"a\", \"\"}."}, "positive_code": [{"source_code": "var s = readline();\nvar p = readline();\n\nvar n = s.length;\nvar dp = new Array();\nfor(var i=0; i<=n; i++)\n{\n dp[i] = new Array();\n}\n\nvar a = new Array();\nvar b = new Array();\n\n//a[i] = t => a[t]-a[i] contains the pattern, meanwhile it should remove b[i] chars\n//dp[i][j] = max(dp[i-1][j-1], dp[i][j-1], dp[i-b[j]][a[j]-1]+1);\n\nfor(var m=0; m=0)\n\t{\n\t if(s[i]==p[j])\n\t\t{\n\t\t if(j==0)\n\t\t\t{\n\t\t\t\ta[m] = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t i--;\n\t\t\tj--;\n\t\t}\n\t\telse\n\t\t{\n\t\t i--;\n\t\t\tb[m]++;\n\t\t}\n\t}\n}\n\nfor(var i=0; i<=n; i++)\n{\n for(var j=0; jj+1)\n\t\t{\n\t\t dp[i][j] = -1;\n\t\t\tcontinue;\n\t\t}\n\t dp[i][j] = 0;\n\t\tif(i-1>=0&&j-1>=0&&dp[i-1][j-1]>dp[i][j])\n\t\t{\n\t\t dp[i][j] = dp[i-1][j-1];\n\t\t}\n\t\tif(j-1>=0&&dp[i][j-1]>dp[i][j])\n\t\t{\n\t\t dp[i][j] = dp[i][j-1];\n\t\t}\n\t\tif(a[j]!=-1&&i-b[j]>=0)\n\t\t{\n\t\t var tt = 0;\n\t\t if(a[j]==0)\n\t\t\t{\n\t\t\t if(i-b[j]==0)\n\t\t\t {tt = 1;}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t tt = 1 + dp[i-b[j]][a[j]-1];\n\t\t\t}\n\t\t\tif(tt>dp[i][j])\n\t\t\t{\n\t\t\t dp[i][j] = tt;\n\t\t\t}\n\t\t}\n\t}\n}\nvar res = dp[0][n-1];\nfor(var i=1; i<=n; i++)\n{\n res = res + ' ' + dp[i][n-1];\n}\nprint(res);"}], "negative_code": [], "src_uid": "abdf06347e6db23932ef07020f49aa52"} {"nl": {"description": "Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T: Set pointer to the root of a tree. Return success if the value in the current vertex is equal to the number you are looking for Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for Return fail if you try to go to the vertex that doesn't exist Here is the pseudo-code of the described algorithm: bool find(TreeNode t, int x) { if (t == null) return false; if (t.value == x) return true; if (x < t.value) return find(t.left, x); else return find(t.right, x);}find(root, x);The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.", "input_spec": "First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree. Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number  - 1 is set instead. Note that different vertices of the tree may contain the same values.", "output_spec": "Print number of times when search algorithm will fail.", "sample_inputs": ["3\n15 -1 -1\n10 1 3\n5 -1 -1", "8\n6 2 3\n3 4 5\n12 6 7\n1 -1 8\n4 -1 -1\n5 -1 -1\n14 -1 -1\n2 -1 -1"], "sample_outputs": ["2", "1"], "notes": "NoteIn the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for."}, "positive_code": [{"source_code": " var n = parseInt(readline());\n var v = new Array(n + 1);\n var l = new Array(n + 1);\n var r = new Array(n + 1);\n var p = new Array(n + 1);\n for(var i = 1; i <= n; i += 1) {\n var tmp = readline().split(' ').map(x => parseInt(x));\n v[i] = tmp[0];\n l[i] = tmp[1];\n if(l[i] !== -1) {\n p[l[i]] = i;\n }\n r[i] = tmp[2];\n if(r[i] !== -1) {\n p[r[i]] = i;\n }\n }\n var root = 1;\n while(p[root] !== undefined) {\n root = p[root];\n }\n var res = 0;\n var ret = [];\n var stack = [\n {\n node: root,\n lb: -1,\n ub: 1000000009\n }\n ];\n while(stack.length > 0) {\n var tmp = stack.pop();\n var node = tmp.node;\n var lb = tmp.lb;\n var ub = tmp.ub;\n if(lb <= v[node] && v[node] <= ub) {\n ret[v[node]] = 1;\n }\n if(l[node] !== -1) {\n stack.push({\n node: l[node],\n lb: lb,\n ub: Math.min(ub, v[node] - 1)\n });\n }\n if(r[node] !== -1) {\n stack.push({\n node: r[node],\n lb: Math.max(lb, v[node] + 1),\n ub: ub\n });\n }\n }\n for(var i = 1; i <= n; i += 1) {\n if(ret[v[i]] === undefined) {\n res += 1;\n }\n }\n print(res);"}], "negative_code": [{"source_code": "\n var n = parseInt(readline());\n var v = [];\n var l = [];\n var r = [];\n var p = [];\n for(var i = 1; i <= n; i += 1) {\n var tmp = readline().split(' ').map(x => parseInt(x));\n v[i] = tmp[0];\n l[i] = tmp[1];\n if(l[i] !== -1) {\n p[l[i]] = i;\n }\n r[i] = tmp[2];\n if(r[i] !== -1) {\n p[r[i]] = i;\n }\n }\n var root = 1;\n while(p[root] !== undefined) {\n root = p[root];\n }\n var res = 0;\n for(var ii = 1; ii <= n; ii += 1) {\n var i = ii;\n var flag = true;\n var min = v[i];\n var max = v[i];\n var path = [];\n while((flag || true) && p[i] !== undefined) {\n path.push(i);\n if(i === l[p[i]]) {\n if(min <= v[p[i]]) {\n min = Math.max(v[p[i]], min);\n max = Math.min(v[i], max);\n } else {\n flag = false;\n }\n } else {\n if(max >= v[p[i]]) {\n min = Math.max(v[i], min);\n max = Math.min(v[p[i]], max);\n } else {\n flag = false;\n }\n }\n i = p[i];\n }\n res += flag ? 0 : 1;\n // console.log(path.map(i => `${i}: ${v[i]}`).join('--'), flag);\n }\n print(res);\n "}, {"source_code": " var n = parseInt(readline());\n var v = [];\n var l = [];\n var r = [];\n var p = [];\n for(var i = 1; i <= n; i += 1) {\n var tmp = readline().split(' ').map(x => parseInt(x));\n v[i] = tmp[0];\n l[i] = tmp[1];\n if(l[i] !== -1) {\n p[l[i]] = i;\n }\n r[i] = tmp[2];\n if(r[i] !== -1) {\n p[r[i]] = i;\n }\n }\n var root = 1;\n while(p[root] !== undefined) {\n root = p[root];\n }\n var res = 0;\n for(var ii = 1; ii <= n; ii += 1) {\n var i = ii;\n if(l[i] === -1 && r[i] === -1) {\n var flag = true;\n var min = v[i];\n var max = v[i];\n while(flag && p[i] !== undefined) {\n if(i === l[p[i]]) {\n if(min <= v[p[i]]) {\n i = p[i];\n min = Math.max(v[p[i]], min);\n max = Math.min(v[i], max);\n } else {\n flag = false;\n }\n } else {\n if(max >= v[p[i]]) {\n i = p[i];\n min = Math.max(v[i], min);\n max = Math.min(v[p[i]], max);\n } else {\n flag = false;\n }\n }\n }\n res += flag ? 0 : 1;\n }\n }\n print(res);"}, {"source_code": " var n = parseInt(readline());\n var v = [];\n var l = [];\n var r = [];\n var p = [];\n for(var i = 1; i <= n; i += 1) {\n var tmp = readline().split(' ').map(x => parseInt(x));\n v[i] = tmp[0];\n l[i] = tmp[1];\n if(l[i] !== -1) {\n p[l[i]] = i;\n }\n r[i] = tmp[2];\n if(r[i] !== -1) {\n p[r[i]] = i;\n }\n }\n var root = 1;\n while(p[root] !== undefined) {\n root = p[root];\n }\n var res = 0;\n for(var i = 1; i <= n; i += 1) {\n var node = root;\n while(true) {\n if(node > n || node <= 0) {\n res += 1;\n break;\n }\n if(v[node] === v[i]) {\n if(node !== i) {\n res += 1;\n }\n break;\n }\n if(v[i] < v[node]) {\n node = l[node];\n } else {\n node = r[node];\n }\n }\n }\n print(res);"}], "src_uid": "a64517a876d3acac84a928131108d1fd"} {"nl": {"description": "You are given a binary string (i. e. a string consisting of characters 0 and/or 1) $$$s$$$ of length $$$n$$$. You can perform the following operation with the string $$$s$$$ at most once: choose a substring (a contiguous subsequence) of $$$s$$$ having exactly $$$k$$$ characters 1 in it, and shuffle it (reorder the characters in the substring as you wish).Calculate the number of different strings which can be obtained from $$$s$$$ by performing this operation at most once.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 5000$$$; $$$0 \\le k \\le n$$$). The second line contains the string $$$s$$$ of length $$$n$$$, consisting of characters 0 and/or 1.", "output_spec": "Print one integer — the number of different strings which can be obtained from $$$s$$$ by performing the described operation at most once. Since the answer can be large, output it modulo $$$998244353$$$.", "sample_inputs": ["7 2\n1100110", "5 0\n10010", "8 1\n10001000", "10 8\n0010011000"], "sample_outputs": ["16", "1", "10", "1"], "notes": "NoteSome strings you can obtain in the first example: to obtain 0110110, you can take the substring from the $$$1$$$-st character to the $$$4$$$-th character, which is 1100, and reorder its characters to get 0110; to obtain 1111000, you can take the substring from the $$$3$$$-rd character to the $$$7$$$-th character, which is 00110, and reorder its characters to get 11000; to obtain 1100101, you can take the substring from the $$$5$$$-th character to the $$$7$$$-th character, which is 110, and reorder its characters to get 101. In the second example, $$$k = 0$$$ so you can only choose the substrings consisting only of 0 characters. Reordering them doesn't change the string at all, so the only string you can obtain is 10010."}, "positive_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n// const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const s = lines[l++]\n output[i] = solve(n, k, s)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, s) {\n const ps = []\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '1') ps.push(i)\n }\n if (ps.length < k) return 1\n\n const cache = combo(n)\n let ans = 1\n let j = 0\n for (let i = 0; i < s.length; i++) {\n const d = (j + k < ps.length ? ps[j + k] : n) - 1 - i\n let c\n if (s[i] === '1') {\n c = Math.min(ps.length - j, k)\n } else {\n c = Math.min(ps.length - j - 1, k - 1)\n }\n // const c = Math.min(ps.length - j, s[i] === '1' ? k : k - 1)\n if (d > 0 && c >= 0 && d >= c && j < ps.length) {\n ans = add(ans, cache[d][c])\n }\n // console.log(d, c)\n if (s[i] === '1') {\n j++\n }\n }\n return ans\n}\nconst MOD = 998244353\nfunction add(a, b) {\n return (a + b) % MOD\n}\nfunction combo(n) {\n const r = []\n for (let i = 1; i <= n; i++) {\n r[i] = []\n for (let j = 0; j <= n; j++) {\n if (i === 1 || !j || i <= j) {\n r[i][j] = 1\n continue\n }\n r[i][j] = add(r[i - 1][j - 1], r[i - 1][j])\n }\n }\n return r\n}\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nlet a;\r\nconst mod = 998244353;\r\nfunction cnk(n, k) {\r\n if (k > n - k)\r\n k = n - k;\r\n return a[n][k];\r\n}\r\n\r\nfunction precalc(n) {\r\n a = new Array(n + 1);\r\n a[0] = new Array(1);\r\n a[0][0] = 1;\r\n for(let i = 1; i <= n; i++) {\r\n a[i] = new Array(Math.floor(i / 2) + 1);\r\n for(let j = 0; j <= Math.floor(i / 2); j++) {\r\n if (j === 0) {\r\n a[i][j] = 1;\r\n } else {\r\n a[i][j] = cnk(i-1,j-1);\r\n if (i > j) {\r\n a[i][j] = (a[i][j] + cnk(i-1,j)) % mod;\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nlet solve = async () => {\r\n const [n,k] = (await getLine()).split(' ').map(num => parseInt(num));\r\n precalc(n);\r\n const nk = cnk(4,2);\r\n const s = await getLine();\r\n let l,r;\r\n if (k===0) {\r\n console.log('1');\r\n return;\r\n }\r\n for(l = 0; l < s.length && s.charAt(l) === '0'; l++);\r\n if (l >= s.length) {\r\n console.log('1');\r\n return;\r\n }\r\n\r\n if (k === 1)\r\n r = l;\r\n else {\r\n let count = k - 1;\r\n for (r = l + 1; r < s.length && count > 0;)\r\n if (s.charAt(r) === '1') {\r\n count--;\r\n if (count > 0) {\r\n r++;\r\n }\r\n } else r++;\r\n if (r >= s.length) {\r\n console.log('1');\r\n return;\r\n }\r\n }\r\n\r\n let res = 1;\r\n while (r < s.length) {\r\n let ll = l;\r\n let rr = r;\r\n while (rr + 1 < s.length && s.charAt(rr + 1) === '0') {\r\n rr++;\r\n }\r\n while (ll - 1 >= 0 && s.charAt(ll - 1) === '0') {\r\n ll--;\r\n res = (res + cnk(rr - ll, k - 1)) % mod;\r\n }\r\n ll = l + 1;\r\n while (rr - ll >= k - 1) {\r\n res = (res + cnk(rr - ll, k - 1)) % mod;\r\n ll++;\r\n }\r\n\r\n if (rr === s.length - 1) {\r\n res = (res + cnk(rr - l,k - 1) + mod - 1) % mod;\r\n }\r\n\r\n r++;\r\n while (r < s.length && s.charAt(r) === '0') r++;\r\n l++;\r\n while (l < s.length && s.charAt(l) === '0') l++;\r\n }\r\n\r\n console.log(res);\r\n\r\n}\r\n\r\nsolve();\r\n"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n// const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const s = lines[l++]\n output[i] = solve(n, k, s)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, s) {\n const ps = []\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '1') ps.push(i)\n }\n if (ps.length < k) return 1\n\n const cache = combo(n)\n let ans = 1\n let j = 0\n for (let i = 0; i < s.length; i++) {\n const d = (j + k < ps.length ? ps[j + k] : n) - 1 - i\n let c\n if (s[i] === '1') {\n c = Math.min(ps.length - j, k)\n } else {\n c = Math.min(ps.length - j - 1, k - 1)\n }\n // const c = Math.min(ps.length - j, s[i] === '1' ? k : k - 1)\n if (d > 0 && c >= 0 && j < ps.length) {\n ans = add(ans, cache[d][c])\n }\n // console.log(d, c)\n if (s[i] === '1') {\n j++\n }\n }\n return ans\n}\nconst MOD = 998244353\nfunction add(a, b) {\n return (a + b) % MOD\n}\nfunction combo(n) {\n const r = []\n for (let i = 1; i <= n; i++) {\n r[i] = []\n for (let j = 0; j <= n; j++) {\n if (i === 1 || !j || i <= j) {\n r[i][j] = 1\n continue\n }\n r[i][j] = add(r[i - 1][j - 1], r[i - 1][j])\n }\n }\n return r\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n// const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const s = lines[l++]\n output[i] = solve(n, k, s)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, s) {\n const ps = []\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '1') ps.push(i)\n }\n if (ps.length < k) return 1\n\n const cache = combo(n)\n let ans = 1\n let j = 0\n for (let i = 0; i < s.length; i++) {\n const d = (j + k < ps.length ? ps[j + k] : n) - 1 - i\n let c\n if (s[i] === '1') {\n c = Math.min(ps.length - j, k)\n } else {\n c = Math.min(ps.length - j - 1, k - 1)\n }\n // const c = Math.min(ps.length - j, s[i] === '1' ? k : k - 1)\n if (d > 0 && j < ps.length) {\n ans = add(ans, cache[d][c])\n }\n // console.log(d, c)\n if (s[i] === '1') {\n j++\n }\n }\n return ans\n}\nconst MOD = 998244353\nfunction add(a, b) {\n return (a + b) % MOD\n}\nfunction combo(n) {\n const r = []\n for (let i = 1; i <= n; i++) {\n r[i] = []\n for (let j = 0; j <= n; j++) {\n if (i === 1 || !j || i <= j) {\n r[i][j] = 1\n continue\n }\n r[i][j] = add(r[i - 1][j - 1], r[i - 1][j])\n }\n }\n return r\n}\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nlet a;\r\nconst mod = 998244353;\r\nfunction cnk(n, k) {\r\n if (k > n - k)\r\n k = n - k;\r\n return a[n][k];\r\n}\r\n\r\nfunction precalc(n) {\r\n a = new Array(n + 1);\r\n a[0] = new Array(1);\r\n a[0][0] = 1;\r\n for(let i = 1; i <= n; i++) {\r\n a[i] = new Array(Math.floor(i / 2) + 1);\r\n for(let j = 0; j <= Math.floor(i / 2); j++) {\r\n if (j === 0) {\r\n a[i][j] = 1;\r\n } else {\r\n a[i][j] = cnk(i-1,j-1);\r\n if (i > j) {\r\n a[i][j] = (a[i][j] + cnk(i-1,j)) % mod;\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nlet solve = async () => {\r\n const [n,k] = (await getLine()).split(' ').map(num => parseInt(num));\r\n precalc(n);\r\n const nk = cnk(4,2);\r\n const s = await getLine();\r\n let l,r;\r\n for(l = 0; l < s.length && s.charAt(l) === '0'; l++);\r\n if (l >= s.length) {\r\n console.log('1');\r\n return;\r\n }\r\n if (k === 1)\r\n r = l;\r\n else {\r\n let count = k - 1;\r\n for (r = l + 1; r < s.length && count > 0;)\r\n if (s.charAt(r) === '1') {\r\n count--;\r\n if (count > 0) {\r\n r++;\r\n }\r\n }\r\n if (r >= s.length) {\r\n console.log('1');\r\n return;\r\n }\r\n }\r\n\r\n let res = 1;\r\n while (r < s.length) {\r\n /* let ll = l;\r\n while (true) {\r\n let rr = r;\r\n while (true) {\r\n res = (res + cnk(rr - ll - 1, k - 2)) % mod;\r\n if (rr === r && ll === l) {\r\n res = (res + mod - 1) % mod;\r\n }\r\n rr++;\r\n if (rr >= s.length || s.charAt(rr) === '1')\r\n break;\r\n }\r\n ll--;\r\n if (ll < 0 || s.charAt(ll) === '1')\r\n break;\r\n } */\r\n let ll = l;\r\n let rr = r;\r\n while (rr + 1 < s.length && s.charAt(rr + 1) === '0') {\r\n rr++;\r\n }\r\n while (ll - 1 >= 0 && s.charAt(ll - 1) === '0') {\r\n ll--;\r\n res = (res + cnk(rr - ll, k - 1)) % mod;\r\n }\r\n ll = l + 1;\r\n while (rr - ll >= k - 1) {\r\n res = (res + cnk(rr - ll, k - 1)) % mod;\r\n ll++;\r\n }\r\n\r\n if (rr === s.length - 1) {\r\n res = (res + cnk(rr - l,k - 1) + mod - 1) % mod;\r\n }\r\n\r\n r++;\r\n while (r < s.length && s.charAt(r) === '0') r++;\r\n l++;\r\n while (l < s.length && s.charAt(l) === '0') l++;\r\n }\r\n\r\n console.log(res);\r\n\r\n}\r\n\r\nsolve();\r\n"}], "src_uid": "d666df06a7a7ecbe801c1018b3d482b9"} {"nl": {"description": "Berland annual chess tournament is coming!Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.Thus, organizers should divide all 2·n players into two teams with n people each in such a way that the first team always wins.Every chess player has its rating ri. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win.After teams assignment there will come a drawing to form n pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.Is it possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing?", "input_spec": "The first line contains one integer n (1 ≤ n ≤ 100). The second line contains 2·n integers a1, a2, ... a2n (1 ≤ ai ≤ 1000).", "output_spec": "If it's possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing, then print \"YES\". Otherwise print \"NO\".", "sample_inputs": ["2\n1 3 2 4", "1\n3 3"], "sample_outputs": ["YES", "NO"], "notes": null}, "positive_code": [{"source_code": "function cmp(a,b)\n{\n return a-b;\n}\n\nvar n = +readline();\nvar s = readline();\n\nvar a = s.split(' ').map(function(v){return +v;});\na.sort(cmp);\nif (a[n-1]===a[n])\n{\n print(\"NO\");\n}\nelse\n{\n print(\"YES\");\n}"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);}).filter(function(elem){\n return !isNaN(elem);\n});\nplayers.sort(function(a,b){\n return ab?1:0);\n});\n\nprint((players[n-1] == players[n])?'NO':'YES');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ');\nfor(var i in players){\n players[i] = parseInt(players[i]);\n}\nplayers.sort(function(a,b){\n return ab?1:0);\n});\n\nprint((players[n-1] == players[n])?'NO':'YES');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\nplayers.sort(function(a,b){\n return ab?1:0);\n});\n\nprint((players[n-1] == players[n])?'NO':'YES');"}, {"source_code": "var length = readline().split(\" \").map(function(x) { return parseInt(x); })[0];\nvar raitings = readline().split(\" \").map(function(x) { return parseInt(x); });\nraitings.sort(function(a,b) { return a - b;});\nvar mid = raitings.length / 2;\nprint(raitings[mid - 1] < raitings[mid] ? \"YES\" : \"NO\")"}], "negative_code": [{"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\n\nplayers.sort(function(a,b){\n return a>=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n\n\nprint((result1=players[n-1])?'YES':'NO');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\nplayers.sort(function(a,b){\n return a>=b;\n});\nwrite((players[n]==players[n-1])?'NO':'YES');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\n\nplayers.sort(function(a,b){\n return a>=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n\n\nprint((result1players[n-1])?'YES':'NO');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\n\nplayers.sort(function(a,b){\n return a>=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n\n\nprint((result1=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n/*print((players[n-1] == players[n])?'NO':'YES');\n*/\nif((result1 < result2) && (players[n-1] < players[n])){\n print(\"YES\");\n}else{\n print(\"NO\");\n}"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);}).filter(function(elem){\n return !isNaN(elem);\n});\nplayers.sort(function(a,b){\n return a>=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n/*print((players[n-1] == players[n])?'NO':'YES');\n*/\n\n\n\nif((result1 < result2) && (players[n-1] < players[n])){\n print(\"YES\");\n}else{\n print(\"NO\");\n}"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);}).filter(function(elem){\n return !isNaN(elem);\n});\nplayers.sort(function(a,b){\n return a>=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n\nprint((result1=b;\n});\n/*var result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);*/\n\nprint((players[n-1] == players[n])?'NO':'YES');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\nplayers.sort(function(a,b){\n return a>=b;\n});\nprint((players[n]>players[n-1])?'YES':'NO');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\n\nplayers.sort(function(a,b){\n return a>b;\n});\n\nwrite((players[n]>players[n-1])?'YES':'NO');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\nplayers.sort(function(a,b){\n return a>=b;\n});\nprint((players[n]==players[n-1])?'NO':'YES');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\n\nplayers.sort(function(a,b){\n return a>=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n\n\nprint((result1players[n-1])?'YES':'NO');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\nplayers.sort(function(a,b){\n return a>b;\n});\nprint((players[n]>players[n-1])?'YES':'NO');"}, {"source_code": "var n = parseInt(readline());\nvar players = readline().split(' ').map(function(term) { return parseInt(term);});\n\nplayers.sort(function(a,b){\n return a>=b;\n});\nvar result1 = players.slice(0,n).reduce(function(sum, elem){return sum+elem},0);\nvar result2 = players.slice(n).reduce(function(sum, elem){return sum+elem},0);\n\nprint((result1 {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let _ = readLine();\n let arr = readLine()\n .split(\" \")\n .map((num) => parseInt(num));\n solve(arr);\n }\n\n function solve(arr) {\n const evenMap = {};\n const oddMap = {};\n\n arr.forEach((num, index) => {\n if (num % 2 === 0) evenMap[index + 1] = num;\n else oddMap[index + 1] = num;\n });\n\n let evenKeys = Object.keys(evenMap);\n let oddKeys = Object.keys(oddMap);\n\n for (let i = 0; i < arr.length / 2 - 1; i++) {\n if (evenKeys.length >= 2) console.log(`${evenKeys.pop()} ${evenKeys.pop()}`);\n else console.log(`${oddKeys.pop()} ${oddKeys.pop()}`);\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nvar input = '';\nprocess.stdin.on('data', function (line) {\n input += line;\n});\nprocess.stdin.on('end', function () {\n var lines = input.split('\\n');\n var tests = parseInt(lines.shift(), 10);\n var _loop_1 = function () {\n var n = parseInt(lines.shift(), 10);\n var arr = lineToNumArray(lines.shift());\n var indices = [[], []];\n arr.forEach(function (element, index) { return indices[element % 2].push(index); });\n if (indices[0].length % 2) {\n indices[0].shift();\n indices[1].shift();\n }\n else {\n var parity = Number(!indices[0].length);\n indices[parity].shift();\n indices[parity].shift();\n }\n indices.forEach(function (parity) {\n while (parity.length) {\n console.log(1 + parity.pop(), 1 + parity.pop());\n }\n });\n };\n while (tests--) {\n _loop_1();\n }\n});\n// input helper\nfunction lineToNumArray(line) {\n return line.split(' ').map(function (element) { return parseInt(element, 10); });\n}\n"}, {"source_code": "const processData = (lines) => {\n let acc = 0\n const n = +lines[acc]\n acc++\n for (let i=0; i x%2)\n acc++\n const map = {\n 0: [],\n 1: []\n }\n for (let i =0; i 1) {\n const l = map[cursor[0]].length\n if (l <= cursor[1]+1) {\n cursor[0] = 1\n cursor[1] = 0\n }\n console.log(map[cursor[0]][cursor[1]]+1, map[cursor[0]][cursor[1]+1]+1)\n cursor[1] += 2\n n--\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var n = +readline();\n var arr = readNumArray();\n var lastEven = 0;\n var lastOdd = 0;\n var counter = 0;\n for (var j = 1; j <= 2 * n; j++) {\n if (arr[j - 1] % 2) {\n if (lastOdd) {\n print(lastOdd + \" \" + j);\n lastOdd = 0;\n counter++;\n } else {\n lastOdd = j;\n }\n } else {\n if (lastEven) {\n print(lastEven + \" \" + j);\n lastEven = 0;\n counter++;\n } else {\n lastEven = j;\n }\n }\n if (counter === n - 1) {\n break;\n }\n }\n }\n}\n\nmain();"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let _ = readLine();\n let arr = readLine()\n .split(\" \")\n .map((num) => parseInt(num));\n solve(arr);\n }\n\n function solve(arr) {\n const map = { even: [], odd: [] };\n arr.forEach((num) => {\n if (num % 2 === 0) map[\"even\"].push(num);\n else map[\"odd\"].push(num);\n });\n for (let i = 0; i < arr.length / 2 - 1; i++) {\n if (map[\"even\"].length >= 2) console.log(`${map[\"even\"].pop()} ${map[\"even\"].pop()}`);\n else console.log(`${map[\"odd\"].pop()} ${map[\"odd\"].pop()}`);\n }\n }\n}\n"}], "src_uid": "96fac9f9377bf03e144067bf93716d3d"} {"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, x2, ..., xn. 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 - hi, xi] or [xi;xi + hi]. 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 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-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 — 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 — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — 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": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = true;\n \n this.find = function( val , fl ) {\n \tvar lo , hi , mi , res , sz1 , sz2 ;\n \tsz1 = this.brr.length ;\n \tsz2 = this.crr.length ;\n \tlo = 0 ;\n \tif( fl == false ) {\n \t\thi = sz1 - 1 ;\n \t}\n \telse {\n \t\thi = sz2 - 1 ;\n \t}\n \tres = -1 ;\n \twhile( lo <= hi ) {\n \t\tmi = Math.floor( ( lo + hi ) / 2 ) ;\n \t\tif( fl == false ) {\n \t\t\tif( this.brr[ mi ].index < val ) {\n \t\t\t\tlo = mi + 1 ;\n \t\t\t\tres = Math.max( res , mi ) ;\n \t\t\t}\n \t\t\telse {\n \t\t\t\thi = mi - 1 ;\n \t\t\t}\n \t\t}\n \t\telse {\n \t\t\tif( this.crr[ mi ].index + this.crr[ mi ].height < val ) {\n \t\t\t\tlo = mi + 1 ;\n \t\t\t\tres = Math.max( res , mi ) ;\n \t\t\t}\n \t\t\telse {\n \t\t\t\thi = mi - 1 ;\n \t\t\t}\n \t\t}\n \t}\n \tif( res != -1 ) {\n \t\tif( fl == false ) {\n \t\t\tres = this.brr[ res ].arrayIndex ;\n \t\t}\n \t\telse {\n \t\t\tres = this.crr[ res ].arrayIndex ;\n \t\t}\n \t}\n \treturn res ;\n } ;\n\n this.solveCase = function() {\n var res , i , j ;\n res = 0 ;\n this.arr = this.arr.sort( function( left , right ) { return left.index - right.index ; } ) ;\n this.brr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( i == 0 ) {\n \t\tthis.brr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n \telse if( this.arr[ i ].index - this.arr[ i ].height > this.arr[ i - 1 ].index ) {\n \t\tthis.brr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n }\n this.crr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( i == this.n - 1 ) {\n \t\tthis.crr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n \telse if( this.arr[ i ].index + this.arr[ i ].height < this.arr[ i + 1 ].index ) {\n \t\tthis.crr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n }\n for( i = 0 ; i < this.n ; i++ ) {\n \tthis.memo[ i ][ 0 ] = 1 ;\n \tthis.memo[ i ][ 1 ] = 1 ;\n \tif( i > 0 ) {\n \t\tj = this.find( this.arr[ i ].index - this.arr[ i ].height , false ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 0 ] = Math.max( this.memo[ i ][ 0 ] , this.memo[ j ][ 0 ] + 1 ) ;\n \t\t}\n \t\tj = this.find( this.arr[ i ].index - this.arr[ i ].height , true ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 0 ] = Math.max( this.memo[ i ][ 0 ] , this.memo[ j ][ 1 ] + 1 ) ;\n \t\t}\n \t\tj = this.find( this.arr[ i ].index , false ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 1 ] = Math.max( this.memo[ i ][ 1 ] , this.memo[ j ][ 0 ] + 1 ) ;\n \t\t}\n \t\tj = this.find( this.arr[ i ].index , true ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 1 ] = Math.max( this.memo[ i ][ 1 ] , this.memo[ j ][ 1 ] + 1 ) ;\n \t\t}\n\t \tthis.memo[ i ][ 0 ] = Math.max( this.memo[ i ][ 0 ] , this.memo[ i - 1 ][ 0 ] ) ;\n\t \tthis.memo[ i ][ 1 ] = Math.max( this.memo[ i ][ 1 ] , this.memo[ i - 1 ][ 1 ] ) ;\n \t}\n \tres = Math.max( res , this.memo[ i ][ 0 ] ) ;\n\t res = Math.max( res , this.memo[ i ][ 1 ] ) ;\n }\n print( res );\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i , obj ;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n this.arr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tobj = {} ;\n \tobj.index = irObj.nextInt() ;\n \tobj.height = irObj.nextInt() ;\n this.arr.push( obj ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.brr = [];\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.idx = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.memo.push( new Array() );\n this.idx.push( new Array() );\n for( j = 0 ; j < 2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.idx[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "function toi(x){return parseInt(x);}\nvar n=+readline();\nif(n==1){\n print(\"1\")\n quit();\n} \t \nvar treex=[];\nvar treeh=[];\nfor(var i=0;i= distance ? FALL.yes : FALL.maybe;\n }\n\n return FALL.no;\n};\n\nvar Tree = function (data) {\n this.x = +data[0];\n this.h = +data[1];\n};\n\nTree.prototype.calculate = function (leftTree, rightTree) {\n this.left = fallType(this, leftTree);\n this.right = fallType(this, rightTree);\n};\n\nTree.prototype.canFall = function () {\n return this.left === FALL.yes || this.right === FALL.yes;\n};\n\nTree.prototype.cantFall = function () {\n return this.left === FALL.no && this.right === FALL.no;\n};\n\nvar trees = [new Tree([-Infinity, 0])];\nfor (var i = 0; i < n; ++i) {\n trees.push(new Tree(readline().split(' ')));\n}\ntrees.push(new Tree([+Infinity, 0]));\n\nfor (var i = 1; i <= n; ++i) {\n trees[i].calculate(trees[i - 1], trees[i + 1]);\n}\n\nvar result = 0;\nvar state = 0;\n\nfor (var i = 1; i <= n; ++i) {\n switch (state) {\n case 0:\n if (trees[i].canFall()) {\n ++result;\n state = 0;\n } else {\n if (trees[i].cantFall()) {\n state = 0;\n } else {\n if (trees[i].left === FALL.no) {\n ++result;\n state = 1;\n } else {\n ++result;\n }\n }\n }\n break;\n case 1:\n if (trees[i].canFall()) {\n ++result;\n state = 0;\n } else {\n if (trees[i].cantFall()) {\n state = 0;\n } else {\n if (trees[i].right === FALL.no) {\n state = 0;\n } else {\n ++result;\n }\n }\n }\n break;\n }\n}\n\nwrite(result);"}, {"source_code": "var n = +readline();\n\nconst FALL = {\n yes: {},\n maybe: {},\n no: {}\n}\n\nvar fallType = function(fallTree, blockTree) {\n var distance = Math.abs(fallTree.x - blockTree.x);\n \n if (fallTree.h + blockTree.h < distance) {\n return FALL.yes;\n }\n \n if (fallTree.h < distance) {\n if (blockTree.h >= distance) {\n return FALL.yes;\n }\n else {\n return FALL.maybe;\n }\n }\n \n return FALL.no;\n}\n\nvar Tree = function(data) {\n this.x = +data[0];\n this.h = +data[1];\n};\n\nTree.prototype.calculate = function(leftTree, rightTree) {\n this.left = fallType(this, leftTree);\n this.right = fallType(this, rightTree);\n};\n\nTree.prototype.canFall = function() {\n return this.left === FALL.yes || this.right === FALL.yes;\n};\n\nTree.prototype.cantFall = function() {\n return this.left === FALL.no && this.right === FALL.no;\n};\n\nTree.prototype.maybeFall = function() {\n return this.left === FALL.maybe || this.right === FALL.maybe;\n};\n\nvar trees = [new Tree([-Infinity, 0])];\nfor (var i = 0; i < n; ++i) {\n trees.push(new Tree(readline().split(' ')));\n}\ntrees.push(new Tree([+Infinity, 0]));\n\nfor (var i = 1; i <= n; ++i) {\n trees[i].calculate(trees[i-1], trees[i+1]);\n}\n\nvar result = 0;\nvar state = 0;\n\nfor (var i = 1; i <= n; ++i) {\n switch (state) {\n case 0:\n if (trees[i].canFall()) {\n ++result;\n state = 0;\n } else {\n if (trees[i].cantFall()) {\n state = 0;\n } else {\n if (trees[i].left === FALL.no) {\n ++result;\n state = 1;\n } else {\n ++result;\n }\n }\n }\n break;\n case 1:\n if (trees[i].canFall()) {\n ++result;\n state = 0;\n } else {\n if (trees[i].cantFall()) {\n state = 0;\n } else {\n if (trees[i].right === FALL.no) {\n state = 0;\n } else {\n ++result;\n }\n }\n }\n break;\n }\n}\n\nwrite(result);"}, {"source_code": "var n = +readline();\n\nconst FALL = {\n yes: {},\n maybe: {},\n no: {}\n};\n\nvar fallType = function (fallTree, blockTree) {\n var distance = Math.abs(fallTree.x - blockTree.x);\n\n if (fallTree.h + blockTree.h < distance) {\n return FALL.yes;\n }\n\n if (fallTree.h < distance) {\n return blockTree.h >= distance ? FALL.yes : FALL.maybe;\n }\n\n return FALL.no;\n};\n\nvar Tree = function (data) {\n this.x = +data[0];\n this.h = +data[1];\n};\n\nTree.prototype.calculate = function (leftTree, rightTree) {\n this.left = fallType(this, leftTree);\n this.right = fallType(this, rightTree);\n};\n\nTree.prototype.canFall = function () {\n return this.left === FALL.yes || this.right === FALL.yes;\n};\n\nTree.prototype.cantFall = function () {\n return this.left === FALL.no && this.right === FALL.no;\n};\n\nvar trees = [new Tree([-Infinity, 0])];\nfor (var i = 0; i < n; ++i) {\n trees.push(new Tree(readline().split(' ')));\n}\ntrees.push(new Tree([+Infinity, 0]));\n\nfor (var i = 1; i <= n; ++i) {\n trees[i].calculate(trees[i - 1], trees[i + 1]);\n}\n\nvar result = 0;\nvar state = 0;\n\nfor (var i = 1; i <= n; ++i) {\n switch (state) {\n case 0:\n if (trees[i].canFall()) {\n ++result;\n } else if (trees[i].cantFall()) {\n // nothing do to here\n } else if (trees[i].left === FALL.no) {\n ++result;\n state = 1;\n } else {\n ++result;\n }\n break;\n case 1:\n if (trees[i].canFall()) {\n ++result;\n state = 0;\n } else if (trees[i].cantFall()) {\n state = 0;\n } else if (trees[i].right === FALL.no) {\n state = 0;\n } else {\n ++result;\n }\n\n break;\n }\n}\n\nwrite(result);"}, {"source_code": "var n = +readline(),\n x = [],\n h = [],\n count = (n === 1) ? 1 : 2;\n\nfor (var i = 0; i < n; i ++)\n{\n var line = readline().split(' ');\n x[i] = +line[0],\n h[i] = +line[1];\n}\n\nfor (var i = 1; i < n - 1; i ++)\n{\n if (x[i - 1] < x[i] - h[i])\n {\n count ++;\n }\n else if (x[i + 1] > x[i] + h[i])\n {\n x[i] += h[i];\n count ++;\n }\n}\n\nprint(count);\n"}], "negative_code": [{"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = true;\n\n this.solveCase = function() {\n var res , i , j , fl , cn , temp , a , b , c , d ;\n res = 0 ;\n this.arr = this.arr.sort( function( left , right ) { return left.index - right.index ; } ) ;\n a = -2000000000 ;\n b = -2000000000 ;\n aa = 0 ;\n bb = 0 ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tc = this.arr[ i ].index ;\n \td = this.arr[ i ].height ;\n \tif( a < c - d ) {\n \t\ta = c ;\n \t\taa += 1 ;\n \t}\n \telse if( b < c - d ) {\n \t\ta = c ;\n \t\taa += 1 ;\n \t}\n \tif( b < c ) {\n \t\tb = c + d ;\n \t\tbb += 1 ;\n \t}\n \telse if( a < c ) {\n \t\tb = c + d ;\n \t\tbb += 1 ;\n \t}\n \tres = Math.max( res , aa ) ;\n \tres = Math.max( res , bb ) ;\n }\n print( res - 1 );\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i , obj ;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n this.arr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tobj = {} ;\n \tobj.index = irObj.nextInt() ;\n \tobj.height = irObj.nextInt() ;\n this.arr.push( obj ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.brr = [];\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = true;\n \n this.find = function( val , fl ) {\n \tvar lo , hi , mi , res , sz1 , sz2 ;\n \tsz1 = this.brr.length ;\n \tsz2 = this.crr.length ;\n \tlo = 0 ;\n \tif( fl == false ) {\n \t\thi = sz1 - 1 ;\n \t}\n \telse {\n \t\thi = sz2 - 1 ;\n \t}\n \tres = -1 ;\n \twhile( lo <= hi ) {\n \t\tmi = Math.floor( ( lo + hi ) / 2 ) ;\n \t\tif( fl == false ) {\n \t\t\tif( this.brr[ mi ].index < val ) {\n \t\t\t\tlo = mi + 1 ;\n \t\t\t\tres = Math.max( res , mi ) ;\n \t\t\t}\n \t\t\telse {\n \t\t\t\thi = mi - 1 ;\n \t\t\t}\n \t\t}\n \t\telse {\n \t\t\tif( this.crr[ mi ].index + this.crr[ mi ].height < val ) {\n \t\t\t\tlo = mi + 1 ;\n \t\t\t\tres = Math.max( res , mi ) ;\n \t\t\t}\n \t\t\telse {\n \t\t\t\thi = mi - 1 ;\n \t\t\t}\n \t\t}\n \t}\n \tif( res != -1 ) {\n \t\tif( fl == false ) {\n \t\t\tres = this.brr[ res ].arrayIndex ;\n \t\t}\n \t\telse {\n \t\t\tres = this.crr[ res ].arrayIndex ;\n \t\t}\n \t}\n \treturn res ;\n } ;\n\n this.solveCase = function() {\n var res , i , j ;\n res = 0 ;\n this.arr = this.arr.sort( function( left , right ) { return left.index - right.index ; } ) ;\n this.brr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( i == 0 ) {\n \t\tthis.brr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n \telse if( this.arr[ i ].index - this.arr[ i ].height > this.arr[ i - 1 ].index ) {\n \t\tthis.brr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n }\n this.crr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( i == this.n - 1 ) {\n \t\tthis.crr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n \telse if( this.arr[ i ].index + this.arr[ i ].height < this.arr[ i + 1 ].index ) {\n \t\tthis.crr.push( { index : this.arr[ i ].index , height : this.arr[ i ].height , arrayIndex : i } ) ;\n \t}\n }\n for( i = 0 ; i < this.n ; i++ ) {\n \tthis.memo[ i ][ 0 ] = 1 ;\n \tthis.memo[ i ][ 1 ] = 1 ;\n \tif( i > 0 ) {\n \t\tj = this.find( this.arr[ i ].index - this.arr[ i ].height , false ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 0 ] = Math.max( this.memo[ i ][ 0 ] , this.memo[ j ][ 0 ] + 1 ) ;\n \t\t}\n \t\tj = this.find( this.arr[ i ].index - this.arr[ i ].height , true ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 0 ] = Math.max( this.memo[ i ][ 0 ] , this.memo[ j ][ 1 ] + 1 ) ;\n \t\t}\n \t\tj = this.find( this.arr[ i ].index , false ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 1 ] = Math.max( this.memo[ i ][ 1 ] , this.memo[ j ][ 0 ] + 1 ) ;\n \t\t}\n \t\tj = this.find( this.arr[ i ].index , true ) ;\n \t\tif( j != -1 ) {\n \t\t\tthis.memo[ i ][ 1 ] = Math.max( this.memo[ i ][ 1 ] , this.memo[ j ][ 1 ] + 1 ) ;\n \t\t}\n\t \tthis.memo[ i ][ 0 ] = Math.max( this.memo[ i ][ 0 ] , this.memo[ i - 1 ][ 0 ] ) ;\n\t \tthis.memo[ i ][ 1 ] = Math.max( this.memo[ i ][ 1 ] , this.memo[ i - 1 ][ 1 ] ) ;\n\t \tres = Math.max( res , this.memo[ i ][ 0 ] ) ;\n\t \tres = Math.max( res , this.memo[ i ][ 1 ] ) ;\n \t}\n }\n print( res );\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i , obj ;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n this.arr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tobj = {} ;\n \tobj.index = irObj.nextInt() ;\n \tobj.height = irObj.nextInt() ;\n this.arr.push( obj ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.brr = [];\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.idx = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.memo.push( new Array() );\n this.idx.push( new Array() );\n for( j = 0 ; j < 2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.idx[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "function toi(x){return parseInt(x);}\nvar n=+readline();\nvar treex=[];\nvar treeh=[];\nfor(var i=0;i= distance) {\n return FALL.yes;\n }\n else {\n return FALL.maybe;\n }\n }\n \n return FALL.no;\n}\n\nvar Tree = function(data) {\n this.x = +data[0];\n this.h = +data[1];\n};\n\nTree.prototype.calculate = function(leftTree, rightTree) {\n this.left = fallType(this, leftTree);\n this.right = fallType(this, rightTree);\n};\n\nTree.prototype.canFall = function() {\n return this.left === FALL.yes || this.right === FALL.yes;\n};\n\nTree.prototype.cantFall = function() {\n return this.left === FALL.no && this.right === FALL.no;\n};\n\nTree.prototype.maybeFall = function() {\n return this.left === FALL.maybe || this.right === FALL.maybe;\n};\n\nvar trees = [new Tree([-Infinity, 0])];\nfor (var i = 0; i < n; ++i) {\n trees.push(new Tree(readline().split(' ')));\n}\ntrees.push(new Tree([+Infinity, 0]));\n\nfor (var i = 1; i <= n; ++i) {\n trees[i].calculate(trees[i-1], trees[i+1]);\n}\n\nvar result = 0;\nvar state = 0;\n\nfor (var i = 1; i <= n; ++i) {\n switch (state) {\n case 0:\n if (trees[i].canFall()) {\n ++result;\n } else {\n if (trees[i].cantFall()) {\n // nothing to do here\n } else {\n if (trees[i].left = FALL.maybe) {\n ++result;\n } else {\n ++result;\n state = 1;\n }\n }\n }\n break;\n case 1:\n if (trees[i].canFall()) {\n ++result;\n state = 0;\n } else {\n if (trees[i].cantFall()) {\n state = 0;\n } else {\n if (trees[i].right = FALL.no) {\n state = 0;\n } else {\n ++result;\n }\n }\n }\n break;\n }\n}\n\nwrite(result);"}, {"source_code": "var n = +readline();\n\nconst FALL = {\n yes: {},\n maybe: {},\n no: {}\n}\n\nvar fallType = function(fallTree, blockTree) {\n var distance = Math.abs(fallTree.x - blockTree.x);\n \n if (fallTree.h + blockTree.h < distance) {\n return FALL.yes;\n }\n \n if (fallTree.h < distance) {\n if (blockTree.h >= distance) {\n return FALL.yes;\n }\n else {\n return FALL.maybe;\n }\n }\n \n return FALL.no;\n}\n\nvar Tree = function(data) {\n this.x = +data[0];\n this.h = +data[1];\n};\n\nTree.prototype.calculate = function(leftTree, rightTree) {\n this.left = fallType(this, leftTree);\n this.right = fallType(this, rightTree);\n};\n\nTree.prototype.canFall = function() {\n return this.left === FALL.yes || this.right === FALL.yes;\n};\n\nTree.prototype.cantFall = function() {\n return this.left === FALL.no && this.right === FALL.no;\n};\n\nTree.prototype.maybeFall = function() {\n return this.left === FALL.maybe || this.right === FALL.maybe;\n};\n\nvar trees = [new Tree([-Infinity, 0])];\nfor (var i = 0; i < n; ++i) {\n trees.push(new Tree(readline().split(' ')));\n}\ntrees.push([new Tree([+Infinity, 0])]);\n\nfor (var i = 1; i <= n; ++i) {\n trees[i].calculate(trees[i-1], trees[i+1]);\n}\n\nvar result = 0;\nvar state = 0;\n\nfor (var i = 1; i <= n; ++i) {\n switch (state) {\n case 0:\n if (trees[i].canFall()) {\n ++result;\n } else {\n if (trees[i].cantFall()) {\n // nothing to do here\n } else {\n if (trees[i].left = FALL.maybe) {\n ++result;\n } else {\n ++result;\n state = 1;\n }\n }\n }\n break;\n case 1:\n if (trees[i].canFall()) {\n ++result;\n state = 0;\n } else {\n if (trees[i].cantFall()) {\n state = 0;\n } else {\n if (trees[i].right = FALL.no) {\n state = 0;\n } else {\n ++result;\n }\n }\n }\n break;\n }\n}\n\nwrite(result);"}, {"source_code": "var n = +readline(),\n x = [],\n h = [],\n spc = [],\n count = 2;\n\nfor (var i = 0; i < n; i ++)\n{\n var line = readline().split(' ');\n x[i] = +line[0],\n h[i] = +line[1];\n}\n\nfor (var i = 1; i < n - 1; i ++)\n{\n if (x[i - 1] < x[i] - h[i])\n {\n count ++;\n }\n else if (x[i + 1] > x[i] + h[i])\n {\n x[i] += h[i];\n count ++;\n }\n}\n\nprint(count);\n"}], "src_uid": "a850dd88a67a6295823e70e2c5c857c9"} {"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$$$) — 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$$$) — 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": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.question(\"\", function (n) {\n functions();\n})\nfunction functions() {\n rl.question('', function (n) {\n var input = n.split(' ')\n var a = parseInt(input[0]);\n var k = parseInt(input[1]);\n var o = 0;\n var output;\n if (k >= a) {\n output = k - a;\n } else {\n if ((a % 2 == 0 && k % 2 == 0) || (a % 2 != 0 && k % 2 != 0)) {\n output = 0\n } else {\n output = 1\n }\n }\n console.log(output)\n functions()\n })\n}\n\n// function functions() {\n// rl.question('', function (input) {\n// var n = input.split(' ');\n// var x = parseInt(n[0]);\n// var y = parseInt(n[1]);\n// var z = parseInt(n[2]);\n// var a, b, c, bool = false;\n// if (x == y && y >= z) {\n// bool = true;\n// a = x;\n// b = z;\n// c = 1;\n// } else if (x == z && z >= y) {\n// bool = true;\n// b = x;\n// a = y;\n// c = 1;\n// } else if (y == z && z >= x) {\n// bool = true;\n// c = y;\n// b = x;\n// a = 1;\n// } else if (x == y && y == z) {\n// bool = true;\n// a = b = c = x;\n// }\n// if (bool) {\n// console.log('yes')\n// console.log(a, b, c)\n// } else {\n// console.log('no')\n// }\n// // console.log(x == y, x > z, z, y > 2)\n// functions();\n// })\n// }\n// function functions() {\n// rl.question(\"\", function (n) {\n// rl.question(\"\", function (num) {\n// var arr = num.split(' ');\n// var l = [];\n// for (var i = 0; i < n * 2; i++) {\n// for (var j = 0; j < arr.length; j++) {\n// var lhas = l.includes(arr[j])\n// if (!lhas) {\n// l.push(arr[j]);\n//\n// }\n// }\n// }\n// console.log(l.join(' '));\n// functions();\n// });\n// })\n// }\n// rl.question('', function (o) {\n// rl.question('', function (n) {\n// rl.question('', function (a) {\n// rl.question('', function (b) {\n// var s = 0;\n// var sa = a.split(' ');\n// var sb = b.split(' ');\n// // console.log(n, newA, s, sa, sb)\n// for (var i = 0; i < n; i++) {\n// var newA = [];\n// var ai = sa[i] - Math.min.apply(Math, sa)\n// var bi = sb[i] - Math.min.apply(Math, sb)\n// newA.push(ai);\n// newA.push(bi);\n// s += Math.max.apply(Math, newA);\n// }\n// console.log(s)\n// functions();\n// })\n// })\n// })\n// })\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [a, b] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n if (a <= b) {\n console.log(b - a);\n } else if (a % 2 != b % 2) {\n console.log(1);\n } else {\n console.log(0);\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.split(/\\n/);\n main(); \n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const t = Number(readLine())\n for (let _ = 0; _ < t; _++) {\n const [n, k] = readLine().split(/\\s/).map(Number)\n console.log(n < k ? k - n : (n - k) % 2)\n }\n}\n\n"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n a = a || 0;\n b = b || (this.length - 1);\n let prev = a;\n for (let i = a; i <= b; i++) {\n if (i == b || fn(this[i], this[i + 1])) {\n arr.push(this.slice(prev, i + 1));\n prev = i + 1;\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nfunction inv(b, m) {\n for (var a = m, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + m) % m;\n}\n\n// let MOD = 1e9 + 7\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;\n let t = $()\n while (t--) {\n let [n, k] = $(2)\n if (n <= k) log(k - n);\n else if (n % 2 == k % 2) log(0);\n else log(1);\n }\n}\n"}, {"source_code": "let _input = '';\nlet lineNumberToRead = -1;\nlet outputArray = [];\nfunction readLine() {\n lineNumberToRead += 1;\n return _input[lineNumberToRead];\n}\n\nconst l = readLine;\n\nfunction flush() {\n console.log(outputArray.join(''));\n outputArray = [];\n}\n\nfunction out(s) {\n outputArray.push(s);\n}\nfunction ria() {\n return l().split(' ').map((x) => +x);\n}\nfunction processInput() {\n const t = +l();\n\n for (let i = 1; i <= t; i += 1) {\n solveTestCase(i);\n }\n\n flush();\n}\n\nfunction solveTestCase(testCaseNumber) {\n const [n, k] = ria();\n\n if(n < k) {\n out(k - n + \"\\n\");\n } else {\n out(((n%2 == k%2) ? 0 : 1) + \"\\n\");\n }\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', (data) => { _input += data; });\nprocess.stdin.on('end', () => {\n _input = _input.trim().split('\\n').map((x) => x.trim());\n processInput();\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probA();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n let [n,k] = readline().split(' ');\n n = pi(n);\n k = pi(k);\n\n if(n < k)\n console.log(k-n);\n else{\n if((n+k) % 2 === 0){\n console.log(0);\n }else{\n console.log(1);\n }\n }\n }\n}\n\nfunction probB(){\n let t = pi(readline());\n\n while(t > 0){\n t--;\n let a = readline().split(' ');\n let b = readline().split(' ');\n\n a[0] = pi(a[0]);\n a[1] = pi(a[1]);\n a[2] = pi(a[2]);\n\n b[0] = pi(b[0]);\n b[1] = pi(b[1]);\n b[2] = pi(b[2]);\n\n let maxSum = 0;\n if(b[2] - (a[0] + a[2]) > 0){\n b[2] = b[2] - (a[0]+a[2]);\n a[0] = 0;\n a[2] = 0;\n }else if(b[2] - a[0] > 0){\n a[2] = a[2] - (b[2] - a[0]);\n b[2] = 0;\n a[0] = 0;\n }else{\n a[0] -= b[2];\n b[2] = 0;\n }\n\n if(a[2] > b[1])\n console.log((b[1] - b[2]) * 2)\n else\n console.log((a[2]-b[2]) * 2);\n\n }\n}\n\nfunction probC(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let a = readline().split(' ');\n let x = JSON.parse(JSON.stringify(a));\n\n x.sort((a,b) => pi(a) - pi(b));\n let res = true;\n for(let i = 0; i < n; i++){\n if(x[i] !== a[i]){\n if(pi(a[i]) % pi(x[0]) !== 0){\n res = false;\n break;\n }\n }\n }\n\n if(res)\n console.log('yes');\n else\n console.log('no');\n }\n}"}, {"source_code": "var t = +(readline());\nwhile (t--) {\n var inputs = readline().split(' ');\n var n = +inputs[0], k = +inputs[1];\n if (n < k) {\n print(k-n);\n } else if (n%2==k%2) print(0);\n else print(1); \n}\n"}, {"source_code": "var t = parseInt(readline());\n\nwhile(t--){\n a = readline().split(' ');\n n = parseInt(a[0]);\n k = parseInt(a[1]);\n \n if (n < k)\n print(k - n);\n else if (n % 2 == k % 2)\n print(0);\n else \n print(1);\n}"}], "negative_code": [{"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.question(\"\", function (n) {\n functions();\n})\nfunction functions() {\n rl.question('', function (n) {\n var input = n.split(' ')\n var a = input[0];\n var k = input[1];\n var o = 0;\n var output;\n if (k >= a) {\n output = k - a;\n } else {\n if ((a % 2 == 0 && k % 2 == 0) || (a % 2 != 0 && k % 2 != 0)) {\n output = 0\n } else {\n output = 1\n }\n }\n console.log(output)\n functions()\n })\n}\n\n// function functions() {\n// rl.question('', function (input) {\n// var n = input.split(' ');\n// var x = parseInt(n[0]);\n// var y = parseInt(n[1]);\n// var z = parseInt(n[2]);\n// var a, b, c, bool = false;\n// if (x == y && y >= z) {\n// bool = true;\n// a = x;\n// b = z;\n// c = 1;\n// } else if (x == z && z >= y) {\n// bool = true;\n// b = x;\n// a = y;\n// c = 1;\n// } else if (y == z && z >= x) {\n// bool = true;\n// c = y;\n// b = x;\n// a = 1;\n// } else if (x == y && y == z) {\n// bool = true;\n// a = b = c = x;\n// }\n// if (bool) {\n// console.log('yes')\n// console.log(a, b, c)\n// } else {\n// console.log('no')\n// }\n// // console.log(x == y, x > z, z, y > 2)\n// functions();\n// })\n// }\n// function functions() {\n// rl.question(\"\", function (n) {\n// rl.question(\"\", function (num) {\n// var arr = num.split(' ');\n// var l = [];\n// for (var i = 0; i < n * 2; i++) {\n// for (var j = 0; j < arr.length; j++) {\n// var lhas = l.includes(arr[j])\n// if (!lhas) {\n// l.push(arr[j]);\n//\n// }\n// }\n// }\n// console.log(l.join(' '));\n// functions();\n// });\n// })\n// }\n// rl.question('', function (o) {\n// rl.question('', function (n) {\n// rl.question('', function (a) {\n// rl.question('', function (b) {\n// var s = 0;\n// var sa = a.split(' ');\n// var sb = b.split(' ');\n// // console.log(n, newA, s, sa, sb)\n// for (var i = 0; i < n; i++) {\n// var newA = [];\n// var ai = sa[i] - Math.min.apply(Math, sa)\n// var bi = sb[i] - Math.min.apply(Math, sb)\n// newA.push(ai);\n// newA.push(bi);\n// s += Math.max.apply(Math, newA);\n// }\n// console.log(s)\n// functions();\n// })\n// })\n// })\n// })\n"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n a = a || 0;\n b = b || (this.length - 1);\n let prev = a;\n for (let i = a; i <= b; i++) {\n if (i == b || fn(this[i], this[i + 1])) {\n arr.push(this.slice(prev, i + 1));\n prev = i + 1;\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nfunction inv(b, m) {\n for (var a = m, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + m) % m;\n}\n\n// let MOD = 1e9 + 7\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;\n let t = $()\n while (t--) {\n let [n, k] = $(2)\n if (n <= k) log(k - n);\n else if (n % 2 == k % 2) log(0);\n else log(1);\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probA(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n let [n,k] = readline().split(' ');\n n = pi(n);\n k = pi(k);\n\n if((n+k) % 2 === 0){\n if(n === 0)\n console.log(k);\n else\n console.log(0);\n }\n else\n console.log(Math.abs(n-k));\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probA(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n let [n,k] = readline().split(' ');\n n = pi(n);\n k = pi(k);\n\n if(n < k)\n console.log(k-n);\n else{\n if((n+k) % 2 === 0){\n console.log(0);\n }else{\n console.log(n-k);\n }\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probA(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n let [n,k] = readline().split(' ');\n n = pi(n);\n k = pi(k);\n\n if((n+k) % 2 === 0 && n > k){\n console.log(0);\n }else{\n console.log(Math.abs(n-k));\n }\n }\n}"}], "src_uid": "f98d1d426f68241bad437eb221f617f4"} {"nl": {"description": "Mishka got an integer array $$$a$$$ of length $$$n$$$ as a birthday present (what a surprise!).Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it \"Mishka's Adjacent Replacements Algorithm\". This algorithm can be represented as a sequence of steps: Replace each occurrence of $$$1$$$ in the array $$$a$$$ with $$$2$$$; Replace each occurrence of $$$2$$$ in the array $$$a$$$ with $$$1$$$; Replace each occurrence of $$$3$$$ in the array $$$a$$$ with $$$4$$$; Replace each occurrence of $$$4$$$ in the array $$$a$$$ with $$$3$$$; Replace each occurrence of $$$5$$$ in the array $$$a$$$ with $$$6$$$; Replace each occurrence of $$$6$$$ in the array $$$a$$$ with $$$5$$$; $$$\\dots$$$ Replace each occurrence of $$$10^9 - 1$$$ in the array $$$a$$$ with $$$10^9$$$; Replace each occurrence of $$$10^9$$$ in the array $$$a$$$ with $$$10^9 - 1$$$. Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($$$2i - 1, 2i$$$) for each $$$i \\in\\{1, 2, \\ldots, 5 \\cdot 10^8\\}$$$ as described above.For example, for the array $$$a = [1, 2, 4, 5, 10]$$$, the following sequence of arrays represents the algorithm: $$$[1, 2, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$1$$$ with $$$2$$$) $$$\\rightarrow$$$ $$$[2, 2, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$2$$$ with $$$1$$$) $$$\\rightarrow$$$ $$$[1, 1, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$3$$$ with $$$4$$$) $$$\\rightarrow$$$ $$$[1, 1, 4, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$4$$$ with $$$3$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$5$$$ with $$$6$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 6, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$6$$$ with $$$5$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\\rightarrow$$$ $$$\\dots$$$ $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\\rightarrow$$$ (replace all occurrences of $$$10$$$ with $$$9$$$) $$$\\rightarrow$$$ $$$[1, 1, 3, 5, 9]$$$. The later steps of the algorithm do not change the array.Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.", "input_spec": "The first line of the input contains one integer number $$$n$$$ ($$$1 \\le n \\le 1000$$$) — the number of elements in Mishka's birthday present (surprisingly, an array). The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) — the elements of the array.", "output_spec": "Print $$$n$$$ integers — $$$b_1, b_2, \\dots, b_n$$$, where $$$b_i$$$ is the final value of the $$$i$$$-th element of the array after applying \"Mishka's Adjacent Replacements Algorithm\" to the array $$$a$$$. Note that you cannot change the order of elements in the array.", "sample_inputs": ["5\n1 2 4 5 10", "10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000"], "sample_outputs": ["1 1 3 5 9", "9999 9 50605065 1 5 89 5 999999999 60506055 999999999"], "notes": "NoteThe first example is described in the problem statement."}, "positive_code": [{"source_code": "\nfunction main() {\n const is = new Scanner();\n const n = is.nextInt();\n const array = is.nextArray();\n for (let i = 0; i < n; i += 1) {\n array[i] = parseInt(array[i], 10);\n }\n\n let tmp;\n for (let i = 0; i < n; i += 1) {\n tmp = array[i];\n for (let j = 0; j < n; j += 1) {\n if (array[j] === tmp && array[j] % 2 === 0) {\n array[j] = tmp - 1;\n }\n }\n }\n\n console.log(array.join(' '));\n}\n\n/*\n * Api Scanner\n */\n\nclass Scanner {\n constructor() {\n this.index = 0;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n\n nextLine() {\n return this.lines[this.index++]; // eslint-disable-line\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray() {\n return this.nextLine().split(' ');\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (input) => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}, {"source_code": "var readline = (()=>{\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n \n let inputString = '';\n let currentLine = 0;\n \n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n \n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n });\t\n \n function readline() {\n return inputString[currentLine++];\n }\n return readline;\n})()\n \n\nfunction main() {\n\treadline();\n\tconsole.log(((str)=>\n\t\tstr.split(\" \").map(item=>item%2===0?item-1:item).join(\" \")\n\t)(readline()));\n}\n"}, {"source_code": "var readline = (()=>{\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n \n let inputString = '';\n let currentLine = 0;\n \n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n \n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n });\t\n \n function readline() {\n return inputString[currentLine++];\n }\n return readline;\n})()\n \n\nfunction main() {\n\treadline();\n\tconsole.log(((str)=>{\n\t\tlet arr=str.split(\" \");\n\t\tarr = arr.reduce((acc,c,i)=>{\n\t\t\tlet n = c%2==0?c-1:c;\n\t\t\tif(acc[n]==null){\n\t\t\t\tacc[n] = [];\n\t\t\t};\n\t\t\tacc[n].push(i);\n\t\t\treturn acc;\n\t\t}, {});\n\t\treturn Object.keys(arr).reduce((acc,e,i)=>{\n\t\t\tlet c = arr[e];\n\t\t\tc.map(t=>acc[t]=e);\n\t\t\treturn acc;\n\t\t},[]).join(\" \")\n\t})(readline()));\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var list = nextIntArray();\n for(var i = 0; i < N; i++){\n list[i] -= (list[i] % 2 == 0) ? 1 : 0;\n }\n myout(myconv(list, 8));\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const a = d.split(' ').map(Number);\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] % 2 === 0) {\n a[i] = a[i] - 1;\n }\n }\n\n console.log(a.join(' '));\n\n c++;\n});\n"}, {"source_code": "let input = [];\n \nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n\nRL.on('line', (line) => {\n input.push(line);\n});\n\nRL.on('close', () => {\n let n = parseInt(input[0]);\n let num = [];\n input[1].split(' ').forEach(i => num.push(parseInt(i)));\n\n for(let i = 0; i < n; i++){\n for(let j = i; j < n; j++){\n if(num[i] === num[j] && num[j] % 2 === 0)\n num[j]--;\n }\n }\n\n let answer = ''; num.forEach( i => answer+= `${i} `)\n console.log(answer);\n});\n\n"}, {"source_code": "n=readline()\nprint(readline().split(' ').map(function(x){return x-(+x+1)%2}).join(' '))"}, {"source_code": "var n = (+ readline ());\nvar a = readline ();\na = a.trim ().split ( ' ' );\nvar i;\nfor ( i = 0; i < n; i ++ ) a [ i ] = Number ( a [ i ] );\nfor ( i = 0; i < n; i ++ ) {\n if ( a [ i ] % 2 == 0 ) a [ i ] --;\n}\nprint ( a.join ( ' ' ) );\n"}, {"source_code": "var elements = readline();\nelements = readline().split(' ').map(e => e % 2 === 0 ? e - 1 : e).join(' ');\nprint(elements);"}, {"source_code": "//var h = readline()\nvar n = parseInt(readline())\nvar nums = (readline().split(' '))\nvar i = 0\nwhile (n--) {\n var a = nums[i] - 1\n var b = parseInt((a / 2), 10)\n var c = b * 2\n var res = c + 1\n write(res, ' ')\n i++\n}"}, {"source_code": "var n = parseInt(readline())\nvar nums = (readline().split(' '))\nvar i = 0\nwhile (n--) {\n var a = nums[i] - 1\n var b = parseInt((a / 2), 10)\n var c = b * 2\n var res = c + 1\n print(res)\n i++\n}"}, {"source_code": "// var print = require('lol-io').print\n// var readline = require('lol-io').readline\n\nreadline();\n\nvar arr = readline().split(' ');\n\nvar answer = '';\n\narr.forEach(nr => {\n if(!(nr % 2)) {\n answer += nr - 1;\n } else {\n answer += nr;\n }\n answer += ' ';\n});\n\nprint(answer);"}, {"source_code": "var n = readline();\nvar a = readline().split(' ').map(function(el) {\n return parseInt(el, 10);\n});\n\nfor (var i of a) {\n if (i % 2 == 0) {\n write(i - 1,' ');\n }\n else {\n write(i, ' ')\n }\n}\n\n"}], "negative_code": [{"source_code": "var readline = (()=>{\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n \n let inputString = '';\n let currentLine = 0;\n \n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n \n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n });\t\n \n function readline() {\n return inputString[currentLine++];\n }\n return readline;\n})()\n \n\nfunction main() {\n\treadline();\n\tconsole.log(((str)=>{\n\t\tlet arr=str.split(\" \");\n\t\tarr = arr.reduce((acc,c,i)=>{\n\t\t\tlet n = c%2===0?c-1:c;\n\t\t\tif(acc[n]==null){\n\t\t\t\tacc[n] = [];\n\t\t\t}\n\t\t\tacc[n].push(i);\n\t\t\treturn acc;\n\t\t}, {});\n\t\treturn Object.keys(arr).reduce((acc,e,i)=>{\n\t\t\tlet c = arr[e];\n\t\t\tconsole.log(e);\n\t\t\tc.map(t=>acc[t]=e);\n\t\t\treturn acc;\n\t\t},[]).join(\" \")\n\t})(readline()));\n}\n"}], "src_uid": "d00696cb27c679dda6e2e29314a8432b"} {"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$$$) — 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$$$) — 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 input = `4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`\n\nlet input = ''\n\n// process.stdin.on('data', str => input += str)\nprocess.stdin.on('end', () => {\n\t// f = 0\n\t// const { EOL } = require('os')\n\t// const lines = input.split(EOL) /*your input text, split by lines*/\n\t// main(input, lines)\n})\n\nconst readline = require('readline').createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\n\nlet f = 0\n// multi line input\nreadline.on('line', l => {\n\tif (!f) {\n\t\tf = 1\n\t\treturn\n\t}\n\t[n, x] = l.split(' ').map(x => +x)\n\t// console.log(Math.ceil((n - 3) / x) + 2)\n\t// console.log(n, x)\n\t// return\n\tif (n <= 2) {\n\t\tconsole.log(1)\n\t}\n\telse {\n\t\tconsole.log(Math.floor((n - 3) / x + 2))\n\t}\n\t// console.log(line);\n});\n\n// function main() {\n// \tinput.split('\\n').slice(1).map(l => {\n// \t\t[n, x] = l.split(' ').map(x => +x)\n// \t\tconsole.log(Math.ceil((n + 2) / x))\n// \t})\n// }\n\n// process.on('SIGINT', function () {\n// \tmain()\n// \tprocess.exit(0);\n// });\n\n// main(`4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`)"}, {"source_code": "// https://codeforces.com/problemset/problem/1426/A\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet data = [];\nrl.on('line', (input) => {\n data.push(input);\n});\n\nrl.on('close', () => {\n solve(data);\n});\n\nfunction solve(data) {\n\n for (let i = 1; i < data.length; i++) {\n [n, x] = data[i].split(\" \");\n\n if (n <= 2) {\n\n // first floor\n console.log(1);\n\n } else {\n\n floor = 0;\n while (true) {\n lower = floor*x+3;\n upper = (floor+1)*x+2;\n if (n >= lower && n <= upper) {\n console.log(floor + 2);\n break;\n }\n floor++;\n }\n\n }\n }\n\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \n \n \nfunction main() {\n let t = readLine();\n t = parseInt(t);\n \n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let a = parseInt(line[0]);\n let b = parseInt(line[1]);\n let res = parseInt(line[1]);\n if (a == 1 || a== 2)\n {\n console.log(1);\n }\n else{\n a -= 2;\n res = a/b;\n res = Math.floor(res)\n if(a%b===0)\n {\n console.log(res+1);\n }\n else\n {\n console.log(res+2);\n }\n }\n }\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n var T = readLine();\n var loop = 1010;\n while (T--) {\n var arr = readLine();\n arr = arr.split(\" \").map(Number);\n var n = arr[0];\n var x = arr[1];\n var result = 0;\n for (let i = 1; i < loop; i++) {\n if (n <= 2) {\n result = 1;\n break;\n }\n result = Math.floor((n - 3) / x + 2);\n }\n console.log(result);\n }\n}\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet data = [];\n\nrl.on(\"line\", (line) => {\n data.push(line);\n});\n\nrl.on(\"close\", () => {\n floor(data);\n})\n\nfunction floor(data) {\n for (let i = 1; i < data.length; i++) {\n [n, x] = data[i].split(\" \").map(Number);\n \n let currentFloor = 1;\n\n if (n > 2) {\n currentFloor = Math.ceil((n - 2) / x) + 1;\n }\n\n console.log(currentFloor);\n }\n}"}, {"source_code": "\nlet _inputLines;\nlet _lineNumber = 0;\nlet inputReader = _inputReader ();\n\nfunction _main() {\n\t\n\t_inputLines = _inputData.trim().split('\\n').map((string) => {\n\t\treturn string.trim();\n\t});;\n\t \n\t\n\t//let [a,b] = inputReader.readNumberArray();\n\tlet noOfTestCases = inputReader.readNumber();\n\t\n\t//console.log(noOfTestCases,typeof noOfTestCases);\n\twhile(noOfTestCases--){\n\t let [a,b] = inputReader.readNumberArray();\n\t let count = 1;\n\t if(a<=2){\n\t console.log(1);\n\t continue;\n\t }\n\t let floor;\n\t if((a-2)%b===0)\n\t floor = (a-2)/b +1;\n\t else\n\t floor = Math.ceil((a-2)/b)+1;\n\t console.log(floor);\n\t \n\t}\n\n}\n\nvar _inputData = '';\nfunction cacheInput(data) {\n\t_inputData += data;\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', cacheInput).on('end', _main);\n\nfunction _inputReader () {\n\tfunction readNumber(){\n\t\treturn Number(_inputLines[_lineNumber++]);\n\t}\n\t\t\n\tfunction readNumberArray(){\n\t\treturn _inputLines[_lineNumber++].split(' ').map(val => Number(val));\n\t}\n\t\t\n\t\n\treturn {\n\t\treadNumber,\n\t\treadNumberArray,\n\t}\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n let [target, flats] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n if (target <= 2) console.log(1);\n else if (target >= 3 && target <= flats) console.log(2);\n else {\n target = target - (2 + flats);\n let result = Math.floor(target / flats);\n if (target % flats !== 0) result += 1;\n console.log(result + 2);\n }\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n↑入力 ↓出力');\n Main();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var one = nextIntArray();\n var N = one[0];\n var X = one[1];\n if(N < 3){\n output[i] = 1;\n }else{\n var count = 0;\n while(true){\n if(3 + count * X <= N && N <= (count + 1) * X + 2){\n output[i] = count + 2;\n break;\n }\n count++;\n }\n }\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n\nfunction print(thing) {\n console.log(thing);\n}\nconst getLine = (function() {\n const getLineGen = (async function*() {\n for await (const line of rl) {\n yield line;\n }\n })();\n return async() => ((await getLineGen.next()).value);\n})();\n\nconst main = async() => {\n let t = Number(await getLine());\n for (test = 0; test < t; test++) {\n let raw = (await getLine()).split(\" \");\n n = Number(raw[0]);\n x = Number(raw[1]);\n if (n <= 2) {\n print(1);\n } else {\n print((Math.floor((n - 3) / x)) + 2);\n }\n }\n process.exit(0);\n};\n\nmain();"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn, init) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);\n if (b < a) return [];\n let arr = Array(b - a + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => gt[n] * rgt[k] * rgt[n - k] % MOD;\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n// let p = [2, 3, 5];\n// for (let i = 6; i < 1e5; i += 6) {\n// let j, x = i + 1;\n// for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;\n// if (x % p[j] != 0) p.push(x);\n// x = i + 5;\n// for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;\n// if (x % p[j] != 0) p.push(x);\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let t = $()\n while (t--) {\n let n = $(), x = $()\n log(max(0, Math.ceil((n - 2) / x)) + 1);\n }\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction solution(n, x){\n return n === 1 ? 1 : Math.floor((n - 3) / x) + 2;\n}\n\nfunction main() {\n const N = parseInt(readline());\n \n for(let i = 0; i < N; i++){\n const line = readline().split(' ').map(item => parseInt(item));\n console.log(solution(line[0], line[1]));\n }\n}"}, {"source_code": "function main(){\n var ncases = +readline();\n for(var i = 0; i < ncases; ++i){\n var input = readline().split(' ');\n var res = Math.ceil((+input[0] - 2) / +input[1]) +1;\n print(res || 1);\n }\n}\n\nmain();"}, {"source_code": "var t = Number(readline());\nwhile(t--){\n var ln = readline().split(\" \");\n var n = Number(ln[0]),x = Number(ln[1]);\n if(n<=2)print(1);\n else print(parseInt((n-2)/x)+((n-2)%x>0)+1);\n}"}, {"source_code": "var ಠ_ಠ = Number(readline());\nwhile(ಠ_ಠ--){\n var ln = readline().split(\" \");\n var n = Number(ln[0]),x = Number(ln[1]);\n if(n<=2)print(1);\n else print(parseInt((n-2)/x)+((n-2)%x>0)+1);\n}"}, {"source_code": "var t = Number( readline() );\nfor(var i=0; iNumber(a));\n print((r[0]<3)?1:Math.floor((r[0]-3)/r[1]+2));\n}\n"}, {"source_code": "var t = parseInt(readline());\nfor (var i = 0; i < t; i++) {\n var params = readline();\n var n = parseInt(params.split(\" \")[0]);\n var apts = parseInt(params.split(\" \")[1]);\n var floor = 1;\n if (n > 2) {\n floor = Math.ceil(parseFloat(n - 2) / apts) + 1;\n }\n\n print(floor);\n}\n"}, {"source_code": "function int(v) {\n return parseInt(v)\n}\n\nvar t = int(readline())\n\nwhile(t--) {\n var a = readline().split(' ').map(int)\n\n var n = a[0], x = a[1]\n \n if(n == 1 || n == 2) {\n print(1)\n }else {\n n -= 2;\n print(1 + Math.ceil(n / x))\n }\n \n \n}"}, {"source_code": "var rr=readline()\n\n\n//var i=0;\nfor(var j=0;jpetyaApartment)&&i===0){\nFloorPetya=i+1\nprint(FloorPetya)\n\nbreak;\n\n}\nif(i!==0){\nNewFloor+=otherFloor\n\n}\nif(NewFloor==petyaApartment||NewFloor>petyaApartment){\n\nFloorPetya=i+1\nprint(FloorPetya)\n\nbreak;\n\n}\n \n}\n}\n//print(FloorPetya)\n\n"}, {"source_code": "var tc = parseInt(readline());\n\nwhile(tc--){\n var ar = readline().split(' ').map( x => parseInt(x));\n var n = ar[0];\n var x = ar[1];\n\n if(n < 3){\n print(1);\n }else{\n print(Math.ceil((n+(x-2))/x));\n }\n}"}, {"source_code": "var tc = parseInt(readline());\n\nwhile (tc--) {\n\tvar numbers = readline().split(' '),\n\t\tn = parseInt(numbers[0]),\n\t\tx = parseInt(numbers[1]);\n\n\tvar ans = 1;\n\tn -= 2;\n\twhile (n > 0) {\n\t\tn -= x;\n\t\tans++;\n\t}\n\n\tprint(ans);\n}\n"}, {"source_code": "var testcases = readline();\n\nfor(var i = 0 ; i < testcases ; i++) {\n var details = readline().split(' ').map(Number)\n var apartmentNumber = details[0];\n var x = details[1];\n var y = Math.ceil(apartmentNumber/x) + 1\n var temp = 2;\n var floor = 1;\n while(y--){\n if(temp >= apartmentNumber){\n print(floor);\n break;\n }\n else{\n temp = temp + x;\n floor++;\n }\n }\n}"}, {"source_code": "var t = +readline();\nvar inp;\n\nfor(var i = 0; i < t; i++) {\n inp = readline().split(\" \").map(Number);\n\n if (inp[0] <= 2) {\n print(1);\n } else {\n print(Math.ceil((inp[0] - 2) / inp[1]) + 1);\n }\n}\n"}], "negative_code": [{"source_code": "// let input = `4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`\n\nlet input = ''\n\n// process.stdin.on('data', str => input += str)\n// process.stdin.on('end', () => {\n// \tconst { EOL } = require('os')\n// \tconst lines = input.split(EOL) /*your input text, split by lines*/\n// \tmain(input, lines)\n// })\n\nconst readline = require('readline').createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\nlet f = 0\n// multi line input\nreadline.on('line', l => {\n\tif (!f) {\n\t\tf = 1\n\t\treturn\n\t}\n\t[n, x] = l.split(' ').map(x => +x)\n\tconsole.log(Math.ceil((n + 2) / x))\n\t// console.log(line);\n});\n\nfunction main() {\n\tinput.split('\\n').slice(1).map(l => {\n\t\t[n, x] = l.split(' ').map(x => +x)\n\t\tconsole.log(Math.ceil((n + 2) / x))\n\t})\n}\n\n// process.on('SIGINT', function () {\n// \tmain()\n// \tprocess.exit(0);\n// });\n\n// main(`4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`)"}, {"source_code": "// let input = `4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`\n\nlet input = ''\n\n// process.stdin.on('data', str => input += str)\nprocess.stdin.on('end', () => {\n\tf = 0\n\t// const { EOL } = require('os')\n\t// const lines = input.split(EOL) /*your input text, split by lines*/\n\t// main(input, lines)\n})\n\nconst readline = require('readline').createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\n\nlet f = 0\n// multi line input\nreadline.on('line', l => {\n\tif (!f) {\n\t\tf = 1\n\t\treturn\n\t}\n\t[n, x] = l.split(' ').map(x => +x)\n\t// console.log(Math.ceil((n - 3) / x) + 2)\n\tif (n <= 2) {\n\t\tconsole.log(1)\n\t}\n\telse {\n\t\tconsole.log(Math.ceil((n + 2) / x))\n\t}\n\t// console.log(line);\n});\n\n// function main() {\n// \tinput.split('\\n').slice(1).map(l => {\n// \t\t[n, x] = l.split(' ').map(x => +x)\n// \t\tconsole.log(Math.ceil((n + 2) / x))\n// \t})\n// }\n\n// process.on('SIGINT', function () {\n// \tmain()\n// \tprocess.exit(0);\n// });\n\n// main(`4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`)"}, {"source_code": "let input = ''\nprocess.stdin.on('data', str => input += str)\nprocess.stdin.on('end', () => {\n\tconst { EOL } = require('os')\n\tconst lines = input.split(EOL) /*your input text, split by lines*/\n\tmain(input, lines)\n})\n\nfunction main(input) {\n\tinput.split('\\n').slice(1).map(l => {\n\t\t[n, x] = l.split(' ').map(x => +x)\n\t\tconsole.log(Math.ceil((n + 2) / x))\n\t})\n}\n\n// main(`4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`)"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \n \n \nfunction main() {\n let t = readLine();\n t = parseInt(t);\n \n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let a = parseInt(line[0]);\n let b = parseInt(line[1]);\n if (a == 1 || a == 2)\n {\n console.log(1);\n }\n else{\n a /= b;\n if(a%b===0)\n {\n console.log(Math.ceil(a));\n }\n else\n {\n console.log(Math.ceil(a+1));\n }\n }\n }\n}"}, {"source_code": "\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n\n\nfunction main() {\n let t = readLine();\n t = parseInt(t);\n\n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let a = parseInt(line[0]);\n let b = parseInt(line[1]);\n if (a == 1 || a == 2)\n {\n console.log(1);\n }\n else{\n a /= b;\n if(a%b===0)\n {\n console.log(a);\n }\n else\n {\n console.log(a+1);\n }\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \n \n \nfunction main() {\n let t = readLine();\n t = parseInt(t);\n \n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let a = parseInt(line[0]);\n let b = parseInt(line[1]);\n if (a == 1 || a == 2)\n {\n console.log(1);\n }\n else{\n a -= 2;\n a /= b;\n if(a%b===0)\n {\n console.log(Math.round(a));\n }\n else\n {\n console.log(Math.round(a+1));\n }\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \n \n \nfunction main() {\n let t = readLine();\n t = parseInt(t);\n \n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let a = parseInt(line[0]);\n \n let b = parseInt(line[1]);\n if (a < 3)\n {\n console.log(1);\n }\n else{\n a -= 2;\n a /= b;\n if(a%b===0)\n {\n console.log(Math.round(a+1));\n }\n else\n {\n console.log(Math.round(a+2));\n }\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \n \n \nfunction main() {\n let t = readLine();\n t = parseInt(t);\n \n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let a = parseInt(line[0]);\n let b = parseInt(line[1]);\n if (a == 1 || a == 2)\n {\n console.log(1);\n }\n else{\n a /= b;\n if(a%b===0)\n {\n console.log(Math.round(a));\n }\n else\n {\n console.log(Math.round(a+1));\n }\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \n \n \nfunction main() {\n let t = readLine();\n t = parseInt(t);\n \n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let a = parseInt(line[0]);\n \n let b = parseInt(line[1]);\n if (a == 1 || a== 2)\n {\n console.log(1);\n }\n else{\n a -= 2;\n a /= b;\n if(a%b===0)\n {\n console.log(Math.round(a+1));\n }\n else\n {\n console.log(Math.round(a+2));\n }\n }\n }\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n var T = readLine();\n var loop = 1010;\n while (T--) {\n var arr = readLine();\n arr = arr.split(\" \").map(Number);\n var n = arr[0];\n var x = arr[1];\n var result = 0;\n for (let i = 1; i < loop; i++) {\n if (n <= 2) {\n result = 1;\n }\n result = (n - 3) / x + 2;\n }\n console.log(Math.floor(result));\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n var T = readLine();\n var loop = 1010;\n while (T--) {\n var arr = readLine();\n arr = arr.split(\" \").map(Number);\n var n = arr[0];\n var x = arr[1];\n var result = 0;\n for (let i = 0; i < loop; i++) {\n if (n <= 2) {\n result = 1;\n }\n result = (n - 3) / x + 2;\n }\n console.log(Math.floor(result));\n }\n}\n"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn, init) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);\n if (b < a) return [];\n let arr = Array(b - a + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => gt[n] * rgt[k] * rgt[n - k] % MOD;\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n// let p = [2, 3, 5];\n// for (let i = 6; i < 1e5; i += 6) {\n// let j, x = i + 1;\n// for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;\n// if (x % p[j] != 0) p.push(x);\n// x = i + 5;\n// for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;\n// if (x % p[j] != 0) p.push(x);\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let t = $()\n while (t--) {\n let n = $(), x = $()\n log(Math.ceil((n - 2) / x) + 1);\n }\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction solution(n, x){\n return Math.floor((n - 3) / x) + 2;\n}\n\nfunction main() {\n const N = parseInt(readline());\n \n for(let i = 0; i < N; i++){\n const line = readline().split(' ').map(item => parseInt(item));\n console.log(solution(line[0], line[1]));\n }\n}"}, {"source_code": "// let input = `4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`\n\nlet input = ''\n\n// process.stdin.on('data', str => input += str)\nprocess.stdin.on('end', () => {\n\tf = 0\n\t// const { EOL } = require('os')\n\t// const lines = input.split(EOL) /*your input text, split by lines*/\n\t// main(input, lines)\n})\n\nconst readline = require('readline').createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\n\nlet f = 0\n// multi line input\nreadline.on('line', l => {\n\tif (!f) {\n\t\tf = 1\n\t\treturn\n\t}\n\t[n, x] = l.split(' ').map(x => +x)\n\t// console.log(Math.ceil((n - 3) / x) + 2)\n\tif (n <= 2) {\n\t\treturn 1\n\t}\n\tconsole.log(Math.ceil((n + 2) / x))\n\t// console.log(line);\n});\n\n// function main() {\n// \tinput.split('\\n').slice(1).map(l => {\n// \t\t[n, x] = l.split(' ').map(x => +x)\n// \t\tconsole.log(Math.ceil((n + 2) / x))\n// \t})\n// }\n\n// process.on('SIGINT', function () {\n// \tmain()\n// \tprocess.exit(0);\n// });\n\n// main(`4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`)"}, {"source_code": "// let input = `4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`\n\nlet input = ''\n\n// process.stdin.on('data', str => input += str)\nprocess.stdin.on('end', () => {\n\t// f = 0\n\t// const { EOL } = require('os')\n\t// const lines = input.split(EOL) /*your input text, split by lines*/\n\t// main(input, lines)\n})\n\nconst readline = require('readline').createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\n\nlet f = 0\n// multi line input\nreadline.on('line', l => {\n\tif (!f) {\n\t\tf = 1\n\t\treturn\n\t}\n\t[n, x] = l.split(' ').map(x => +x)\n\t// console.log(Math.ceil((n - 3) / x) + 2)\n\t// console.log(n, x)\n\t// return\n\tif (n <= 2) {\n\t\tconsole.log(1)\n\t}\n\telse {\n\t\tconsole.log(Math.ceil((n - 3) / x) + 2)\n\t}\n\t// console.log(line);\n});\n\n// function main() {\n// \tinput.split('\\n').slice(1).map(l => {\n// \t\t[n, x] = l.split(' ').map(x => +x)\n// \t\tconsole.log(Math.ceil((n + 2) / x))\n// \t})\n// }\n\n// process.on('SIGINT', function () {\n// \tmain()\n// \tprocess.exit(0);\n// });\n\n// main(`4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`)"}, {"source_code": "// let input = `4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`\n\nlet input = ''\n\n// process.stdin.on('data', str => input += str)\nprocess.stdin.on('end', () => {\n\tsetTimeout(() => f = 0)\n\t// const { EOL } = require('os')\n\t// const lines = input.split(EOL) /*your input text, split by lines*/\n\t// main(input, lines)\n})\n\nconst readline = require('readline').createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\n\nlet f = 0\n// multi line input\nreadline.on('line', l => {\n\tif (!f) {\n\t\tf = 1\n\t\treturn\n\t}\n\t[n, x] = l.split(' ').map(x => +x)\n\tconsole.log(Math.ceil((n + 2) / x))\n\t// console.log(line);\n});\n\n// function main() {\n// \tinput.split('\\n').slice(1).map(l => {\n// \t\t[n, x] = l.split(' ').map(x => +x)\n// \t\tconsole.log(Math.ceil((n + 2) / x))\n// \t})\n// }\n\n// process.on('SIGINT', function () {\n// \tmain()\n// \tprocess.exit(0);\n// });\n\n// main(`4\n// 7 3\n// 1 5\n// 22 5\n// 987 13`)"}, {"source_code": "function main(){\n var ncases = +readline();\n for(var i = 0; i < ncases; ++i){\n var input = readline().split(' ');\n print(Math.ceil((+input[0] - 2) / +input[1]) +1);\n }\n}\n\nmain();"}, {"source_code": "var t = Number(readline());\nwhile(t--){\n \n}"}, {"source_code": "var t = Number(readline());\nwhile(t--){\n var ln = readline().split(\" \");\n var n = Number(ln[0]),x = Number(ln[1]);\n}"}, {"source_code": "var t = Number(readline());\nwhile(t--){\n var ln = readline().split(\" \");\n var n = Number(ln[0]),x = Number(ln[1]);\n if(n<=2)print(1);\n else print((n-2)/x+((n-2)%x>0)+1);\n}"}, {"source_code": "var t = parseInt(readline());\nfor (var i = 0; i < t; i++) {\n var params = readline();\n var n = parseInt(params.split(\" \")[0]);\n var apts = parseInt(params.split(\" \")[1]);\n var floor = 1;\n if (n > 2) {\n floor = Math.ceil(parseFloat(n) / apts) + 1;\n }\n\n print(floor);\n}\n"}, {"source_code": "var t = parseInt(readline());\nfor (var i = 0; i < t; i++) {\n var params = readline();\n var n = parseInt(params.split(\" \")[0]);\n var apts = parseInt(params.split(\" \")[1]);\n var floor = 1;\n if (n > 2) {\n floor = Math.ceil(n / apts) + 1;\n }\n\n print(floor);\n}\n"}, {"source_code": "var inp = readline().split(' ');\nvar NewFloor=2;\nvar petyaApartment=parseInt(inp[0]);\nvar FloorPetya;\nconst otherFloor=parseInt(inp[1]);\n\n//var i=0;\n\nfor(var i=0;i<1000;i++){\n \n \nif((NewFloor==petyaApartment||NewFloor>petyaApartment)&&i===0){\nFloorPetya=i+1\n\nbreak;\n\n}\nif(i!==0){\nNewFloor+=otherFloor\n\n}\nif(NewFloor==petyaApartment||NewFloor>petyaApartment){\n\nFloorPetya=i+1\n\nbreak;\n\n}\n \n}\nprint(FloorPetya)\n\n"}, {"source_code": "var t = readline();\nvar test = +t;\n\nwhile(t++ <= 0) {\n var test = readline().split(' ').map(Number);\n if (test[0] <= 2) {\n print(1);\n } else {\n print(Math.ceil((test[0] - 2) / test[1]) + 1)\n }\n}\n"}, {"source_code": "var t = Number(readline());\n\nprint(t);\nwhile(false) {\n var test = readline().split(' ').map(Number);\n\n if (test[0] <= 2) {\n print(1);\n } else {\n print(Math.ceil((test[0] - 2) / test[1]) + 1)\n }\n}\n"}, {"source_code": "var t = +readline();\n\nwhile(t++ <= 0) {\n var test = readline().split(' ').map(Number);\n if (test[0] <= 2) {\n print(1);\n } else {\n print(Math.ceil((test[0] - 2) / test[1]) + 1)\n }\n}\n"}, {"source_code": "var t = Number(readline());\nprint(t);\nwhile(t++ <= 0) {\n var test = readline().split(' ').map(Number);\n\n if (test[0] <= 2) {\n print(1);\n } else {\n print(Math.ceil((test[0] - 2) / test[1]) + 1)\n }\n}\n"}], "src_uid": "8b50a0eb2e1c425455b132683d3e6047"} {"nl": {"description": "DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew $$$n$$$ distinct lines, given by equations $$$y = x + p_i$$$ for some distinct $$$p_1, p_2, \\ldots, p_n$$$.Then JLS drew on the same paper sheet $$$m$$$ distinct lines given by equations $$$y = -x + q_i$$$ for some distinct $$$q_1, q_2, \\ldots, q_m$$$.DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$), the number of test cases in the input. Then follow the test case descriptions. The first line of a test case contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), the number of lines drawn by DLS. The second line of a test case contains $$$n$$$ distinct integers $$$p_i$$$ ($$$0 \\le p_i \\le 10^9$$$) describing the lines drawn by DLS. The integer $$$p_i$$$ describes a line given by the equation $$$y = x + p_i$$$. The third line of a test case contains an integer $$$m$$$ ($$$1 \\le m \\le 10^5$$$), the number of lines drawn by JLS. The fourth line of a test case contains $$$m$$$ distinct integers $$$q_i$$$ ($$$0 \\le q_i \\le 10^9$$$) describing the lines drawn by JLS. The integer $$$q_i$$$ describes a line given by the equation $$$y = -x + q_i$$$. The sum of the values of $$$n$$$ over all test cases in the input does not exceed $$$10^5$$$. Similarly, the sum of the values of $$$m$$$ over all test cases in the input does not exceed $$$10^5$$$. In hacks it is allowed to use only one test case in the input, so $$$t=1$$$ should be satisfied.", "output_spec": "For each test case in the input print a single integer — the number of line pairs with integer intersection points. ", "sample_inputs": ["3\n3\n1 3 2\n2\n0 3\n1\n1\n1\n1\n1\n2\n1\n1"], "sample_outputs": ["3\n1\n0"], "notes": "NoteThe picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates. "}, "positive_code": [{"source_code": "var queriesCount = parseInt(readline());\n// var queriesCount = 1;\n\nfor (var i = 0; i < queriesCount; i++) {\n readline(); \n var DSL = readline().split(' ').map(function(num) {\n return parseInt(num);\n })\n readline();\n var JSL = readline().split(' ').map(function(num) {\n return parseInt(num);\n })\n\n // var DSL = [1,2,3]\n // var JSL = [0,3]\n\n var oddsDSL = 0;\n var evensDSL = 0;\n var oddsJSL = 0;\n var evensJSL = 0;\n \n for (var j = 0; j < DSL.length; j++) {\n if (DSL[j] % 2 === 0) {\n evensDSL++;\n } else {\n oddsDSL++;\n }\n }\n for (var k = 0; k < JSL.length; k++) {\n if (JSL[k] % 2 === 0) {\n evensJSL++;\n } else {\n oddsJSL++;\n }\n }\n\n write(((evensDSL * evensJSL) + (oddsDSL * oddsJSL)) + '\\n')\n}\n// });"}, {"source_code": "function solve() {\n var T = Number(read());\n for (var t = 0; t < T; ++t) {\n read();\n var cp = [0, 0];\n read().split(' ').forEach(function(sn) {\n ++cp[Number(sn) % 2];\n });\n read();\n var cq = [0, 0];\n read().split(' ').forEach(function(sn) {\n ++cq[Number(sn) % 2];\n });\n write(cp[0] * cq[0] + cp[1] * cq[1]);\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n \n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n \n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n solve();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', solve);\n }\n} else {\n solve();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin\n});\n\nlet answer = \"\";\n\nlet lines = [];\n\nrl.on('line', (t)=>{\n lines.push(t);\n}).on('close', ()=>{\n let t = parseInt(lines[0]);\n for(let i = 0; i < t; i++){\n let a = lines[1 + i * 4 + 1].split(\" \");\n let b = lines[1 + i * 4 + 3].split(\" \");\n\n let n1 = 0, m1 = 0, n2 = 0, m2 = 0;\n\n a.map((n)=>{if(n%2 == 0) n1++; else m1++;});\n b.map((n)=>{if(n%2 == 0) n2++; else m2++;});\n\n answer += (\"\" + (n1 * n2 + m1 * m2) + '\\n');\n }\n console.log(answer);\n});"}, {"source_code": "\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nvar gcd = (a, b) => a ? gcd(b % a, a) : b;\nvar lcm = (a, b) => a * b / gcd(a, b);\n\n\nfunction main(){\n\tlet t = +(readLine());\n\n\twhile(t--){\n\t\tlet n = +(readLine());\n\t\tlet p = readLine().split(\" \").map(Number);\n\t\tlet m = +(readLine());\n\t\tlet q = readLine().split(\" \").map(Number);\n\t\tlet ctr=0;\n\t\tlet odd1 = p.filter(x=> x%2==1).length;\n\t\tlet odd2 = q.filter(x=> x%2==1).length;\n\t\tlet even1 = p.filter(x=> x%2==0).length;\n\t\tlet even2 = q.filter(x=> x%2==0).length;\n\t\tctr = odd1*odd2 + even2*even1;\n\t\tconsole.log(ctr);\n\n\t}\n}\n"}], "negative_code": [{"source_code": "var queriesCount = parseInt(readline());\n// var queriesCount = 1;\n\nfor (var i = 0; i < queriesCount; i++) {\n readline(); \n var DSL = readline().split(' ').map(function(num) {\n return parseInt(num);\n })\n readline();\n var JSL = readline().split(' ').map(function(num) {\n return parseInt(num);\n })\n\n // var DSL = [1,2,3]\n // var JSL = [0,3]\n\n var oddsDSL = 0;\n var evensDSL = 0;\n var oddsJSL = 0;\n var evensJSL = 0;\n \n for (var i = 0; i < DSL.length; i++) {\n if (DSL[i] % 2 === 0) {\n evensDSL++;\n } else {\n oddsDSL++;\n }\n }\n for (var i = 0; i < JSL.length; i++) {\n if (JSL[i] % 2 === 0) {\n evensJSL++;\n } else {\n oddsJSL++;\n }\n }\n\n write(((evensDSL * evensJSL) + (oddsDSL * oddsJSL)) + '\\n')\n}\n// });"}], "src_uid": "adf4239de3b0034cc690dad6160cf1d0"} {"nl": {"description": "You are given an array of positive integers $$$a = [a_0, a_1, \\dots, a_{n - 1}]$$$ ($$$n \\ge 2$$$).In one step, the array $$$a$$$ is replaced with another array of length $$$n$$$, in which each element is the greatest common divisor (GCD) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the $$$(n - 1)$$$-th element is the $$$0$$$-th element).Formally speaking, a new array $$$b = [b_0, b_1, \\dots, b_{n - 1}]$$$ is being built from array $$$a = [a_0, a_1, \\dots, a_{n - 1}]$$$ such that $$$b_i$$$ $$$= \\gcd(a_i, a_{(i + 1) \\mod n})$$$, where $$$\\gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$, and $$$x \\mod y$$$ is the remainder of $$$x$$$ dividing by $$$y$$$. In one step the array $$$b$$$ is built and then the array $$$a$$$ is replaced with $$$b$$$ (that is, the assignment $$$a$$$ := $$$b$$$ is taking place).For example, if $$$a = [16, 24, 10, 5]$$$ then $$$b = [\\gcd(16, 24)$$$, $$$\\gcd(24, 10)$$$, $$$\\gcd(10, 5)$$$, $$$\\gcd(5, 16)]$$$ $$$= [8, 2, 5, 1]$$$. Thus, after one step the array $$$a = [16, 24, 10, 5]$$$ will be equal to $$$[8, 2, 5, 1]$$$.For a given array $$$a$$$, find the minimum number of steps after which all values $$$a_i$$$ become equal (that is, $$$a_0 = a_1 = \\dots = a_{n - 1}$$$). If the original array $$$a$$$ consists of identical elements then consider the number of steps is equal to $$$0$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. Each test case contains two lines. The first line contains an integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) — length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_0, a_1, \\dots, a_{n - 1}$$$ ($$$1 \\le a_i \\le 10^6$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$t$$$ numbers — answers for each test case.", "sample_inputs": ["5\n4\n16 24 10 5\n4\n42 42 42 42\n3\n4 6 4\n5\n1 2 3 4 5\n6\n9 9 27 9 9 63"], "sample_outputs": ["3\n0\n2\n1\n1"], "notes": null}, "positive_code": [{"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n var arr = lines[l++].split(' ').map(Number)\n console.log(solve(n, arr))\n }\n});\n\nfunction solve(n, arr) {\nconst t1 = new Date()\n const d = arr.reduce((s, x) => gcd(s, x), arr[0])\n let same = true\n arr = arr.map(x => {\n if (x !== d) same = false\n return x / d\n })\n if (same) return 0\n\n// console.log('pre', new Date() - t1)\n // let j = 0\n // for (var i = 0; i < 2 * n; i++) {\n // j++\n // }\n const tree = []\n createTree(tree, 0, 0, 2 * n - 1, 0)\n// console.log('tree created', new Date() - t1)\n// return\n initTree(tree, gcd, arr)\n// console.log('tree inited', new Date() - t1)\n\n let max = 0\n for (let i = 0; i < n; i++) {\n const last = binarySearch(i, i + n - 1, x => {\n return i === x || queryTree(tree, 0, i, x, gcd) > 1\n })\n const len = last - i + 1\n max = Math.max(max, len)\n // console.log(i, last, queryTree(tree, 0, i, last, gcd))\n }\n return max\n}\nfunction createTree(tree, p, left, right, val) {\n tree[p] = { left, right, val }\n if (left === right) return\n\n const mid = Math.floor((left + right) / 2)\n createTree(tree, 2 * p + 1, left, mid, val)\n createTree(tree, 2 * p + 2, mid + 1, right, val)\n\n // const tree = []\n // tree[0] = {\n // left: 0,\n // right: n - 1,\n // val\n // }\n\n // const q = [[0, n - 1, 0]]\n // while (q.length) {\n // const [left, right, p] = q.shift()\n // const mid = Math.floor((left + right) / 2)\n // tree[2 * p + 1] = {\n // left,\n // right: mid,\n // val\n // }\n // if (left !== mid) {\n // q.push([left, mid, 2 * p + 1])\n // }\n\n // tree[2 * p + 2] = {\n // left: mid + 1,\n // right,\n // val\n // }\n // if (mid + 1 !== right) {\n // q.push([mid + 1, right, 2 * p + 2])\n // }\n // console.log('q.length ' + q.length)\n // }\n // return tree\n}\nfunction initTree(tree, merge, arr) {\n for (let i = tree.length - 1; i >= 0; i--) {\n if (!tree[i]) continue\n const { left, right } = tree[i]\n tree[i].val = left === right\n ? arr[left % arr.length]\n : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)\n }\n}\nfunction insertTree(tree, idx, l, r, val) {\n const { left, right } = tree[idx]\n if (l === left && r === right) {\n tree[idx].val = val\n return\n }\n\n const mid = Math.floor((left + right) / 2)\n if (r <= mid) {\n insertTree(tree, 2 * idx + 1, l, r, val)\n } else if (l > mid) {\n insertTree(tree, 2 * idx + 2, l, r, val)\n } else {\n insertTree(tree, 2 * idx + 1, l, mid, val)\n insertTree(tree, 2 * idx + 2, mid + 1, r, val)\n }\n}\nfunction queryTree(tree, idx, l, r, merge) {\n const { left, right } = tree[idx]\n // if (left === right) return tree[idx].val\n if (l === left && r === right) return tree[idx].val\n\n const mid = Math.floor((left + right) / 2)\n if (r <= mid) {\n return queryTree(tree, 2 * idx + 1, l, r, merge)\n } else if (l > mid) {\n return queryTree(tree, 2 * idx + 2, l, r, merge)\n } else {\n const a = queryTree(tree, 2 * idx + 1, l, mid, merge)\n const b = queryTree(tree, 2 * idx + 2, mid + 1, r, merge)\n return merge(a, b)\n }\n}\nfunction gcd(a, b) {\n if (a === 0) return b\n if (b === 0) return a\n\n while (a) {\n const r = b % a\n b = a\n a = r\n }\n return b\n}\nfunction binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nconst MAX_A = 1000002;\r\nlet n;\r\nlet arr;\r\nlet primes = [];\r\nlet sieve = new Int32Array(MAX_A).fill(0); // min pf of i\r\nfunction pre() {\r\n sieve[1] = 1;\r\n for (let i = 2; i < MAX_A; i++) {\r\n if (sieve[i] == 0) {\r\n sieve[i] = i;\r\n primes.push(i);\r\n for (let j = i; i * j < MAX_A; j++) {\r\n sieve[i * j] = i;\r\n }\r\n }\r\n }\r\n // for (let i = 1; i < 60; i++) {\r\n // printf(\"sieve[%d] %d\\n\", i, sieve[i]);\r\n // }\r\n}\r\nfunction gcd(a, b) {\r\n while (a > 0) {\r\n let c = a;\r\n a = b % a;\r\n b = c;\r\n }\r\n return b;\r\n}\r\nfunction solve() {\r\n const pf = Array.from({ length: n });\r\n for (let i = 0; i < n; i++) {\r\n pf[i] = new Set();\r\n let t = arr[i];\r\n while (t != 1) {\r\n pf[i].add(sieve[t]);\r\n t /= sieve[t];\r\n }\r\n }\r\n // printf(\"arr %j\\n\", arr);\r\n let ans = 0;\r\n for (let i = 0; i < n; i++) {\r\n for (let p of pf[i]) {\r\n let cnt = 1;\r\n let j = (n + i - 1) % n;\r\n while (pf[j].has(p)) {\r\n pf[j].delete(p);\r\n cnt++;\r\n j = (n + j - 1) % n;\r\n }\r\n j = (i + 1) % n;\r\n while (pf[j].has(p)) {\r\n pf[j].delete(p);\r\n cnt++;\r\n j = (j + 1) % n;\r\n }\r\n // printf(\"i %d p %d cnt %d\\n\",i, p, cnt);\r\n ans = Math.max(ans, cnt);\r\n }\r\n pf[i].clear();\r\n }\r\n return ans;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n pre();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n arr = new Int32Array(n);\r\n for (let i = 0; i < n; i++) {\r\n arr[i] = nextInt();\r\n }\r\n let com = arr[0];\r\n for (let i = 1; i < n; i++) {\r\n com = gcd(com, arr[i]);\r\n }\r\n for (let i = 0; i < n; i++) {\r\n arr[i] /= com;\r\n }\r\n printf(\"%d\\n\", solve());\r\n }\r\n}\r\n"}, {"source_code": "var sz;\r\nvar gets;\r\n\r\nfunction gcd(a, b) {\r\n return b === 0 ? a : gcd(b, a % b);\r\n}\r\n\r\nfunction ini(n) {\r\n\tsize = 1;\r\n\twhile(size < n)\r\n\t\tsize *= 2;\r\n\tgets = new Array(2 * size).fill(0);\r\n}\r\n \r\nfunction sets(i, v, cur, l, r) {\r\n\tif(r - l == 1) {\r\n\t\tgets[cur] = v;\r\n\t\treturn;\r\n\t}\r\n\tvar m = (l + r) >> 1;\r\n\tif(i= rx || lx >= r)\r\n\t\treturn 0;\r\n\tif(lx >= l && rx <= r)\r\n\t\treturn gets[cur];\r\n\tvar m = (lx + rx) >> 1;\r\n\tvar s1 = gt(l, r, 2 * cur + 1, lx, m);\r\n\tvar s2 = gt(l, r, 2 * cur + 2, m, rx);\r\n\treturn gcd(s1, s2);\r\n}\r\n \r\nfunction ret(l, r) {\r\n\treturn gt(l, r, 0, 0, size);\r\n}\r\n\r\nvar t = parseInt(readline());\r\nfor(var tc = 0; tc < t; tc++) {\r\n var n = parseInt(readline());\r\n var a = readline().split(\" \");\r\n\tfor(var i = 0; i < n; i++) {\r\n\t a[i] = parseInt(a[i]);\r\n\t}\r\n\tini(n);\r\n\tfor(var i = 0; i < n; i++)\r\n\t\tupd(i, a[i]);\r\n\tvar l = 0, r = n - 1;\r\n\twhile(l <= r) {\r\n\t\tvar mid = (l + r) >> 1;\r\n\t\tvar gc = ret(0, mid + 1);\r\n\t\tvar ok = 1;\r\n\t\tfor(var i = 1; i < n; i++)\r\n\t\t{\r\n\t\t\tvar idx = i + mid;\r\n\t\t\tif(idx < n)\r\n\t\t\t\tok &= ret(i, idx + 1) == gc;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tidx %= n;\r\n\t\t\t\tok &= gcd(ret(i, n), ret(0, idx + 1)) == gc;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(ok) {\r\n\t\t r = mid - 1;\r\n\t\t}\r\n\t\telse {\r\n\t\t l = mid + 1;\r\n\t\t}\r\n\t}\r\n\tprint(l);\r\n}"}], "negative_code": [], "src_uid": "1dfef6ab673b51e3622be6e8ab949ddc"} {"nl": {"description": "3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ 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": "var input = readline().split(\" \").map(function(x) { return parseInt(x); }); \nvar n = input[0];\nvar q = input[1];\n\nvar field = Array.apply(null, Array(n)).map(Number.prototype.valueOf,0);\nvar blocks = 0;\nwhile(q--)\n{\n input = readline().split(\" \").map(function(x) { return parseInt(x); }); \n var r = input[0];\n var c = input[1];\n\n var blocksPrev = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++) \n {\n if (field[i] == 0)\n continue;\n\n var selfstatus = 0;\n if (field[i] == 3)\n selfstatus = field[i] == 3;\n\n var leftstatus = 0;\n if (i - 1 >= 0 && (field[i] | field[i - 1]) == 3)\n {\n leftstatus = 1;\n selfstatus |= 1;\n }\n\n var rightstatus = 0;\n if (i + 1 < n && (field[i] | field[i + 1]) == 3)\n {\n rightstatus = 1;\n selfstatus |= 1;\n } \n \n blocksPrev += rightstatus | leftstatus | selfstatus;\n }\n\n field[c - 1] ^= r;\n \n var blocksAfter = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++) \n {\n if (field[i] == 0)\n continue;\n\n var selfstatus = 0;\n if (field[i] == 3)\n selfstatus = field[i] == 3;\n\n var leftstatus = 0;\n if (i - 1 >= 0 && (field[i] | field[i - 1]) == 3)\n {\n leftstatus = 1;\n selfstatus |= 1;\n }\n\n var rightstatus = 0;\n if (i + 1 < n && (field[i] | field[i + 1]) == 3)\n {\n rightstatus = 1;\n selfstatus |= 1;\n } \n \n blocksAfter += rightstatus | leftstatus | selfstatus;\n }\n\n blocks += blocksAfter - blocksPrev;\n \n /*\n var ans = \"yes\";\n for(var i = 0; i < n - 1; i++)\n {\n if ((field[i] | field[i + 1]) == 3)\n {\n ans = \"no\";\n break;\n }\n }\n */\n if (blocks > 0)\n print(\"no\");\n else\n print(\"yes\");\n}"}, {"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main(arr)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a, i) {\n if(i === undefined) return parseInt(a.shift())\n else return parseInt(a[i])\n}\n\nfunction readInts(a, i) {\n if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))\n else return arr[i].split(' ').map(a => parseInt(a))\n}\n\nfunction main(input) {\n let t = 0\n const [n, q] = readInts(input,t++)\n\n let arr = [Array(n).fill(false), Array(n).fill(false)]\n\n let result = false\n\n let blocks = 0\n while(t <= q) {\n let [r, c] = readInts(input,t++)\n r--\n c--\n\n arr[r][c] = !arr[r][c]\n\n if(!arr[r][c] && !result) wr('YES')\n\n else if(arr[r][c]) {\n let r1 = (r + 1) % 2\n if(arr[r1][c - 1] && c > 0) blocks ++\n if(arr[r1][c]) blocks ++ \n if(arr[r1][c + 1] && c < n - 1) blocks ++\n if(blocks == 0) {\n result = false\n wr('YES')\n }\n else {\n result = true\n wr('NO')\n }\n }\n else if(!arr[r][c] && result) {\n let r1 = (r + 1) % 2\n if(arr[r1][c - 1]) blocks--\n if(arr[r1][c]) blocks--\n if(arr[r1][c + 1]) blocks--\n if(blocks == 0) {\n result = false\n wr('YES')\n }\n else wr('NO')\n }\n // wr(arr, blocks)\n }\n}"}], "negative_code": [{"source_code": "var input = readline().split(\" \").map(function(x) { return parseInt(x); }); \nvar n = input[0];\nvar q = input[1];\n\nvar field = Array.apply(null, Array(n)).map(Number.prototype.valueOf,0);\nvar blocks = 0;\nwhile(q--)\n{\n input = readline().split(\" \").map(function(x) { return parseInt(x); }); \n var r = input[0];\n var c = input[1];\n\n var blocksPrev = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++) \n if ((field[i - 1] | field[i] | field[i + 1]) == 3)\n blocksPrev++;\n\n field[c - 1] ^= r;\n \n var blocksAfter = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++) \n if ((field[i - 1] | field[i] | field[i + 1]) == 3)\n blocksAfter++;\n\n blocks += blocksAfter - blocksPrev;\n \n /*\n var ans = \"yes\";\n for(var i = 0; i < n - 1; i++)\n {\n if ((field[i] | field[i + 1]) == 3)\n {\n ans = \"no\";\n break;\n }\n }\n */\n if (blocks > 0)\n print(\"no\");\n else\n print(\"yes\");\n}"}, {"source_code": "var input = readline().split(\" \").map(function(x) { return parseInt(x); }); \nvar n = input[0];\nvar q = input[1];\n\nvar field = Array.apply(null, Array(n)).map(Number.prototype.valueOf,0);\nvar blocks = 0;\nwhile(q--)\n{\n input = readline().split(\" \").map(function(x) { return parseInt(x); }); \n var r = input[0];\n var c = input[1];\n\n var blocksPrev = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++)\n {\n var status = field[i];\n if (i - 1 >= 0)\n status |= field[i - 1];\n if (i + 1 < n)\n status |= field[i + 1];\n \n if (status == 3)\n blocksPrev++;\n }\n\n field[c - 1] ^= r;\n \n var blocksAfter = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++) \n {\n var status = field[i];\n if (i - 1 >= 0)\n status |= field[i - 1];\n if (i + 1 < n)\n status |= field[i + 1];\n \n if (status == 3)\n blocksAfter++;\n }\n\n blocks += blocksAfter - blocksPrev;\n \n /*\n var ans = \"yes\";\n for(var i = 0; i < n - 1; i++)\n {\n if ((field[i] | field[i + 1]) == 3)\n {\n ans = \"no\";\n break;\n }\n }\n */\n if (blocks > 0)\n print(\"no\");\n else\n print(\"yes\");\n}"}, {"source_code": "var input = readline().split(\" \").map(function(x) { return parseInt(x); }); \nvar n = input[0];\nvar q = input[1];\n\nvar field = Array.apply(null, Array(n)).map(Number.prototype.valueOf,0);\nvar blocks = 0;\nwhile(q--)\n{\n input = readline().split(\" \").map(function(x) { return parseInt(x); }); \n var r = input[0];\n var c = input[1];\n\n var blocksPrev = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++)\n {\n var status = field[i];\n if (i - 1 >= 0)\n status |= field[i - 1];\n if (i + 1 < n)\n status |= field[i + 1];\n \n if (status == 3)\n blocksPrev++;\n }\n\n field[c - 1] ^= r;\n \n var blocksAfter = 0;\n for (var i = Math.max(0, c - 3); i < Math.min(n, c + 2); i++) \n {\n var status = field[i];\n if (i - 1 >= 0)\n status |= field[i - 1];\n if (i + 1 < n)\n status |= field[i + 1];\n \n if (status == 3)\n blocksPrev++;\n }\n\n blocks += blocksAfter - blocksPrev;\n \n /*\n var ans = \"yes\";\n for(var i = 0; i < n - 1; i++)\n {\n if ((field[i] | field[i + 1]) == 3)\n {\n ans = \"no\";\n break;\n }\n }\n */\n if (blocks > 0)\n print(\"no\");\n else\n print(\"yes\");\n}"}], "src_uid": "af036416721694d1843368988ca78e8e"} {"nl": {"description": "Innokentiy decides to change the password in the social net \"Contact!\", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: the length of the password must be equal to n, the password should consist only of lowercase Latin letters, the number of distinct symbols in the password must be equal to k, any two consecutive symbols in the password must be distinct. Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions. ", "input_spec": "The first line contains two positive integers n and k (2 ≤ n ≤ 100, 2 ≤ k ≤ min(n, 26)) — the length of the password and the number of distinct symbols in it. Pay attention that a desired new password always exists.", "output_spec": "Print any password which satisfies all conditions given by Innokentiy.", "sample_inputs": ["4 3", "6 6", "5 2"], "sample_outputs": ["java", "python", "phphp"], "notes": "NoteIn the first test there is one of the appropriate new passwords — java, because its length is equal to 4 and 3 distinct lowercase letters a, j and v are used in it.In the second test there is one of the appropriate new passwords — python, because its length is equal to 6 and it consists of 6 distinct lowercase letters.In the third test there is one of the appropriate new passwords — phphp, because its length is equal to 5 and 2 distinct lowercase letters p and h are used in it.Pay attention the condition that no two identical symbols are consecutive is correct for all appropriate passwords in tests. "}, "positive_code": [{"source_code": "var generatePassword = (n,k) => {\n if (n < 2 || n > 100 || k < 2 || k > Math.min(n,26))\n throw new Error('Invalid input');\n \n // create an array of letters from a - z;\n const latinLetters = [...Array(26)].map((v,i) => String.fromCharCode(i + 'a'.charCodeAt()));\n // shuffle the array\n latinLetters.sort(() => Math.random() - 0.5); \n const distinctSymbols = [];\n // add the first k elements to the distinctSymbols Array;\n\n while (distinctSymbols.length < k){\n // .shift() removes the first element and return it\n distinctSymbols.push(latinLetters.shift())\n }\n \n let i = 0;\n let output = distinctSymbols.join('')\n while (output.length < n){\n output += distinctSymbols[i++ % k]\n }\n\n console.log(output)\n}\n\nprocess.stdin.on('data',(chunk) => {\n var n = chunk.toString().split(' ')[0];\n var k = chunk.toString().split(' ')[1];\n\n generatePassword(n,k)\n})"}, {"source_code": "var generatePassword = (n,k) => {\n let output = ''\n for (let i = 0; i < k; i++)\n output += String.fromCharCode(i + 'a'.charCodeAt())\n \n const count = Math.floor(n / k);\n const remainingSpots = n % k;\n output = output.repeat(count) + output.slice(0,remainingSpots);\n console.log(output)\n}\n\nprocess.stdin.on('data',(chunk) => {\n var n = chunk.toString().split(' ')[0];\n var k = chunk.toString().split(' ')[1];\n\n generatePassword(n,k)\n})"}, {"source_code": "var generatePassword = (n,k) => {\n if (n < 2 || n > 100 || k < 2 || k > Math.min(n,26))\n throw new Error('Invalid input');\n // create an array of letters from a - z;\n const latinLetters = [...Array(26)].map((v,i) => String.fromCharCode(i + 'a'.charCodeAt()));\n // shuffle the array (even if we dont shuffle it the answer will be valid)\n latinLetters.sort(() => Math.random() - 0.5);\n // joining the first k elements\n let output = latinLetters.slice(0,k).join('')\n //\n const count = Math.floor(n / k);\n const remainingSpots = n % k;\n\n output = output.repeat(count) + output.slice(0,remainingSpots);\n\n console.log(output)\n}\n\nprocess.stdin.on('data',(chunk) => {\n var n = chunk.toString().split(' ')[0];\n var k = chunk.toString().split(' ')[1];\n\n generatePassword(n,k)\n})"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.on('line', (input) => {\n rl.close();\n let line = input.split(' ');\n console.log(solve(parseInt(line[0]), parseInt(line[1])));\n});\n\n\nconst solve = (n, k) => {\n let z = k;\n let password = '';\n let alphIndex = 0;\n let characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',\n 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z'\n ];\n\n while (k !== 0) {\n password += characters[alphIndex++];\n k--;\n }\n\n return password.repeat(Math.ceil(n / z)).slice(0, n);\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n const [n, k] = readline().split(' ').map(x => parseInt(x));\n const a = [];\n const c = 'abcdefghijklmnopqrstuvwxyz';\n let i = 0, s = 0;\n while (i++ < n) {\n if (s === k) {\n s = 0;\n }\n a.push(c.charAt(s));\n s++;\n }\n // output\n print(a.join(''));\n}\n\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const [n, k] = d.split(' ').map(Number);\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const ans = [];\n\n for (let i = 0; i < k; i++) {\n ans.push(letters[i]);\n }\n\n let inc = 0;\n while (ans.length < n) {\n ans.push(ans[inc]);\n inc++;\n }\n\n console.log(ans.join(''));\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const [n, k] = d.split(' ').map(Number);\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n // const ans = [];\n let ans = '';\n\n for (let i = 0; i < n; i++) {\n ans += letters[i % k];\n }\n\n console.log(ans);\n\n // for (let i = 0; i < k; i++) {\n // ans.push(letters[i]);\n // }\n\n // let inc = 0;\n // while (ans.length < n) {\n // ans.push(ans[inc]);\n // inc++;\n // }\n\n // console.log(ans.join(''));\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const [n, k] = d.split(' ').map(Number);\n // const letters = 'abcdefghijklmnopqrstuvwxyz';\n // const ans = [];\n let ans = '';\n\n for (let i = 0; i < n; i++) {\n ans += String.fromCharCode(i % k + 97);\n }\n\n console.log(ans);\n\n // for (let i = 0; i < k; i++) {\n // ans.push(letters[i]);\n // }\n\n // let inc = 0;\n // while (ans.length < n) {\n // ans.push(ans[inc]);\n // inc++;\n // }\n\n // console.log(ans.join(''));\n});\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readint() {\n let line = readline().split(' ').map(function(num) {\n return parseInt(num);\n });\n return line;\n}\n\nfunction readfloat() {\n let line = readline().split(' ').map(function(num) {\n return parseFloat(num);\n });\n return line;\n}\n\nfunction print(x) {\n console.log(x);\n}\n\nfunction write(x) {\n process.stdout.write(x);\n}\nfunction min(a,b) {\n if(a > b) return b;\n else return a;\n}\nfunction main() {\n let [n,k] = readint();\n let ab = n + 2 - k;\n let beg = 97;\n for(let i = 0; i < ab; i++) {\n write(String.fromCharCode(beg));\n if(beg == 97) beg = 98;\n else beg = 97;\n } \n beg = 99;\n for(let i = 0; i < k - 2; i++) {\n write(String.fromCharCode(beg));\n beg++;\n }\n}"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet input = [];\nreadline.on('line', line => {\n input.push(line);\n});\nprocess.stdin.on('end', () => {\nlet firstLine = input[0].split(' ');\nconst length = parseInt(firstLine[0], 10);\nconst uniqueAmount = parseInt(firstLine[1], 10);\nlet text = '';\nfor (let i=0; i= disNum)\n i = 0;\n }\n \n x = x.join('');\n\n print(x);"}, {"source_code": "var informations = readline().split(' ').map(Number)\n\n var n = informations[0]\n var k = informations[1]\n var firstIndex = 'a'.charCodeAt(0)\n var lastIndex = 'a'.charCodeAt(0) + k\n\n var password = new Array(n).fill('_')\n\n\n var index = firstIndex\n for (var i = 0; i < n; i++) {\n password[i] = String.fromCharCode(index)\n index += 1\n if (index >= lastIndex) {\n index = firstIndex\n }\n }\n\n print(password.join(''))"}, {"source_code": "var informations = readline().split(' ').map(Number)\n\n var n = informations[0]\n var k = informations[1]\n\n var result = []\n for (var i = 0; i < n; i++) {\n result.push(String.fromCharCode(i % k + 'a'.charCodeAt(0)))\n }\n\n print(result.join(''))"}, {"source_code": "function main() {\n var row = readline().split(\" \");\n var n = row[0], k = row[1];\n var alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n var possible = alphabet.slice(0, k);\n var pass = Array(Math.ceil(n/k)+1).join(possible);\n pass = pass.slice(0, n);\n print(pass);\n\n return 0;\n}\n\nmain();"}, {"source_code": "var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"]) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); } }; }();\n\nvar data = [];\ndata.push(readline());\n\nfunction solve() {\n var _data$0$split$map = data[0].split(' ').map(function (d) {\n return parseInt(d);\n });\n\n var _data$0$split$map2 = _slicedToArray(_data$0$split$map, 2);\n\n var n = _data$0$split$map2[0];\n var k = _data$0$split$map2[1];\n\n var pass = Array(k).fill(0).map(function (_, i) {\n return String.fromCharCode(i + 97);\n }).join('');\n var i = 0;\n while (pass.length < n) {\n pass += pass[i];\n i++;\n }\n print(pass);\n}\n\nsolve();"}, {"source_code": "var l = readline().split(' ');\nvar n = l[0];\nvar k = l[1];\nvar str =\"\";\nfor(var i=0; i= passwordChars.length) pointer = 0;\n\tchar = passwordChars[pointer++];\n\tpassword.push(char);\n}\n\nprint(password.join(\"\"));"}, {"source_code": "var input = readline().trim().split(\" \");\nvar n = +input[0], k = +input[1];\n\nvar s = \"qwertyuiopasdfghjklzxcvbnm\";\nvar ans = \"\";\n\nfor (var i = 0; i < n; i++) {\n\tans += s.charAt(i % k);\n}\n\nprint(ans);\n"}, {"source_code": "var letters = [ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o','p','a',\n's','d','f','g','h','j','k','l','z','x','c','v','b','n','m'];\n\nvar input = readline().split(' ');\nvar n = input[0];\nvar k = input[1];\nvar usedLetters = letters.slice(0, k);\nvar ans = '';\nfor (var i = 0; i < n; i++) {\n\tans += usedLetters[i % usedLetters.length];\n}\nprint(ans);\n"}, {"source_code": "var line = readline().split(\" \"),\n length = line[0],\n count = line[1],\n letters = \"qwertyuiopasdfghjklzxcvbnm\".split(\"\"),\n \n random = function(a, b) {\n return Math.floor(Math.random() * (b - a + 1)) + a;\n },\n \n sel = [],\n selUse = [],\n password = [];\n \nfor (var i = 0; i < count; ++i) {\n var idx = random(0, letters.length - 1),\n q = letters[idx];\n sel.push(q);\n selUse.push(q);\n letters.splice(idx, 1);\n}\n\nvar last;\nfor (var i = 0; i < length; ++i) {\n var cur, idx, db;\n do {\n db = selUse.length ? selUse : sel;\n cur = db[idx = random(0, db.length - 1)];\n } while (cur == last);\n password.push(cur);\n db === selUse && db.splice(idx, 1);\n last = cur;\n}\n\nprint(password.join(\"\"));"}, {"source_code": "function main() {\n var row = readline().split(\" \");\n var n = row[0], k = row[1];\n var alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n var possible = alphabet.slice(0, k);\n var pass = Array(Math.ceil(n/k)+1).join(possible);\n pass = pass.slice(0, n);\n print(pass);\n\n return 0;\n}\n\nmain();"}, {"source_code": "var a = ['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'];\nvar g = readline().split(\" \");\nvar arr = [];\nvar n = Number(g[0]);\nvar k = Number(g[1]);\nfor(i=0;i {\n if (n < 2 || n > 100 || k < 2 || k > Math.min(n,26))\n throw new Error('Invalid input');\n \n // create an array of letters from a - z;\n const latinLetters = [...Array(26)].map((v,i) => String.fromCharCode(i + 'a'.charCodeAt()));\n // shuffle the array\n latinLetters.sort(() => Math.random() - 0.5); \n const distinctSymbols = [];\n // add the first k elements to the distinctSymbols Array;\n\n while (distinctSymbols.length < k){\n // .shift() removes the first element and return it\n distinctSymbols.push(latinLetters.shift())\n }\n \n let i = 0;\n let output = distinctSymbols.join('')\n while (output.length < n){\n output += distinctSymbols[i++ % k]\n }\n\n console.log(output)\n}\n\n\ngeneratePassword(99,26)"}, {"source_code": "var generatePassword = (n,k) => {\n if (n < 2 || n > 100 || k < 2 || k > Math.min(n,26))\n throw new Error('Invalid input');\n \n // create an array of letters from a - z;\n const latinLetters = [...Array(26)].map((v,i) => String.fromCharCode(i + 'a'.charCodeAt()));\n // shuffle the array\n latinLetters.sort(() => Math.random() - 0.5); \n const distinctSymbols = [];\n // add the first k elements to the distinctSymbols Array;\n\n while (distinctSymbols.length < k){\n // .shift() removes the first element and return it\n distinctSymbols.push(latinLetters.shift())\n }\n \n let i = 0;\n let output = distinctSymbols.join('')\n while (output.length < n){\n output += distinctSymbols[i++ % k]\n }\n\n return output\n}\n\n\ngeneratePassword(6,4)"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.on('line', (input) => {\n rl.close();\n let line = input.split(' ');\n console.log(solve(parseInt(line[0]), parseInt(line[1])));\n});\n\n\nconst solve = (n, k) => {\n\n let password = '';\n let alphIndex = 0;\n let characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',\n 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z'\n ];\n\n while (k !== 0) {\n password += characters.shift();\n k--;\n }\n n -= 26 - characters.length;\n while (n !== 0) {\n if (alphIndex === characters.length - 1) alphIndex = 0;\n password += characters[alphIndex++];\n n--;\n }\n return password;\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n const [n, k] = readline().split(' ').map(x => parseInt(x));\n const a = [];\n const c = 'abcdefghijklmnopqrstuvwxyz';\n let i = 0, s = 0;\n while (i++ < n) {\n if (s < k) {\n a.push(c.charAt(s));\n s++;\n } else {\n s = 0;\n a.push(c.charAt(s));\n }\n }\n // output\n print(a.join(''));\n}\n\n"}, {"source_code": "//Input\n// var firstLine = \"4 3\";\n// var firstLine = \"6 6\";\n// var firstLine = \"5 2\";\n\nvar firstLine = readline();\n\nretorno = eval(firstLine);\n\n//Solution\nfunction eval(firstLine){\n var tmp = firstLine.split(\" \");\n var n = parseInt(tmp[0]);\n var k = parseInt(tmp[1]);\n\n // console.log(getPassword(n, k));\n write(getPassword(n, k));\n //return \"Hola\";\n};\n\nfunction getPassword(n, k){\n var alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n var newPassword = \"\";\n var index = parseInt((Math.random())*26);\n //console.log(\"index: \" + index + \" alphabet[\" + index + \"]: \" + alphabet[index]);\n newPassword += alphabet[index];\n //console.log(\"newPassword: \" + newPassword)\n var nextIndex = index;\n\n for(var i = 1 ; i < n ; i++){\n while(index == nextIndex){\n nextIndex = parseInt((Math.random())*26);\n //console.log(\"index: \" + index + \" nextIndex: \" + nextIndex);\n if(nextIndex != index){\n newPassword += alphabet[nextIndex];\n index = nextIndex;\n break;\n };\n };\n //console.log(\"nextIndex: \" + nextIndex);\n };\n\n\n\n\n return newPassword;\n};\n\n\n\n"}, {"source_code": "var l = readline().split(' ');\nvar n = l[0];\nvar k = l[1];\nvar str =\"\";\nfor(var i=0; it;t++)_[e[t]]=t;for(var a=0,t=1;r>t;t++)a+=Math.abs(_[t+1]-_[t]);return a}print(calculate(e))}var _=(parseInt(readline()),readline().split(\" \").map(function(e){return parseInt(e)}));solve(_)}]);"}, {"source_code": "var n = +readline();\nvar f = readline().split(' ').map(Number);\nvar fm = [];\nvar count = 0;\nfor (var i=0; i a[1] - b[1] );\nfor (var i=0; i +i);\n\nvar positions = [];\nf.forEach((fi, i) => positions[fi - 1] = i);\n\nvar steps = positions\n .map((pfi, i, p) => Math.abs(pfi - p[i-1] || 0))\n .reduce((sum, diff) => sum + diff);\nprint(steps);\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$$$) — 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": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst lineReader = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet inputPos = 0;\r\nconst inputWords = [];\r\nlineReader.on('line', (line) => {\r\n inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));\r\n});\r\nlineReader.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(inputWords[inputPos++]));\r\n}\r\nfunction nextStr() {\r\n return inputWords[inputPos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nfunction main() {\r\n let n = nextInt();\r\n const a = af(n);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = nextInt();\r\n }\r\n let ans = Infinity;\r\n for (let i = 0; i < n; i++) {\r\n let t = 0;\r\n let last = 0;\r\n for (let j = i - 1; j >= 0; j--) {\r\n let need = Math.ceil((last + 1) / a[j]);\r\n t += need;\r\n last = need * a[j];\r\n }\r\n last = 0;\r\n for (let j = i + 1; j < n; j++) {\r\n let need = Math.ceil((last + 1) / a[j]);\r\n t += need;\r\n last = need * a[j];\r\n }\r\n ans = Math.min(ans, t);\r\n }\r\n printf(\"%d\\n\", ans);\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(n, a) {\r\n let res = Infinity;\r\n for (let i = 0; i < n; i++) {\r\n const tmp = new Array(n).fill(0),\r\n queue = [[i + 1, 1], [i - 1, -1]];\r\n let count = 0;\r\n for (let [j, dj] of queue) {\r\n if (j < 0 || j >= n) continue;\r\n let num = Math.floor(tmp[j - dj] / (a[j] * dj)) + 1;\r\n tmp[j] = num * a[j] * dj;\r\n count += num;\r\n queue.push([j + dj, dj]);\r\n }\r\n res = Math.min(res, count);\r\n }\r\n console.log(res);\r\n}\r\n\r\nfunction main(inputs) {\r\n const n = Number(inputs[0].trim());\r\n const a = inputs[1].trim().split(' ').map(Number);\r\n solve(n, a);\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nmain(inputs);\r\n"}, {"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n let index = 0;\n\n const n = parseInt(input[index]);\n index++;\n const a = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n a,\n };\n\n testCases.push(testCase);\n}\n\nfunction solution(testCase, index) {\n const { n, a } = testCase;\n\n let result = Infinity;\n\n for (let pivot = 0; pivot < n; pivot++) {\n let moves = 0;\n let ref = 1;\n const b = new Array(n).fill(0);\n // Left\n for (let i = pivot - 1; i >= 0; i--) {\n const nbMovesNeeded = Math.ceil((ref - a[i]) / a[i]) + 1;\n\n ref = nbMovesNeeded * a[i];\n b[i] = -ref;\n ref++;\n moves += nbMovesNeeded;\n }\n\n ref = 1;\n // Right\n for (let i = pivot + 1; i < n; i++) {\n const nbMovesNeeded = Math.ceil((ref - a[i]) / a[i]) + 1;\n\n ref = nbMovesNeeded * a[i];\n b[i] = ref;\n ref++;\n moves += nbMovesNeeded;\n }\n\n if (moves < result) result = moves;\n }\n\n console.log(result);\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet s = \"\";\nprocess.stdin.on(\"data\", (data) => {\n s += data;\n});\n\nprocess.stdin.on(\"end\", () => {\n s = s.split(\"\\n\");\n\n main();\n});\n\nfunction main() {\n const n = Number(s[0]);\n const a = s[1].split(\" \").map(Number);\n\n solve(n, a);\n}\n\nfunction solve(n, a) {\n let count = Infinity;\n\n for (let i = 0; i < n; i++) {\n let tc = 0;\n // Greater\n let prev = 0;\n for (let j = i + 1; j < n; j++) {\n if (a[j] > prev) {\n tc++;\n prev = a[j];\n } else {\n const newValCount = Math.floor(prev / a[j]) + 1;\n tc += newValCount;\n prev = a[j] * newValCount;\n }\n }\n\n // Lesser\n prev = 0;\n for (let j = i - 1; j >= 0; j--) {\n if (a[j] > prev) {\n tc++;\n prev = a[j];\n } else {\n const newValCount = Math.floor(prev / a[j]) + 1;\n tc += newValCount;\n prev = a[j] * newValCount;\n }\n }\n\n count = Math.min(count, tc);\n }\n\n console.log(count);\n}\n"}, {"source_code": "'use strict';\n\nconst { timeStamp } = require('console');\nconst { checkPrime } = require('crypto');\nconst { Z_FIXED } = require('zlib');\n\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst l = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\n \nconst ra = ()=>readline().split(' ').map(a=>+a)\n\nconst times = (target, using)=>{\n return Math.max(1, Math.ceil(target/using))\n}\n\nconst calc = (n, A)=>{\n let ans = Infinity;\n for (let i=0; i=0; j--){\n let ops = times(target, A[j]);\n cur += ops;\n target = ops*A[j]+1;\n }\n target = 1;\n for (let j=i+1; j lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\n\n\nconst calc = (n, a)=>{\n let count = Infinity;\n for (let i = 0; i < n; i++) {\n let localCount = 0;\n let prev = 0;\n for (let j = i + 1; j < n; j++) {\n if (prev === 0) {\n localCount++;\n prev = a[j];\n } else {\n let match = Math.floor(prev / a[j]);\n let diff = match + 1;\n localCount += diff;\n prev = a[j] * diff;\n }\n }\n prev = 0;\n for (let j = i - 1; j >= 0; j--) {\n if (prev === 0) {\n localCount++;\n prev = a[j];\n } else {\n let match = Math.floor(prev / a[j]);\n let diff = match + 1;\n localCount += diff;\n prev = a[j] * diff;\n }\n }\n count = Math.min(count, localCount);\n }\n\n return count;\n};\n\nfunction main() {\n // let T = +readline();\n // for (let t = 1; t <= T; t++){\n let n = +readline();\n let a = ra();\n \n console.log(`${calc(n, a)}`);\n // }\n}\n\n\n\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = 1;\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n let cnt = Infinity;\r\n const left = (pos) => {\r\n let op = 0,\r\n prev = 0;\r\n for (let i = pos - 1; i >= 0; i--) {\r\n if (prev === 0) {\r\n prev = -1 * arr[i];\r\n op++;\r\n } else {\r\n let k = Math.floor(Math.abs(prev) / arr[i]) + 1;\r\n prev = k * arr[i] * -1;\r\n op += k;\r\n }\r\n }\r\n return op;\r\n };\r\n const right = (pos) => {\r\n let op = 0,\r\n prev = 0;\r\n for (let i = pos + 1; i < n; i++) {\r\n if (prev === 0) {\r\n op++;\r\n prev = arr[i];\r\n } else {\r\n let k = Math.floor(prev / arr[i]) + 1;\r\n prev = k * arr[i];\r\n op += k;\r\n }\r\n }\r\n return op;\r\n };\r\n for (let i = 0; i < n; i++) cnt = Math.min(cnt, left(i) + right(i));\r\n console.log(cnt);\r\n }\r\n};\r\nsolve();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst lineReader = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet inputPos = 0;\r\nconst inputWords = [];\r\nlineReader.on('line', (line) => {\r\n inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));\r\n});\r\nlineReader.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(inputWords[inputPos++]));\r\n}\r\nfunction nextStr() {\r\n return inputWords[inputPos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nfunction main() {\r\n let n = nextInt();\r\n const a = af(n);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = nextInt();\r\n }\r\n let ans = 1e15;\r\n for (let i = 0; i < n; i++) {\r\n let t = 0;\r\n let last = 0;\r\n for (let j = i - 1; j >= 0; j--) {\r\n let need = Math.ceil((last + 1) / a[j]);\r\n t += need;\r\n last = need * a[j];\r\n }\r\n last = 0;\r\n for (let j = i + 1; j < n; j++) {\r\n let need = Math.ceil((last + 1) / a[j]);\r\n t += need;\r\n last = need * a[j];\r\n }\r\n ans = Math.min(ans, t);\r\n }\r\n printf(\"%d\\n\", ans);\r\n}\r\n"}], "src_uid": "da2fb0ea61808905a133021223f6148d"} {"nl": {"description": "Valera's finally decided to go on holiday! He packed up and headed for a ski resort.Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions: Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1. The path contains as many objects as possible (k is maximal). Help Valera. Find such path that meets all the criteria of our hero!", "input_spec": "The first line contains integer n (1 ≤ n ≤ 105) — the number of objects. The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel. The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.", "output_spec": "In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.", "sample_inputs": ["5\n0 0 0 0 1\n0 1 2 3 4", "5\n0 0 1 0 1\n0 1 2 2 4", "4\n1 0 0 0\n2 3 4 2"], "sample_outputs": ["5\n1 2 3 4 5", "2\n4 5", "1\n1"], "notes": null}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tobjects = tokenizeIntegers(readline()),\n\t\tparents = tokenizeIntegers(readline()),\n\t\tnumChildren = new Array(n+1);\n\tobjects.unshift(null);\n\tparents.unshift(null);\n\tfor (var i = 1; i <= n; ++i) {\n\t\tnumChildren[i] = 0;\n\t}\n\tfor (var i = 1; i <= n; ++i) {\n\t\tnumChildren[parents[i]] += 1;\n\t}\n\tvar maxLength = 0, maxPath = [];\n\tfor (var i = 1; i <= n; ++i) {\n\t\tif (objects[i] == 1) {\n\t\t\tvar path = [i], node = i;\n\t\t\twhile (true) {\n\t\t\t\tnode = parents[node];\n\t\t\t\t//print(node, numChildren[node]);\n\t\t\t\tif (node == 0 || numChildren[node] > 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tpath.push(node);\n\t\t\t}\n\t\t\tif (path.length > maxLength) {\n\t\t\t\tmaxLength = path.length;\n\t\t\t\tmaxPath = path;\n\t\t\t}\n\t\t}\n\t}\n\tprint(maxLength);\n\tmaxPath.reverse();\n\tprint(maxPath.join(' '));\n}\n\nmain();\n"}], "negative_code": [], "src_uid": "a704760d5ccd09d08558ea98d6007835"} {"nl": {"description": " Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters \"a\", \"b\" and \"c\". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string \"abc\" as a substring. A valid replacement of a character is replacing it with \"a\", \"b\" or \"c\".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \\le n, q \\le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters \"a\", \"b\" and \"c\". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \\le i \\le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is \"a\", \"b\" or \"c\".", "output_spec": "For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain \"abc\" as a substring.", "sample_inputs": ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"], "sample_outputs": ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"], "notes": "NoteLet's consider the state of the string after each query: $$$s =$$$ \"abcabcabc\". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bbcaccabb\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bbcabcabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bbcbbcbbc\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bccabcabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bccbbcbbc\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcaabcabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcbbc\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabbcabc\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcabb\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabccabc\". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcabb\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabccaac\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcaac\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"bcabccaab\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"bcabbcaab\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"ccabccaab\". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ \"ccabbcaab\". This string does not contain \"abc\" as a substring. $$$s =$$$ \"ccaaccaab\". In this case the string does not contain \"abc\" as a substring and no replacements are needed."}, "positive_code": [{"source_code": "const check = (str,pos,n)=>{\r\n let issub;\r\n if(str[pos]===\"a\"){\r\n if(pos+2>n) issub = false;\r\n else if((str[pos+1]===\"b\")&&(str[pos+2]===\"c\")) issub = true;\r\n else issub = false;\r\n }\r\n else if(str[pos]===\"b\"){\r\n if((pos===1)||(pos+1>n)) issub = false;\r\n else if((str[pos-1]===\"a\")&&(str[pos+1]===\"c\")) issub = true;\r\n else issub = false;\r\n }\r\n else{\r\n if(pos<3) issub = false;\r\n else if((str[pos-1]===\"b\")&&(str[pos-2]===\"a\")) issub = true;\r\n else issub = false;\r\n }\r\n return issub;\r\n}\r\nconst solve = (n,str,q)=>{\r\n let cnt = 0;\r\n for(let i=1;i<=n;i++){\r\n if((str[i]===\"a\")&&((i+2)<=n)){\r\n if((str[i+1]===\"b\")&&(str[i+2]===\"c\")) cnt++;\r\n }\r\n }\r\n for(let i=0;iparseInt(cur));\r\n let str = (\" \"+readline().trim()).split(\"\");\r\n let q = [];\r\n for(let i=0;i dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n \r\nfunction main () {\r\n\tlet [n, q] = rna();\r\n\tlet s = rl().split('');\r\n \r\n\tlet cnt = 0;\r\n\tfor (let i = 0; i < s.length - 2; i++) {\r\n\t\tif (s.slice(i, i + 3).join('') == 'abc') {\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t}\r\n \r\n\twhile (q--) {\r\n\t\tlet [i, c] = ra();i--;\r\n\t\tconst olds = s.slice(Math.max(0, i-2), i+3).join('');\r\n\t\ts[i] = c;\r\n\t\tconst news = s.slice(Math.max(0, i-2), i+3).join('');\r\n \r\n\t\tconst dif = news.includes('abc') - olds.includes('abc');\r\n\t\tcnt += dif;\r\n\t\tconsole.log(cnt);\r\n\t}\r\n}"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet [n, q] = rna();\r\n\tlet s = rl().split('');\r\n\r\n\tlet cnt = 0;\r\n\tfor (let i = 0; i < s.length - 2; i++) {\r\n\t\tif (s.slice(i, i + 3).join('') == 'abc') {\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t}\r\n\r\n\twhile (q--) {\r\n\t\tlet [i, c] = ra();i--;\r\n\t\tconst olds = s.slice(Math.max(0, i-2), i+3).join('');\r\n\t\ts[i] = c;\r\n\t\tconst news = s.slice(Math.max(0, i-2), i+3).join('');\r\n\r\n\t\tconst dif = news.includes('abc') - olds.includes('abc');\r\n\t\tcnt += dif;\r\n\t\tconsole.log(cnt);\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "db473ad780a93983667d12b1357c6e2f"} {"nl": {"description": "Let us define two functions f and g on positive integer numbers. You need to process Q queries. In each query, you will be given three integers l, r and k. You need to print the number of integers x between l and r inclusive, such that g(x) = k. ", "input_spec": "The first line of the input contains an integer Q (1 ≤ Q ≤ 2 × 105) representing the number of queries. Q lines follow, each of which contains 3 integers l, r and k (1 ≤ l ≤ r ≤ 106, 1 ≤ k ≤ 9).", "output_spec": "For each query, print a single line containing the answer for that query.", "sample_inputs": ["4\n22 73 9\n45 64 6\n47 55 7\n2 62 4", "4\n82 94 6\n56 67 4\n28 59 9\n39 74 4"], "sample_outputs": ["1\n4\n0\n8", "3\n1\n1\n5"], "notes": "NoteIn the first example: g(33) = 9 as g(33) = g(3 × 3) = g(9) = 9 g(47) = g(48) = g(60) = g(61) = 6 There are no such integers between 47 and 55. g(4) = g(14) = g(22) = g(27) = g(39) = g(40) = g(41) = g(58) = 4 "}, "positive_code": [{"source_code": "n=1000000\na=new Array(n)\ncounts=new Array(9)\ncountAts=new Array(9)\nfor(i=0;i<9;i++)\n{\n\tcounts[i]=0\n\tcountAts[i]=new Array(n+1)\n\tcountAts[i][0]=0\n}\nfor(i=0;i9)\n\t{\n\t\tif(a[cur-1]!==undefined)\n\t\t{\n\t\t\tcur=a[cur-1]\n\t\t\tbreak\n\t\t}\n\t\tpro=1\n\t\twhile(cur>1)\n\t\t{\n\t\t\tpro*=cur%10>1?cur%10:1\n\t\t\tcur=parseInt(cur/10)\n\t\t}\n\t\tcur=pro\n\t}\n\ta[i]=cur\n\tcounts[cur-1]++\n\tfor(j=0;j<9;j++)\n\t\tcountAts[j][i+1]=counts[j]\n}\n\nq=Number(readline())\nans=new Array(q)\nfor(i=0;i9)\n\t{\n\t\tif(a[cur-1]!==undefined)\n\t\t{\n\t\t\tcur=a[cur-1]\n\t\t\tbreak\n\t\t}\n\t\tpro=1\n\t\twhile(cur>1)\n\t\t{\n\t\t\tpro*=cur%10>1?cur%10:1\n\t\t\tcur=parseInt(cur/10)\n\t\t}\n\t\tcur=pro\n\t}\n\ta[i]=cur\n\tcounts[cur-1]++\n\tfor(j=0;j<9;j++)\n\t\tcountAts[j][i+1]=counts[j]\n}\n\nq=parseInt(readline())\nfor(i=0;i9)\n\t{\n\t\tif(a[cur-1]!==undefined)\n\t\t{\n\t\t\tcur=a[cur-1]\n\t\t\tbreak\n\t\t}\n\t\tpro=1\n\t\twhile(cur>1)\n\t\t{\n\t\t\tpro*=cur%10>1?cur%10:1\n\t\t\tcur=parseInt(cur/10)\n\t\t}\n\t\tcur=pro\n\t}\n\ta[i]=cur\n\tcounts[cur-1]++\n\tfor(j=0;j<9;j++)\n\t\tcountAts[j][i+1]=counts[j]\n}\n\nq=Number(readline())\nans=new Array(q)\nfor(i=0;i9)\n\t{\n\t\tif(a[cur-1]!==undefined)\n\t\t{\n\t\t\tcur=a[cur-1]\n\t\t\tbreak\n\t\t}\n\t\tpro=1\n\t\twhile(cur>1)\n\t\t{\n\t\t\tpro*=cur%10>1?cur%10:1\n\t\t\tcur=parseInt(cur/10)\n\t\t}\n\t\tcur=pro\n\t}\n\ta[i]=cur\n\tcounts[cur-1]++\n\tfor(j=0;j<9;j++)\n\t\tcountAts[j][i+1]=counts[j]\n}\n\nq=Number(readline())\nans=Array(q)\nfor(i=0;i9)\n\t{\n\t\tif(a[cur-1]!==undefined)\n\t\t{\n\t\t\tcur=a[cur-1]\n\t\t\tbreak\n\t\t}\n\t\tpro=1\n\t\twhile(cur>1)\n\t\t{\n\t\t\tpro*=cur%10>1?cur%10:1\n\t\t\tcur=parseInt(cur/10)\n\t\t}\n\t\tcur=pro\n\t}\n\ta[i]=cur\n\tcounts[cur-1]++\n\tfor(j=0;j<9;j++)\n\t\tcountAts[j][i+1]=counts[j]\n}\n\nq=parseInt(readline())\nans=new Array(q)\nfor(i=0;i9)\n\t{\n\t\tif(a[cur-1]!==undefined)\n\t\t{\n\t\t\tcur=a[cur-1]\n\t\t\tbreak\n\t\t}\n\t\tpro=1\n\t\twhile(cur>1)\n\t\t{\n\t\t\tpro*=cur%10>1?cur%10:1\n\t\t\tcur=parseInt(cur/10)\n\t\t}\n\t\tcur=pro\n\t}\n\ta[i]=cur\n\tcounts[cur-1]++\n\tfor(j=0;j<9;j++)\n\t\tcountAts[j][i+1]=counts[j]\n}\n\nfor(i=0;i= 0; i--) {\n var dig = Number(num[i])\n \n if (!hasZeros && dig === 0) {\n hasZeros = true\n }\n \n dig %= 3\n \n sumMod += dig\n sumMod %= 3\n \n if (dig !== 0 && scapeGoats[dig - 1].length < 2) {\n scapeGoats[dig - 1].push(i)\n }\n}\n\nimpossible = false\n\nvar del = []\nvar del2 = []\nif (sumMod !== 0) {\n if (scapeGoats[sumMod - 1].length > 0) {\n del.push(scapeGoats[sumMod - 1][0])\n }\n if (scapeGoats[1 - (sumMod - 1)].length === 2 && num.length > 2) {\n del2 = del2.concat(scapeGoats[1 - (sumMod - 1)])\n }\n}\n\n\nvar ans = num\n\nfor (var i = 0; i < del.length; i++) {\n ans = ans.substring(0, del[i]) + ans.substring(del[i] + 1)\n}\n\nans = ans.replace(/^0*/, '')\n\nif (ans === '' && hasZeros) {\n ans = '0'\n}\n\nvar ans2 = num\n\nfor (var i = 0; i < del2.length; i++) {\n ans2 = ans2.substring(0, del2[i]) + ans2.substring(del2[i] + 1)\n}\n\nans2 = ans2.replace(/^0*/, '')\n\nif (ans2 === '' && hasZeros) {\n ans2 = '0'\n}\n\nif (sumMod !== 0 && del.length === 0) {\n ans = ''\n}\n\nif (sumMod !== 0 && del2.length === 0) {\n ans2 = ''\n}\n\nif (ans === '' && ans2 === '') {\n print('-1')\n} else {\n print(ans.length < ans2.length? ans2 : ans)\n}\n"}, {"source_code": " var d = readline();\n var sum = 0;\n for(var i = 0; i < d.length; i += 1) {\n sum += parseInt(d[i]);\n sum %= 3;\n }\n var done = false;\n if(sum === 0) {\n print(d);\n done = true;\n }\n if(!done) {\n var target = -1;\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === sum) {\n target = i;\n break;\n }\n }\n var target2 = [];\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === 3 - sum) {\n target2.unshift(i);\n if(target2.length === 2) {\n break;\n }\n }\n }\n if(target !== -1 && target !== 0) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n } else if(target === 0) {\n var zeroes = 0;\n for(var i = 1; i 0) {\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print(0);\n done = true;\n } else {\n print(-1);\n done = true;\n }\n } else {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n if(res.length === 0) {\n print(-1);\n done = true;\n } else {\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length === 0) {\n res = '0';\n }\n print(res);\n done = true;\n }\n } else if(!done) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n }\n }\n } else if(!done && target === -1) {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n if(res.length === 0) {\n print(-1);\n done = true;\n } else {\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length === 0) {\n res = '0';\n }\n print(res);\n done = true;\n }\n } else if(!done) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n }\n }\n }\n if(!done) {\n print(-1);\n }"}], "negative_code": [{"source_code": "// Neither neat nor clear :(\nvar num = readline()\n\nvar scapeGoats = [[], []]\n\nvar hasZeros = false\n\nvar sumMod = 0\n\nfor (var i = num.length - 1; i >= 0; i--) {\n var dig = Number(num[i])\n \n if (!hasZeros && dig === 0) {\n hasZeros = true\n }\n \n dig %= 3\n \n sumMod += dig\n sumMod %= 3\n \n if (dig !== 0 && scapeGoats[dig - 1].length < 2) {\n scapeGoats[dig - 1].push(i)\n }\n}\n\nimpossible = false\n\nvar del = []\n\nif (sumMod !== 0) {\n if (scapeGoats[sumMod - 1].length > 0) {\n del.push(scapeGoats[sumMod - 1][0])\n } else if (scapeGoats[1 - (sumMod - 1)].length === 2 && num.length > 2) {\n del = del.concat(scapeGoats[1 - (sumMod - 1)])\n } else {\n impossible = true\n }\n}\n\nif (impossible) {\n print('-1')\n} else {\n var ans = num\n\n for (var i = 0; i < del.length; i++) {\n ans = ans.substring(0, del[i]) + ans.substring(del[i] + 1)\n }\n \n ans = ans.replace(/^0*/, '')\n \n if (ans === '' && hasZeros) {\n ans = '0'\n }\n \n if (ans === '') {\n print('-1')\n } else {\n print(ans)\n }\n}"}, {"source_code": "// Neither neat nor clear :(\nvar num = readline()\n\nvar scapeGoats = [[], []]\n\nvar hasZeros = false\n\nvar sumMod = 0\n\nfor (var i = num.length - 1; i >= 0; i--) {\n var dig = Number(num[i])\n \n if (!hasZeros && dig === 0) {\n hasZeros = true\n }\n \n dig %= 3\n \n sumMod += dig\n sumMod %= 3\n \n if (dig !== 0 && scapeGoats[dig - 1].length < 2) {\n scapeGoats[dig - 1].push(i)\n }\n}\n\nimpossible = false\n\nvar del = []\nvar del2 = []\nif (sumMod !== 0) {\n if (scapeGoats[sumMod - 1].length > 0) {\n del.push(scapeGoats[sumMod - 1][0])\n }\n if (scapeGoats[1 - (sumMod - 1)].length === 2 && num.length > 2) {\n del2 = del2.concat(scapeGoats[1 - (sumMod - 1)])\n }\n}\n\n\nvar ans = num\n\nfor (var i = 0; i < del.length; i++) {\n ans = ans.substring(0, del[i]) + ans.substring(del[i] + 1)\n}\n\nans = ans.replace(/^0*/, '')\n\nif (ans === '' && hasZeros) {\n ans = '0'\n}\n\nvar ans2 = num\n\nfor (var i = 0; i < del2.length; i++) {\n ans2 = ans2.substring(0, del2[i]) + ans2.substring(del2[i] + 1)\n}\n\nans2 = ans2.replace(/^0*/, '')\n\nif (ans2 === '' && hasZeros) {\n ans2 = '0'\n}\n\nif (del.length === 0) {\n ans = ''\n}\n\nif (del2.length === 0) {\n ans2 = ''\n}\n\nif (ans === '' && ans2 === '') {\n print('-1')\n} else {\n print(ans.length < ans2.length? ans2 : ans)\n}\n"}, {"source_code": "\n var d = readline();\n var sum = 0;\n for(var i = 0; i < d.length; i += 1) {\n sum += parseInt(d[i]);\n sum %= 3;\n }\n var done = false;\n if(sum === 0) {\n print(d);\n done = true;\n }\n if(!done) {\n var target = -1;\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === sum) {\n target = i;\n break;\n }\n }\n var target2 = [];\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === 3 - sum) {\n target2.unshift(i);\n if(target2.length === 2) {\n break;\n }\n }\n }\n if(target !== -1 && target !== 0) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n } else if(target === 0) {\n var zeroes = 0;\n for(var i = 1; i 0) {\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print(0);\n done = true;\n } else {\n print(-1);\n done = true;\n }\n } else {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > 0) {\n print(res);\n done = true;\n }\n }\n }\n } else if(!done && target === -1) {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > 0) {\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print('0');\n done = true;\n }\n } else if(!done) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n }\n }\n }\n if(!done) {\n print(-1);\n }"}, {"source_code": "\n var d = readline();\n var sum = 0;\n for(var i = 0; i < d.length; i += 1) {\n sum += parseInt(d[i]);\n sum %= 3;\n }\n var done = false;\n if(sum === 0) {\n print(d);\n done = true;\n }\n if(!done) {\n var target = -1;\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === sum) {\n target = i;\n break;\n }\n }\n var target2 = [];\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === 3 - sum) {\n target2.unshift(i);\n if(target2.length === 2) {\n break;\n }\n }\n }\n if(target !== -1 && target !== 0) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n } else if(target === 0) {\n var zeroes = 0;\n for(var i = 1; i 0) {\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print(0);\n done = true;\n } else {\n print(-1);\n done = true;\n }\n } else {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > zeroes || res.length === 1) {\n res = res.slice(zeroes);\n if(res.length === 0) {\n res = '0';\n }\n print(res);\n done = true;\n }\n }\n }\n } else if(!done && target === -1) {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n if(res.length > zeroes || res.length === 1) {\n res = res.slice(zeroes);\n if(res.length === 0) {\n res = '0';\n }\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print('0');\n done = true;\n }\n } else if(!done) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n }\n }\n }\n if(!done) {\n print(-1);\n }\n "}, {"source_code": " var d = readline();\n var sum = 0;\n for(var i = 0; i < d.length; i += 1) {\n sum += parseInt(d[i]);\n sum %= 3;\n }\n var done = false;\n if(sum === 0) {\n print(d);\n done = true;\n }\n if(!done) {\n var target = -1;\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === sum) {\n target = i;\n break;\n }\n }\n var target2 = [];\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === 3 - sum) {\n target2.unshift(i);\n if(target2.length === 2) {\n break;\n }\n }\n }\n if(target !== -1 && target !== 0) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n } else if(target === 0) {\n var zeroes = 0;\n for(var i = 1; i 0) {\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print(0);\n done = true;\n } else {\n print(-1);\n done = true;\n }\n } else {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > 0) {\n print(res);\n done = true;\n }\n }\n }\n } else if(!done && target === -1) {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n if(res.length > zeroes || res.length === 1) {\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print('0');\n done = true;\n }\n } else if(!done) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n }\n }\n }\n if(!done) {\n print(-1);\n }"}, {"source_code": " var d = readline();\n var sum = 0;\n for(var i = 0; i < d.length; i += 1) {\n sum += parseInt(d[i]);\n sum %= 3;\n }\n var done = false\n if(sum === 0) {\n print(d);\n done = true;\n }\n if(!done) {\n var target = -1;\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === sum) {\n target = i;\n break;\n }\n }\n var target2 = [];\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === 3 - sum) {\n target2.unshift(i);\n if(target2.length === 2) {\n break;\n }\n }\n }\n if(target === 0) {\n var zeroes = 0;\n for(var i = 1; i 0) {\n print(res);\n\n done = true;\n }\n } else {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > 0) {\n print(res);\n done = true;\n }\n }\n }\n } else if(!done && target === -1) {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > 0) {\n print(res);\n done = true;\n } \n } else if(!done) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n }\n }\n }\n if(!done) {\n print(-1);\n }"}, {"source_code": " var d = readline();\n var sum = 0;\n for(var i = 0; i < d.length; i += 1) {\n sum += parseInt(d[i]);\n sum %= 3;\n }\n var done = false\n if(sum === 0) {\n print(d);\n done = true;\n }\n if(!done) {\n var target = -1;\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === sum) {\n target = i;\n break;\n }\n }\n var target2 = [];\n for(var i = d.length - 1; i >= 0; i -= 1) {\n if(parseInt(d[i]) % 3 === 3 - sum) {\n target2.unshift(i);\n if(target2.length === 2) {\n break;\n }\n }\n }\n if(target === 0) {\n var zeroes = 0;\n for(var i = 1; i 0) {\n print(res);\n done = true;\n } else if(d[d.length - 1] === '0') {\n print(0);\n done = true;\n } else {\n print(-1);\n done = true;\n }\n } else {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > 0) {\n print(res);\n done = true;\n }\n }\n }\n } else if(!done && target === -1) {\n if(target2.length === 2) {\n var res = d.slice(0, target2[0]) + d.slice(target2[0] + 1, target2[1]) + d.slice(target2[1] + 1, d.length);\n var zeroes = 0;\n for(var i = 0; i < res.length; i += 1) {\n if(res[i] === '0') {\n zeroes += 1;\n } else {\n break;\n }\n }\n res = res.slice(zeroes);\n if(res.length > 0) {\n print(res);\n done = true;\n } \n } else if(!done) {\n print(d.slice(0, target) + d.slice(target + 1, d.length));\n done = true;\n }\n }\n }\n if(!done) {\n print(-1);\n }\n"}], "src_uid": "df9942d1eb66b1f3b5c6b665b446cd3e"} {"nl": {"description": "The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?", "input_spec": "The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \\leq n \\leq 99$$$, $$$0 \\leq k \\leq 2\\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively.", "output_spec": "Print \"YES\", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print \"NO\". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is \"#\" if that cell has a hotel on it, or \".\" if not.", "sample_inputs": ["7 2", "5 3"], "sample_outputs": ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."], "notes": null}, "positive_code": [{"source_code": "var line = readline().split(' ');\nvar n = +line[0];\nvar k = +line[1];\nvar ok = 1;\nvar a = '';\nvar b = '';\nvar c = '';\nvar d = '';\nfor(var i = 0; i < n; i ++){\n a = a + '.';\n d = d + '.';\n}\nif(k % 2){\n if(k > n-2){\n for(var i = 0; i < n; i ++){\n if(i == 0 || i == n-1){\n b = b + '.';\n } else{\n b = b + '#';\n }\n }\n k -= n-2;\n for(var i = 0; i < n; i ++){\n if(i == 0 || i == n-1){\n c = c + '.';\n } else{\n if(i < n/2){\n if(i <= k / 2){\n c = c + '#';\n } else{\n c = c + '.';\n }\n } else{\n if(n - 1 - i <= k / 2){\n c = c + '#';\n } else{\n c = c + '.';\n }\n }\n }\n }\n } else{\n for(var i = 0; i < n; i ++){\n if(i < n / 2){\n if(i < (n - k) / 2){\n b = b + '.';\n } else{\n b = b + '#';\n }\n } else{\n if(n - 1 - i < (n - k) / 2){\n b = b + '.';\n } else{\n b = b + '#';\n }\n }\n }\n c = a;\n }\n} else{\n for(var i = 0; i < n; i ++){\n if(i > 0 && i <= k / 2){\n b = b + '#';\n c = c + '#';\n } else{\n b = b + '.';\n c = c + '.';\n }\n }\n}\nprint('YES');\nprint(a);\nprint(b);\nprint(c);\nprint(d);"}], "negative_code": [{"source_code": "var line = readline().split(' ');\nvar n = +line[0];\nvar k = +line[1];\nvar ok = 1;\nvar a = '';\nvar b = '';\nvar c = '';\nvar d = '';\nif(k > n-2 && k % 2){\n ok = 0;\n}\nfor(var i = 0; i < n; i ++){\n a = a + '.';\n d = d + '.';\n}\nif(k % 2){\n for(var i = 0; i < n; i ++){\n if(i < n / 2){\n if(i < (n - k) / 2){\n b = b + '.';\n } else{\n b = b + '#';\n }\n } else{\n if(n - 1 - i < (n - k) / 2){\n b = b + '.';\n } else{\n b = b + '#';\n }\n }\n }\n c = a;\n} else{\n for(var i = 0; i < n; i ++){\n if(i > 0 && i <= k / 2){\n b = b + '#';\n c = c + '#';\n } else{\n b = b + '.';\n c = c + '.';\n }\n }\n}\nif(ok){\n print('YES');\n print(a);\n print(b);\n print(c);\n print(d);\n} else{\n print('NO');\n}"}], "src_uid": "2669feb8200769869c4b2c29012059ed"} {"nl": {"description": "Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: the graph contains exactly 2n + p edges; the graph doesn't contain self-loops and multiple edges; for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p 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 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; ) — 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 + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — 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": "print(function(t) {\n\tvar ans=[];\n\tfor(var i=0;i dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet [n, m, k] = rna();\r\n\r\n\t\tif \t\t(m < n - 1) \t\t\tconsole.log('NO'); // non connected graph\r\n\t\telse if (m > n * (n - 1) / 2)\tconsole.log('NO'); // multiedged graph\r\n\t\telse if (k < 2)\t\t\t\tconsole.log('NO');\r\n\t\telse if (k == 2)\t\t\t\tconsole.log(n == 1 \t\t\t\t ? 'YES' : 'NO');\r\n\t\telse if (k == 3) \t\t\t\tconsole.log(m == n * (n - 1) / 2 ? 'YES' : 'NO');\r\n\t\telse if (k > 3) \t\t\t\tconsole.log('YES');\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet [n, m, k] = rna();\r\n\r\n\t\tfunction put (ans) { console.log(ans); }\r\n\r\n\t\tif (m < n - 1) \t\t\t\tput('NO');\r\n\t\telse if (m > n*(n-1)/2)\t \tput('NO');\r\n\t\telse if (k < 2)\t\t\t\tput('NO');\r\n\t\telse if (k == 2)\t\t\tput(n == 1 ? 'YES' : 'NO');\r\n\t\telse if (k == 3) \t\t\tput(m == n * (n - 1) / 2 ? 'YES' : 'NO');\r\n\t\telse if (k > 3) \t\t\tput('YES');\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, m, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n let l = ((n) * (n - 1n)) / 2n;\r\n if(l1n) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n continue;\r\n }\r\n if(l===m){\r\n if(k>2n) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n continue;\r\n }\r\n if(k>3n) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n \r\n }\r\n};\r\nsolve();"}, {"source_code": "/* Common Template Starts */\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n\t return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n/* Common Template Ends */\r\nfunction main() {\r\n let Q = +(readline()); // Read Input\r\n\r\n for (let q = 0; q < Q; q++) {\r\n let [N, M, K] = readline().split(\" \").map((a) => parseInt(a));\r\n\r\n let full = N * (N-1) / 2;\r\n\r\n if (M < N - 1 || M > full) {\r\n console.log(\"NO\");\r\n continue;\r\n }\r\n\r\n if (M === full) {\r\n if (N === 1) {\r\n\tconsole.log(K >= 2? \"YES\": \"NO\");\r\n } else {\r\n\tconsole.log(K >= 3? \"YES\": \"NO\");\r\n }\r\n continue;\r\n }\r\n\r\n console.log(K >= 4? \"YES\": \"NO\");\r\n }\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "var dataitr;\nvar stdin_input = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\n\nconst rl = () => dataitr.next().value.trim();\nconst rn = () => Number(rl());\nconst ra = () => rl().split(' ');\nconst rna = () => ra().map(x => Number(x));\n\nfunction main () {\n\tlet t = rn();\n\twhile (t--) {\n\t\tlet [n, m, k] = rna();\n\n\t\tif (k < 2) console.log('NO');\n\t\tif (k == 2) console.log(n == 1 ? 'YES' : 'NO');\n\t\tif (k == 3) console.log(m == n * (n - 1) / 2 ? 'YES' : 'NO');\n\t\tif (k > 3) console.log('YES');\n\t}\n}\n\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet [n, m, k] = rna();\r\n\r\n\t\tif (k < 3) console.log('NO');\r\n\t\tif (k > 3) console.log('YES');\r\n\t\tif (k == 3) console.log(m == n * (n - 1) / 2 ? 'YES' : 'NO');\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, m, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let l = (BigInt(n) * BigInt(n - 1)) / 2n;\r\n if (m > l) {\r\n console.log(\"NO\");\r\n continue;\r\n }\r\n if (n === 1) {\r\n console.log(\"YES\");\r\n continue;\r\n }\r\n if (n > m) {\r\n if (n - m > 1) console.log(\"NO\");\r\n else {\r\n if (m < k - 1) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n } else {\r\n if (k - 1 === 0) console.log(\"NO\");\r\n else if (k - 1 > Math.floor(n / 2)) console.log(\"YES\");\r\n else {\r\n if (BigInt(m) >= l) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n }\r\n }\r\n};\r\nsolve();"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, m, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let l = (BigInt(n) * BigInt(n - 1)) / 2n;\r\n if (m > l) {\r\n console.log(\"NO\");\r\n continue;\r\n }\r\n if (n === 1) {\r\n console.log(\"YES\");\r\n continue;\r\n }\r\n if (n > m) {\r\n if (n - m > 1) console.log(\"NO\");\r\n else {\r\n if (m < k - 1) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n } else {\r\n if (k - 1 === 0) console.log(\"NO\");\r\n else if (k - 1 < Math.floor(n / 2)) console.log(\"YES\");\r\n else {\r\n if (BigInt(m) >= l) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, m, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n if (n > m) {\r\n if (n - m > 1) console.log(\"NO\");\r\n else {\r\n if (m < k - 1) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n } else {\r\n if (k - 1 === 0) console.log(\"NO\");\r\n else if (k - 1 > Math.floor(n / 2)) console.log(\"YES\");\r\n else {\r\n let l = (BigInt(n) * BigInt(n - 1)) / 2n;\r\n if (BigInt(m) >= l) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "/* Common Template Starts */\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n\t return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n/* Common Template Ends */\r\nfunction main() {\r\n let Q = +(readline()); // Read Input\r\n\r\n for (let q = 0; q < Q; q++) {\r\n let [N, M, K] = readline().split(\" \").map((a) => parseInt(a));\r\n\r\n let full = N * (N-1) / 2;\r\n\r\n if (M < N - 1 || M > full) {\r\n console.log(\"NO\");\r\n continue;\r\n }\r\n\r\n if (M === full) {\r\n console.log(K >= 3? \"YES\": \"NO\");\r\n continue;\r\n }\r\n\r\n console.log(K >= 4? \"YES\": \"NO\");\r\n }\r\n}\r\n\r\n"}], "src_uid": "f853a61741518cb884c00c8b760692aa"} {"nl": {"description": "You are given three positive integers $$$n$$$, $$$a$$$ and $$$b$$$. You have to construct a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters such that each substring of length $$$a$$$ has exactly $$$b$$$ distinct letters. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.Recall that the substring $$$s[l \\dots r]$$$ is the string $$$s_l, s_{l+1}, \\dots, s_{r}$$$ and its length is $$$r - l + 1$$$. In this problem you are only interested in substrings of length $$$a$$$.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains three space-separated integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \\le a \\le n \\le 2000, 1 \\le b \\le \\min(26, a)$$$), where $$$n$$$ is the length of the required string, $$$a$$$ is the length of a substring and $$$b$$$ is the required number of distinct letters in each substring of length $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\\sum n \\le 2000$$$).", "output_spec": "For each test case, print the answer — such a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters that each substring of length $$$a$$$ has exactly $$$b$$$ distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists.", "sample_inputs": ["4\n7 5 3\n6 1 1\n6 6 1\n5 2 2"], "sample_outputs": ["tleelte\nqwerty\nvvvvvv\nabcde"], "notes": "NoteIn the first test case of the example, consider all the substrings of length $$$5$$$: \"tleel\": it contains $$$3$$$ distinct (unique) letters, \"leelt\": it contains $$$3$$$ distinct (unique) letters, \"eelte\": it contains $$$3$$$ distinct (unique) letters. "}, "positive_code": [{"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const inp = getInts()\n\n let s = ''\n let init = 'a'.charCodeAt()\n for (let i = 0; i < inp[2]; ++i) {\n s += String.fromCharCode(init ++)\n }\n \n while (s.length < inp[1]) s += 'a'\n while (s.length < inp[0]) s += s\n print(s.slice(0, inp[0]))\n }\n}"}, {"source_code": "var t = parseInt(readline());\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nvar ch = 'a';\nvar acode = ch.charCodeAt(0);\n\n\nfor (var tt = 0; tt < t; tt++) {\n var inp = readline().split(' ').map(Number);\n var n = inp[0];\n var a = inp[1];\n var b = inp[2] - 1;\n var res = '';\n \n for (var i = 0; i < n; i++) {\n var pos = i % a;\n if (pos > b) {\n res += String.fromCharCode(acode+b);\n } else {\n res += String.fromCharCode(acode+pos);\n }\n }\n \n write(res+'\\n');\n}\n"}, {"source_code": "var n = +readline();\nvar string = 'abcdefghijklmnopqrstuvwxyz';\nfor(var i = 0; i < n; i++){\n var s = readline().split(' ').map(Number);\n var x = s[0];\n var a = s[1];\n var b = s[2];\n \n var _ = parseInt(x/a);\n var str = string.slice(0,b).repeat(parseInt(b/a)+1).slice(0,a);\n str = str.repeat(parseInt(x/b) + 1).slice(0,x);\n write(str + '\\n');\n}"}, {"source_code": "var n = +readline();\n\nvar alp = 'abcdefghijklmnopqrstuvwxyz';\nfor (var i = 0; i < n; i ++) {\n var s = readline().split(' ').map(Number);\n \n var x = s[0];\n var a = s[1];\n var b = s[2];\n \n var rp = parseInt(x / a);\n var str = alp.slice(0, b).repeat(parseInt(b / a) + 1).slice(0, a);\n str = str.repeat(parseInt(x / b) + 1).slice(0, x);\n write(str + '\\n');\n}\n\n// abc abcab abcabab"}, {"source_code": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(n); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _iterableToArrayLimit(arr, i) { if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar t = readline();\n\nwhile (t--) {\n var _readline$split = readline().split(' '),\n _readline$split2 = _slicedToArray(_readline$split, 3),\n n = _readline$split2[0],\n a = _readline$split2[1],\n b = _readline$split2[2]; //1, 2, 3\n\n\n var charCods = [];\n\n for (var i = 97; i < 97 + 26; i++) {\n charCods.push(i);\n }\n\n var str = String.fromCharCode.apply(String, charCods).slice(0, b);\n str = str.repeat(Math.ceil(n / str.length)).slice(0, n);\n print(str);\n}"}, {"source_code": "var n = Number(readline());\nvar inp;\nfor(var i = 0; i < n; i++){\n inp = readline().split(' ').map(cur => Number(cur));\n stringGenerator(...inp);\n}\n\nfunction stringGenerator (l,a,b){\n\nconst arr = [...Array(26)].map((cur,i) => String.fromCharCode(97+i));\n\nvar res = [];\n\nfor(var i = 0; i< l ;i++){\nres.push(arr[i%b]); \n} \n \n print(res.join(''));\n}"}, {"source_code": "var t = parseInt(readline());\n\nfunction mapper(num) {\n return +num;\n}\n\nvar alph = ['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\nfor (var i = 0; i < t; i++) {\n var data = readline().split(' ').map(mapper);\n var n = data[0];\n var a = data[1];\n var b = data[2];\n \n var letters = alph.slice(0, b);\n var str = letters.join('');\n var res = '';\n \n for(var j = 0; j < Math.ceil(n / b); j++) {\n res += str;\n }\n\n res = res.slice(0, n);\n print(res);\n}"}, {"source_code": "var range = readline();\n\nfor(var i=0;i parseInt(x));\n var arrange = []; \n var startString = 97;\n \n for(var j=0;j= input_lines.length;\n}\nvar letters = \"qwertyuiopasdfghjklzxcvbnm\";\nfunction main() {\n var t = parseInt(input());\n for (var casen = 0; casen < t; casen++) {\n var _a = input().split(' ').map(function (x) { return parseInt(x); }), n = _a[0], a = _a[1], b = _a[2];\n var answer = [];\n while (answer.length < n) {\n for (var i = 0; i < b - 1; i++) {\n answer.push(letters.charAt(i));\n }\n for (var i = 0; i < a - (b - 1); i++) {\n answer.push(letters.charAt(b - 1));\n }\n }\n answer = answer.splice(0, n);\n console.log(\"\".concat.apply(\"\", answer));\n }\n}\n"}, {"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nlet input = ''\nlet ptr = 0\nprocess.stdin.on('data', (i) => {\n input += i\n})\n\n\nprocess.stdin.on('end', () => {\n input = input.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main()\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if (inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt() {\n return parseInt(input[ptr++])\n}\n\nfunction readString() {\n return input[ptr++]\n}\n\nfunction readStrings() {\n return input[ptr++].split(' ')\n}\n\nfunction readInts() {\n return input[ptr++].split(' ').map(a => parseInt(a))\n}\n\nfunction main() {\n let t = readInt()\n while(t--) {\n const [n, a, b] = readInts()\n let ans = ''\n let ax = ''\n for(let i = 0, j = 97; i < b; i++) {\n ax += String.fromCharCode(j)\n j++\n }\n ax = ax.padEnd(a, 'a')\n ans = ans.padEnd(n, ax)\n wr(ans)\n }\n}"}, {"source_code": "\n//DISABLE THIS LINE END ENABLE NEXT\n//const rl = require('readline').createInterface({input: require('fs').createReadStream('input.txt')});\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nconst print = console.log\nconst write = (...args) => {\n process.stdout.write(args.join(' ') );\n}\nconst lines = []\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\n\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n \nfunction repeat(pattern, count) {\n if (count < 1) return '';\n var result = '';\n while (count > 1) {\n if (count & 1) result += pattern;\n count >>= 1, pattern += pattern;\n }\n return result + pattern;\n}\n\nfunction main() {\n\tvar parr = \"abcdefghijklmnopqrstuvwxyz\";//.split();\n\tvar y = +readline()\n\twhile(y > 0) {\n\t\tvar z = readline().split(' ');\n\t\tvar n = +z[0];\n\t\tvar a = +z[1];\n\t\tvar b = +z[2];\n\t\tvar res = \"\";\n\t\t//[0,...., b-1] from parr\n\t\tvar res = \"\";\n\t\tvar p = parr.substring(0,b);\n\t\tvar count = Math.floor(n / p.length);\n\t\tres = repeat(p, count);\n\t\twhile(res.length < n) {\n\t\t\tres += p;\n\t\t}\n\t\tres = res.substring(0, n);\n\t\tif (y > 1) {\n\t\t\twrite(res + '\\n');\n\t\t} else {\n\t\t\twrite(res);\n\t\t}\n\t\ty--;\n\t}\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const [n, a, b] = d.split(' ').map(Number);\n let ans = '';\n\n let i = 0;\n while (ans.length < n) {\n ans += String.fromCharCode((i % 26) % b + 97);\n i++;\n\n if (i === a) {\n i = 0;\n }\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "const processData = (input) => {\n let exp = /\\s+/;\n let arr = input.split(exp);\n arr = arr.map(el => +el);\n let l = arr[0];\n arr = arr.slice(1);\n const a = 97;\n for (let i = 0; i < l; i++){\n let temp = arr.slice(i*3,i*3+3);\n let str = \"\";\n let max = temp[2] + a;\n let current = a;\n for (let i = 0; i < temp[0]; i++) {\n str += String.fromCharCode(current);\n current++;\n if (current === max) current = a;\n }\n console.log(str);\n }\n}\n\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\n_input = \"\";\nprocess.stdin.on(\"data\", function (input) {\n _input += input;\n});\n\nprocess.stdin.on(\"end\", function () {\n processData(_input);\n});\n\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nvar inputString = '';\nvar currentLine = 0;\nprocess.stdin.on('data', function (input) { inputString += input; });\nprocess.stdin.on('end', function (_) { inputString = inputString.split('\\n'); main(); });\nvar readline = function () { return inputString[currentLine++]; };\nfunction main() {\n var tests = parseInt(readline());\n var abc = ' abcdefghijklmnopqrstuvwxyz';\n while (tests--) {\n var _a = readline().split(' ').map(function (x) { return parseInt(x); }), n = _a[0], a = _a[1], b = _a[2];\n var copies = Math.floor(n / b) + 1;\n var ans = '';\n while (b) {\n ans += abc[b];\n b--;\n }\n ans = ans.repeat(copies);\n ans = ans.substr(0, n);\n console.log(ans);\n }\n}\n"}, {"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nfunction print(x) {\n console.log(x);\n}\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on(\"end\", () => {\n inputString = inputString.split(\"\\n\");\n main();\n});\nfunction readline() {\n return inputString[currentLine++];\n}\n\n//-----------main fucntion-----------\n\nfunction main() {\n var T = parseInt(readline());\n while (T--) {\n var input1 = readline().split(' ').map(x => parseInt(x));\n var a = input1[0]\n var b = input1[1]\n var c = input1[2]\n var str=\"\"\n for(var i=0; i {\n const num = +lines[0]\n for (let i=0; i +x)\n let res = ''\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const init = () => {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n let inputString = '';\n let currentLine = 0;\n\n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n\n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main(); \n });\n\n global.readline = () => {\n return inputString[currentLine++];\n };\n};\n\nif (typeof readline === 'undefined') {\n init();\n}\n\nconst print = (...args) => {\n console.log(...args);\n};\n\nconst main = () => {\n let t = Number(readline());\n while (t--) {\n let [n, a, b] = readline().split(' ').map(x => parseInt(x));\n let s = '';\n let ci = 0;\n const CHAR_CODE_BASE = 97;\n for (let i = 0; i < n; i++) {\n s += String.fromCharCode(ci + CHAR_CODE_BASE);\n ci++;\n ci %= b;\n }\n print(s);\n }\n};\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin; \n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction solve(n, a, b) {\n let res = '';\n let substr = '';\n let alphabet = 'abcdefghijklmnopqrstuvwxyz';\n for (let i = 0; i < b; i++) {\n substr += alphabet[i];\n }\n for (let i = 0; i < n; i++) {\n res += substr[i % substr.length];\n }\n return res;\n}\n\nfunction main() {\n const t = parseInt(readLine());\n for (let i = 0; i < t; i++) {\n // let n = parseInt(readLine());\n let [n, a, b] = readLine().split(' ').map((val) => parseInt(val));\n let res = solve(n, a, b);\n console.log(res);\n }\n //process.stdout.write(\"hello: \");\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n let n = parseInt(readline(), 10);\n const Acode = 'a'.charCodeAt(0)\n\n for (var j = 0; j < n; j++) {\n const [n, a ,b] = readline().split(\" \").map(e => parseInt(e));\n let res = '';\n var alaphabet = [];\n for (var i = 0; i < b; i++) {\n alaphabet.push(String.fromCharCode((Acode+i)));\n }\n for (var i = 0; i < n; i++) {\n res += alaphabet[i % alaphabet.length];\n }\n console.log(res);\n }\n \n}\n"}], "negative_code": [{"source_code": "var n = +readline();\n\nvar alp = 'abcdefghijklmnopqrstuvwxyz';\nfor (var i = 0; i < n; i ++) {\n var s = readline().split(' ').map(Number);\n \n var x = s[0];\n var a = s[1];\n var b = s[2];\n \n var rp = parseInt(x / a);\n var str = ('a'.repeat(a - b) + alp.slice(0, b)).repeat(rp);\n if (rp * a < x) {\n var diff = x - (a * rp);\n str += alp.slice(-diff);\n }\n \n write(str + '\\n');\n}"}, {"source_code": "var n = +readline();\n\nvar alp = 'abcdefghijklmnopqrstuvwxyz';\nfor (var i = 0; i < n; i ++) {\n var s = readline().split(' ').map(Number);\n \n var x = s[0];\n var a = s[1];\n var b = s[2];\n \n var rp = parseInt(x / a);\n var str = ('a'.repeat(a - b) + alp.slice(0, b)).repeat(rp);\n if (rp * a < x) {\n var diff = x - (a * rp);\n str += str.slice(-diff);\n }\n \n write(str + '\\n');\n}"}, {"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nlet input = ''\nlet ptr = 0\nprocess.stdin.on('data', (i) => {\n input += i\n})\n\n\nprocess.stdin.on('end', () => {\n input = input.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main()\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if (inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt() {\n return parseInt(input[ptr++])\n}\n\nfunction readString() {\n return input[ptr++]\n}\n\nfunction readStrings() {\n return input[ptr++].split(' ')\n}\n\nfunction readInts() {\n return input[ptr++].split(' ').map(a => parseInt(a))\n}\n\nfunction main() {\n let t = readInt()\n while(t--) {\n const [n, a, b] = readInts()\n let ans = ''\n let ax = ''\n for(let i = 0, j = 97; i < a; i++) {\n ax += String.fromCharCode(j)\n j++\n if(j - 96 > b) j = 97\n if(j > 121) j = 97\n }\n // wr(ax)\n ans = ans.padEnd(n, ax)\n wr(ans)\n }\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const [n, a, b] = d.split(' ').map(Number);\n let ans = '';\n\n for (let i = 0; i < n; i++) {\n ans += String.fromCharCode( (i % 26) % b + 97 );\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nfunction print(x) {\n console.log(x);\n}\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on(\"end\", () => {\n inputString = inputString.split(\"\\n\");\n main();\n});\nfunction readline() {\n return inputString[currentLine++];\n}\n\n//-----------main fucntion-----------\n\nfunction main() {\n var T = parseInt(readline());\n while (T--) {\n var input1 = readline().split(' ').map(x => parseInt(x));\n var a = input1[0]\n var b = input1[1]\n var c = input1[2]\n var str=\"\"\n for(var i=0; i 1){\n\t\tfor(j = i; j <= n*2; j++){\n\t\t\tif(signs[j] == 0){\n\t\t\t\tsigns[i]--;\n\t\t\t\tsigns[j]++;\n\t\t\t\tcnt += j - i;\n\t\t\t}\n\t\t\tif(signs[i] == 1){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nwrite(cnt);"}, {"source_code": "function Stack(){this.a=[]}function Queue(){this.l=new Stack,this.r=new Stack}function Reader(){this.b=[],this.c=0}function Writer(){this.l=[\"\"],this.c=0}Array.prototype.back=function(){return this[this.length-1]},Math.gcd=function(t,i){return i?gcd(i,t%i):t},Math.lcm=function(t,i){return t/gcd(t,i)*i},Math.sign=function(t){return(t>0)-(0>t)},Math.cmp=function(t,i){return(+t>+i)-(+i>+t)},Math.icmp=function(t,i){return(+i>+t)-(+t>+i)},Stack.prototype.empty=function(){return 0==this.a.length},Stack.prototype.push=function(t){this.a.push(t)},Stack.prototype.pop=function(){return this.empty()?void 0:this.a.pop()},Stack.prototype.top=function(){return this.empty()?void 0:this.a[this.a.length-1]},Stack.prototype.clear=function(){this.a=[]},Stack.prototype.size=function(){return this.a.length},Queue.prototype.push=function(t){this.l.push(t)},Queue.prototype.empty=function(){return this.r.empty()&&this.l.empty()},Queue.prototype.pop=function(){if(this.r.empty())for(;!this.l.empty();)this.r.push(this.l.pop());return this.r.empty()?void 0:this.r.pop()},Queue.prototype.front=function(){if(this.r.empty())for(;!this.l.empty();)this.r.push(this.l.pop());return this.r.empty()?void 0:this.r.top()},Queue.prototype.size=function(){return l.size()+r.size()},Queue.prototype.clear=function(){l.clear(),r.clear()},Reader.prototype.next=function(){return this.c==this.b.length&&(this.c=0,this.b=readline().split(\" \")),this.b[this.c++]},Writer.prototype.print=function(t){this.l[this.c]+=t},Writer.prototype.println=function(t){this.l[this.c]+=t,this.l.push(\"\"),++this.c},Writer.prototype.flush=function(){print(this.l.join(\"\\n\")),this.l=[]};\n\nvar cnt = new Array(10000);\n\nfunction main(cin, cout)\n{\n var n = +cin.next();\n var t;\n for(var i = 0; i < 10000; ++i)\n cnt[i] = 0;\n for(var i = 0; i < n; ++i)\n {\n t = +cin.next();\n cnt[t]++; \n }\n var ans = 0;\n for(var i = 1; i <= n; ++i)\n {\n while(cnt[i] > 1)\n {\n var j;\n for(j = i + 1; cnt[j]; ++j);\n --cnt[i];\n ++cnt[j];\n ans += j - i;\n }\n }\n cout.print(ans);\n}\n\nvar cin = new Reader();\nvar cout = new Writer(); \n\nmain(cin, cout);\n\ncout.flush();"}, {"source_code": "/**\n * Created by Det on 25.05.2015.\n */\n(function main() {\n var line1 = readline().split(' ');\n var line2 = readline().split(' ');\n var money = 0;\n var sold = [];\n var lish = [];\n\n for (var i=0; i < line2.length; i++){\n if (sold[line2[i]]) {\n lish.push(sold[line2[i]]);\n } else {\n sold[line2[i]] = line2[i];\n }\n }\n for (var i=0; i < lish.length; i++) {\n for (var j=+lish[i]; j < (sold.length + lish.length); j++) {\n if(!sold[j]){\n sold[j] = 1;\n money += j - lish[i];\n break;\n }\n }\n }\n\n print(money);\n})();\n"}, {"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = false;\n\n this.solveCase = function() {\n var res , i , j , fl , cn , temp ;\n res = 0 ;\n this.arr = this.arr.sort( function( left , right ) { return left - right ; } ) ;\n prev = -1 ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( this.arr[ i ] <= prev ) {\n \t\tres += prev + 1 - this.arr[ i ] ;\n \t\tprev = prev + 1 ;\n \t}\n \telse {\n \t\tprev = this.arr[ i ] ;\n \t}\n }\n print( res );\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n this.arr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n this.arr.push( irObj.nextInt() ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.arr = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "function main() {\n var numBadges = parseInt(readline());\n\n var badges = readline().split(\" \");\n \n\n badges.sort(function(a, b) {\n return a - b;\n });\n for(var i = 0; i < badges.length; ++i) {\n badges[i] = parseInt(badges[i]);\n }\n //print(badges);\n var numChanges = 0;\n for(var i = 0; i < badges.length-1; i++) {\n while(badges[i] >= badges[i+1]) {\n ++numChanges;\n ++badges[i+1];\n }\n }\n return numChanges;\n\n}\n\nprint(main());"}], "negative_code": [{"source_code": "function countUniqueElements(input,output){\n\tfor(var i = 0; i < input.length; i++){\n\t\toutput[+input[i]]++;\n\t}\n}\n\nvar n = +readline(), a = readline().split(\" \").map(Number);\nvar signs = {}, cnt = 0;\n\nfor(i = 1; i <= n; i++){\n\tsigns[i] = 0;\n}\n\ncountUniqueElements(a,signs);\n\nfor(sign in signs){\n\tif(signs[sign] == 0){\n\t\tcnt++;\n\t}\n}\n\nwrite(cnt);"}, {"source_code": "function countUniqueElements(input,output){\n\tfor(var i = 0; i < input.length; i++){\n\t\toutput[+input[i]]++;\n\t}\n}\n\nvar n = +readline(), a = readline().split(\" \").map(Number);\nvar signs = {}, cnt = 0;\n\nfor(i = 1; i <= n; i++){\n\tsigns[i] = 0;\n}\n\ncountUniqueElements(a,signs);\n\nfor(i = 1; i <= n; i++){\n\tif(signs[i] > 1){\n\t\tfor(j = signs[i]; j <= n; j++){\n\t\t\tif(signs[j] == 0){\n\t\t\t\tsigns[i]--;\n\t\t\t\tsigns[j]++;\n\t\t\t\tcnt += j - i;\n\t\t\t}\n\t\t}\n\t}\n}\n\nwrite(cnt);"}, {"source_code": "function main() {\n var numBadges = parseInt(readline());\n\n var badges = readline().split(\" \");\n badges.map(parseInt);\n\n badges.sort();\n var numChanges = 0;\n for(var i = 0; i < badges.length-1; i++) {\n if(badges[i] == badges[i+1]) {\n ++numChanges;\n ++badges[i+1];\n }\n }\n return numChanges;\n\n}\n\nprint(main());"}, {"source_code": "function main() {\n var numBadges = parseInt(readline());\n\n var badges = readline().split(\" \");\n badges.map(parseInt);\n\n badges.sort(function(a, b) {\n return a - b;\n });\n var numChanges = 0;\n for(var i = 0; i < badges.length-1; i++) {\n if(badges[i] == badges[i+1]) {\n ++numChanges;\n ++badges[i+1];\n }\n }\n return numChanges;\n\n}\n\nprint(main());"}, {"source_code": "function main() {\n var numBadges = parseInt(readline());\n\n var badges = readline().split(\" \");\n badges.map(parseInt);\n\n badges.sort(function(a, b) {\n return a - b;\n });\n //print(badges);\n var numChanges = 0;\n for(var i = 0; i < badges.length-1; i++) {\n while(badges[i] >= badges[i+1]) {\n ++numChanges;\n ++badges[i+1];\n }\n }\n return numChanges;\n\n}\n\nprint(main());"}], "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 - 6.", "sample_inputs": ["1 2 1 2"], "sample_outputs": ["0.666666666667"], "notes": null}, "positive_code": [{"source_code": "// problem name: Archer\n// problem link: https://codeforces.com/problemset/problem/312/B\n// contest link: https://codeforces.com/contest/312\n// author: reyad\n// time: (?)\n\n'use strict';\n\nfunction main() {\n\tlet a = nextInt();\n\tlet b = nextInt();\n\tlet c = nextInt();\n\tlet d = nextInt();\n\n\tlet p = a / b; // probability that SmallR wins in the first round\n\tlet q = c / d; // probability that Zanoes wins in the first round\n\n\t// let's say SmallR hit the target in the first round, then\n\t// probabilty of win is (a/b) i.e. simply p(as p = (a/b))\n\t\n\t// now let's say SmallR was not successful in the first round, then two cases arise\n\t// (i) Zanoes will hit the target and win\n\t// (ii) Zanoes will miss the target and SmallR would again have some chance to shoot\n\t// In the second case, SmallR's probalility of win will be\n\t// (probability that SmallR loses in the first round *\n\t// probability that Zanoes loses in the first round * \n\t// probability that SmallR wins in the second round)\n\t// and it is (\n\t// \t(1 - (a/b)) * \n\t//\t\t\t \t(1 - (c/d)) *\n\t//\t\t\t \t(a/b)\n\t//\t\t\t )\n\t// or simply (\n\t//\t\t\t\t(1 - p) * \n\t//\t\t\t\t(1 - q) *\n\t//\t\t\t\tp\n\t//\t\t\t )\n\n\t// this process will go on for third round\n\t// and the probability of win in the third round is ((1-p) * (1-q) * (1-p) * (1-q) * p)\n\t// i.e. simply ((1-p)^2 * (1-q)^2 * p)\n\n\t// for fourth round, it'll be ((1-p)^3 * (1-q)^3 * p)\n\t// and this will go on for infinity\n\n\t// and by adding those probabilities of each round\n\t// we'll be able to found the answer i.e.\n\t// the probability that SmallR will win\n\n\t// now, ans = p + ((1-p) * (1-q) * p) + ((1-p)^2 * (1-q)^2 * p) + ...\n\t// let us consider, (1-p) * (1-q) = r\n\t// then, ans = p + (r * p) + (r^2 * p) + (r^3 + p) + ...\n\t// as 0 < p < 1 and 0 < q < 1, then 0 < r < 1\n\t// then, ans = p / (1 - r) (by applying formula of geometric progression)\n\n\tlet r = (1 - p) * (1 - q);\n\tlet ans = p / (1 - r);\n\tconsole.log(ans);\n}\n\n\n\n// reader and main caller\n\nlet readline = require('readline');\n\nlet rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n\tterminal: false\n});\n\nlet inputBuf = [];\nlet inputBufCnt = 0;\nlet tk = []\nlet tkCnt = 0;\n\nfunction nextLine() {\n\treturn inputBuf[inputBufCnt++];\n}\nfunction next() {\n\tif(tkCnt == tk.length) {\n\t\ttk = inputBuf[inputBufCnt++].split(' ');\n\t\ttkCnt = 0;\n\t}\n\treturn tk[tkCnt++];\n}\nfunction nextInt() {\n\treturn parseInt(next());\n}\nfunction nextDouble() {\n\treturn parseFloat(next());\n}\n\nrl.on('line', (line) => {\n\tinputBuf.push(line);\n}).on('close', () => {\n\tmain();\n});\n"}], "negative_code": [], "src_uid": "7b932b2d3ab65a353b18d81cf533a54e"} {"nl": {"description": "This is an interactive problem.We hid from you a permutation $$$p$$$ of length $$$n$$$, consisting of the elements from $$$1$$$ to $$$n$$$. You want to guess it. To do that, you can give us 2 different indices $$$i$$$ and $$$j$$$, and we will reply with $$$p_{i} \\bmod p_{j}$$$ (remainder of division $$$p_{i}$$$ by $$$p_{j}$$$).We have enough patience to answer at most $$$2 \\cdot n$$$ queries, so you should fit in this constraint. Can you do it?As a reminder, a permutation of length $$$n$$$ 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 only line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$) — length of the permutation.", "output_spec": null, "sample_inputs": ["3\n\n1\n\n2\n\n1\n\n0"], "sample_outputs": ["? 1 2\n\n? 3 2\n\n? 1 3\n\n? 2 1\n\n! 1 3 2"], "notes": null}, "positive_code": [{"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n\n let inputResolve;\n let inputNext = i => new Promise(resolve => inputResolve = resolve);\n process.stdin.on('data', c => inputResolve(+c));\n let n = await inputNext();\n if (n == 1) {\n console.log('! 1');\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n // setTimeout(() => {\n // process.stdout.write(`! ${a.filter(v => v).length} ${Arr(n - 1, 1, 0, i => i).join(' ')}\\n`);\n // process.exit();\n // }, 800);\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n console.log('?', i, j);\n let mij = await inputNext()\n console.log('?', j, i);\n let mji = await inputNext()\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n console.log('!', a.slice(1).join(' '));\n process.exit();\n})();\n\n"}, {"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n\n let inputResolve;\n let inputNext = i => new Promise(resolve => inputResolve = resolve);\n process.stdin.on('data', c => inputResolve(+c));\n let n = await inputNext();\n if (n == 1) {\n process.stdout.write(`! 1\\n`);\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n // setTimeout(() => {\n // process.stdout.write(`! ${a.filter(v => v).length} ${Arr(n - 1, 1, 0, i => i).join(' ')}\\n`);\n // process.exit();\n // }, 800);\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n process.stdout.write(`? ${i} ${j}\\n`);\n let mij = await inputNext()\n process.stdout.write(`? ${j} ${i}\\n`);\n let mji = await inputNext()\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n process.stdout.write(`! ${a.slice(1).join(' ')}\\n`);\n process.exit();\n})();\n\n"}, {"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n\n function* genMain() {\n let n = yield;\n if (n == 1) {\n console.log('! 1');\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n console.log('?', i, j);\n let mij = yield;\n console.log('?', j, i);\n let mji = yield;\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n console.log('!', a.slice(1).join(' '));\n process.exit();\n }\n let main = genMain();\n main.next();\n process.stdin.on('data', c => main.next(+c));\n\n})();\n\n"}], "negative_code": [{"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n let next = i => new Promise(resolve => process.stdin.on('data', c => resolve(+c)));\n let n = await next();\n if (n == 1) {\n process.stdout.write(`! 1\\n`);\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n setTimeout(() => {\n process.stdout.write(`! ${a.filter(v => v).length}\\n`);\n process.exit();\n }, 800);\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n process.stdout.write(`? ${i} ${j}\\n`);\n let mij = await next();\n process.stdout.write(`? ${j} ${i}\\n`);\n let mji = await next();\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n process.stdout.write(`! ${a.slice(1).join(' ')}\\n`);\n process.exit();\n})();\n\n"}, {"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n let next = i => new Promise(resolve => process.stdin.on('data', c => resolve(+c)));\n let n = await next();\n if (n == 1) {\n process.stdout.write(`! 1\\n`);\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n setTimeout(() => {\n process.stdout.write(`! ${Arr(n, 1, 0, i => i).join(' ')}\\n`);\n process.exit();\n }, 800);\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n process.stdout.write(`? ${i} ${j}\\n`);\n let mij = await next();\n process.stdout.write(`? ${j} ${i}\\n`);\n let mji = await next();\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n process.stdout.write(`! ${a.slice(1).join(' ')}\\n`);\n process.exit();\n})();\n\n"}, {"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n let next = i => new Promise(resolve => process.stdin.on('data', c => resolve(+c)));\n let n = await next();\n if (n == 1) {\n process.stdout.write(`! 1\\n`);\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n setTimeout(() => {\n process.stdout.write(`! ${a.filter(v => v).length} ${Arr(n - 1, 1, 0, i => i).join(' ')}\\n`);\n process.exit();\n }, 800);\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n process.stdout.write(`? ${i} ${j}\\n`);\n let mij = await next();\n process.stdout.write(`? ${j} ${i}\\n`);\n let mji = await next();\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n process.stdout.write(`! ${a.slice(1).join(' ')}\\n`);\n process.exit();\n})();\n\n"}, {"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n let next = i => new Promise(resolve => process.stdin.on('data', c => resolve(+c)));\n let n = await next();\n if (n == 1) {\n process.stdout.write(`! 1\\n`);\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n setTimeout(() => {\n process.stdout.write(`! ${a.filter(v => v).length} ${a.slice(1).join(' ')}\\n`);\n process.exit();\n }, 800);\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n process.stdout.write(`? ${i} ${j}\\n`);\n let mij = await next();\n process.stdout.write(`? ${j} ${i}\\n`);\n let mji = await next();\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n process.stdout.write(`! ${a.slice(1).join(' ')}\\n`);\n process.exit();\n})();\n\n"}, {"source_code": "// let input = '';\n// let inputResolve;\n// let inputPromise = new Promise(resolve => inputResolve = resolve);\n// process.stdin.on('data', c => input += c);\n// process.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, step, fn) {\n let res;\n for (let i = a; i <= b; i += step) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, step, fn, init) {\n if (!step) {\n return a < b\n ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))\n : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))\n }\n let arr = Array(Math.max(a, b) + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n// let MOD = 998244353n;\n// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);\n// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);\n// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;\n// let nCk = (n, k) => {\n// return gt[n] * rgt[k] * rgt[n - k] % MOD;\n// }\n// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1\n\n(async () => {\n // await inputPromise;\n // let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n // out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a;\n let next = i => new Promise(resolve => process.stdin.on('data', c => resolve(+c)));\n let n = await next();\n if (n == 1) {\n process.stdout.write(`! 1\\n`);\n process.exit();\n }\n let a = Array(n + 1);\n let i = 1;\n let j = 2;\n setTimeout(() => {\n process.stdout.write(`! ${Arr(n, 1, -1, i => i).join(' ')}\\n`);\n process.exit();\n }, 800);\n while (1) {\n while (i <= n && a[i] || i == j) i++;\n while (j <= n && a[j] || i == j) j++;\n if (i > n || j > n) break;\n process.stdout.write(`? ${i} ${j}\\n`);\n let mij = await next();\n process.stdout.write(`? ${j} ${i}\\n`);\n let mji = await next();\n if (mij > mji) a[i++] = mij;\n else a[j++] = mji;\n }\n For(1, n, 1, i => a[i] ? null : a[i] = n);\n process.stdout.write(`! ${a.slice(1).join(' ')}\\n`);\n process.exit();\n})();\n\n"}], "src_uid": "9bfbd68e61f4d2f3d404fd0413aded35"} {"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, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y. 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  ≤  n  ≤  1000, , 1 ≤ w ≤ 1000) — 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, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — 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 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) 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, 2} 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, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, 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": "\nfunction sa(n, w, weights, nicest, friends){\n \n var friendsTo = [];\n \n for(var i=0;i 0){\n var current = queue.pop();\n if(visited[current]){\n continue;\n }\n visited[current] = true;\n newSet.push(current);\n for(var j=0;j= 0; j--) {\n var sumWeight = 0;\n var sumPrice = 0;\n for(var k=0;k j) ? dp[j]: Math.max(dp[j], dp[j-weight] + nice);\n }\n dp[j] = (sumWeight > j) ? dp[j]: Math.max(dp[j], dp[j-sumWeight] + sumPrice);\n }\n }\n return dp[w];\n \n \n }\n var f = readline().split(\" \").map(Number);\n var n = f[0];\n var m = f[1];\n var w = f[2];\n var weights = readline().split(\" \").map(Number);\n var nicest = readline().split(\" \").map(Number);\n var friends = [];\n for(var i=0;i a-1));\n }\n print(sa(n, w, weights, nicest, friends));"}], "negative_code": [{"source_code": "\nfunction sa(n, w, weights, nicest, friends){\n \n var friendsTo = [];\n \n for(var i=0;i 0){\n var current = queue.pop();\n if(visited[current]){\n continue;\n }\n visited[current] = true;\n newSet.push(current);\n for(var j=0;j a-1));\n }\n print(sa(n, w, weights, nicest, friends));"}, {"source_code": "\nfunction sa(n, w, weights, nicest, friends){\n \n var friendsTo = [];\n \n for(var i=0;i 0){\n var current = queue.pop();\n if(visited[current]){\n continue;\n }\n visited[current] = true;\n newSet.push(current);\n for(var j=0;j a-1));\n }\n print(sa(n, w, weights, nicest, friends));"}], "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 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) 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": "var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n') ;\n let str = arr[0],stack = [];\n let len = str.length;\n for(i=0;i= 0; i--) {\r\n let [x, y] = b[i];\r\n x--, y--;\r\n if (!visr.has(x) && sx < m || !visc.has(y) && sy < n) {\r\n res = mul(res, k);\r\n }\r\n if (sx === m && sy === n) break;\r\n if (!visr.has(x)) visr.add(x);\r\n if (!visc.has(y)) visc.add(y);\r\n if (!vx.has(y)) {\r\n vx.add(y);\r\n sx++;\r\n }\r\n if (!vy.has(x)) {\r\n vy.add(x);\r\n sy++;\r\n }\r\n }\r\n return res;\r\n}\r\nconst MOD = 998244353;\r\nfunction mul(...args) {\r\n if (args.length === 0) throw new Error('参数不能为空');\r\n if (args.length === 1) return args[0];\r\n const [a, b] = args;\r\n if (args.length > 2) return mul(mul(a, b), ...args.slice(2));\r\n return ((a >> 16) * b % MOD * 65536 + (a & 65535) * b) % MOD;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = a[3];\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(a, b) {\r\n let [n, m, k, q] = a;\r\n let visr = new Set(),\r\n visc = new Set(),\r\n res = 0,\r\n vx = new Set(),\r\n vy = new Set(),\r\n sx = 0,\r\n sy = 0;\r\n for (let i = q - 1; i >= 0; i--) {\r\n let [x, y] = b[i];\r\n x--, y--;\r\n if (!visr.has(x) && sx < m || !visc.has(y) && sy < n) {\r\n res++;\r\n }\r\n if (sx === m && sy === n) break;\r\n if (!visr.has(x)) visr.add(x);\r\n if (!visc.has(y)) visc.add(y);\r\n if (!vx.has(y)) {\r\n vx.add(y);\r\n sx++;\r\n }\r\n if (!vy.has(x)) {\r\n vy.add(x);\r\n sy++;\r\n }\r\n }\r\n return power(k, res);\r\n}\r\nconst MOD = 998244353;\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(...args) {\r\n if (args.length === 0) throw new Error('参数不能为空');\r\n if (args.length === 1) return args[0];\r\n const [a, b] = args;\r\n if (args.length > 2) return mul(mul(a, b), ...args.slice(2));\r\n return ((a >> 16) * b % MOD * 65536 + (a & 65535) * b) % MOD;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = a[3];\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, m, k, q] = lines[l++].trim().split(' ').map(Number)\n const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))\n l += q\n output[i] = solve(n, m, k, qs)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, m, k, qs) {\n const rows = {}\n const cols = {}\n let cr = 0\n let cc = 0\n let count = 0\n for (let i = qs.length - 1; i >= 0; i--) {\n let [x, y] = qs[i]\n x--; y--\n //\n let ok = 0\n if (!rows[x] && cc < m) {\n ok = 1\n }\n if (!cols[y] && cr < n) {\n ok = 1\n }\n if (ok) count++\n // if (n > 1 && m > 1) {\n // } else if (n > 1) {\n // if (!rows[x] && cc < m) {\n // count++\n // }\n // // } else if (m > 1) {\n // } else {\n // if (!cols[y] && cr < n) {\n // count++\n // }\n // }\n //\n if (!rows[x]) {\n rows[x] = 1\n cr++\n }\n if (!cols[y]) {\n cols[y] = 1\n cc++\n }\n // console.log(cr, cc)\n }\n return pow(k, count)\n}\n\nconst MOD = 998244353\nconst MOD_CUT = ((1 << 20) * (1 << 20)) % MOD\nfunction add(a, b) {\n return (a + b) % MOD\n}\nfunction minus(a, b) {\n return add(add(a, -b), MOD)\n}\nfunction mul(a, b) {\n let r = (a >> 20) * (b >> 20) * MOD_CUT\n + (a & 0xfff00000) * (b & 0xfffff)\n + (a & 0xfffff) * b\n return r % MOD\n}\nfunction pow(a, b) {\n let r = 1\n let base = a\n while (b) {\n if (b & 1) {\n r = mul(r, base)\n }\n b >>= 1\n base = mul(base, base)\n }\n return r\n}\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(a, b) {\r\n let [n, m, k, q] = a;\r\n b = b.map(arr => arr.map(num => num - 1));\r\n let visr = new Array(n),\r\n visc = new Array(n),\r\n res = 1,\r\n v1 = new Array(n),\r\n v2 = new Array(n),\r\n sum1 = 0,\r\n sum2 = 0;\r\n for (let i = q - 1; i >= 0; i--) {\r\n const [x, y] = b[i];\r\n if (!visr[x] && sum1 < n || !visc[y] && sum2 < m) {\r\n res = mul(res, k);\r\n }\r\n visr[x] = 1;\r\n visc[y] = 1;\r\n if (!v1[y]) {\r\n v1[y] = 1;\r\n sum1++;\r\n }\r\n if (!v2[x]) {\r\n v2[x] = 1;\r\n sum2++;\r\n }\r\n }\r\n return res;\r\n}\r\nconst MOD = 998244353;\r\nfunction mul(...args) {\r\n if (args.length === 0) throw new Error('参数不能为空');\r\n if (args.length === 1) return args[0];\r\n const [a, b] = args;\r\n if (args.length > 2) return mul(mul(a, b), ...args.slice(2));\r\n return ((a >> 16) * b % MOD * 65536 + (a & 65535) * b) % MOD;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = a[3];\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "src_uid": "623a373709e4c4223fbbb9a320f307b1"} {"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$$$) — 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 — 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": "var cases = parseInt(readline());\r\nvar t;\r\nfor(t=0; t parseInt(e));;\r\n var indexSpy = 0;\r\n var occorences = {};\r\n\r\n // count all occorence of two number in the array\r\n array.forEach( (e) => {\r\n occorences[e] = occorences[e] ? (occorences[e] += 1) : 1;\r\n });\r\n\r\n // find number with one occorence\r\n if( occorences[ Object.keys(occorences)[0] ] == 1){\r\n indexSpy = Object.keys(occorences)[0];\r\n } else {\r\n indexSpy = Object.keys(occorences)[1];\r\n }\r\n\r\n // print output\r\n print( array.indexOf( parseInt(indexSpy) ) + 1 );\r\n\r\n}\r\n"}, {"source_code": "// 1512 A - Spy detected!\r\n\r\n// number of test case\r\nvar numTests = parseInt( readline() );\r\n\r\nfor (var numTest = 0; numTest < numTests; numTest++) {\r\n \r\n // input data \r\n var n = parseInt( readline() );\r\n var array = readline().split(' ').map( e => parseInt(e));;\r\n var indexSpy = 0;\r\n var occorences = {};\r\n\r\n array.forEach( (e) => {\r\n occorences[e] = occorences[e] ? (occorences[e] += 1) : 1;\r\n });\r\n \r\n // print(JSON.stringify(occorences));\r\n\r\n if( occorences[ Object.keys(occorences)[0] ] == 1){\r\n indexSpy = Object.keys(occorences)[0];\r\n } else {\r\n indexSpy = Object.keys(occorences)[1];\r\n }\r\n \r\n // print('spy: '+indexSpy);\r\n indexSpy = array.indexOf( parseInt(indexSpy) ) + 1 ;\r\n // print('index: '+indexSpy+'\\n');\r\n \r\n print(indexSpy);\r\n \r\n}"}, {"source_code": "var testCases = readline();\r\nvar count;\r\nvar resultObj;\r\nvar result;\r\nvar length0;\r\nfor (var i = 0; i < testCases; i++) {\r\n resultObj = {};\r\n length0= readline();\r\n var arr = readline().split(' ');\r\n for (var val of arr) { \r\n if(!resultObj[val]) resultObj[val] = 1;\r\n else resultObj[val]++;\r\n }\r\n for (var key in resultObj) {\r\n if(resultObj[key] == 1) result = key;\r\n }\r\n print(arr.indexOf(result) + 1);\r\n}"}, {"source_code": "function solution() {\r\n var t = parseInt(readline());\r\n for (var i = 0; i < t; i++) {\r\n var n = parseInt(readline());\r\n var a = readline().split(\" \");\r\n var nonSpy = a[0] === a[1] ? a[0] : a[2];\r\n for (var j = 0; j < n; j++) {\r\n if (a[j] !== nonSpy) {\r\n print(j+1);\r\n }\r\n }\r\n }\r\n}\r\n\r\nsolution();"}, {"source_code": "var t = readline();\r\n for(var i = 0 ; i < t ; i++){\r\n var n = readline(),\r\n a = readline().split(' ');\r\n valuesArray = [...new Set(a)],\r\n unexceptedValue = valuesArray[0] , counter = 0;\r\n for(var j = 0 ; j < n ; j++){\r\n if(parseInt(valuesArray[0]) == parseInt(a[j]) ){\r\n counter++;\r\n if(counter > 1){\r\n unexceptedValue = valuesArray[1];\r\n break;\r\n }\r\n }\r\n }\r\n print(parseInt(a.indexOf(unexceptedValue)) + 1);\r\n }"}, {"source_code": "var t = parseInt(readline());\r\n\r\nfor (var i = 0; i < t; i++) {\r\n var n = parseInt(readline());\r\n var arr = readline().split(' ');\r\n\r\n if (arr[0] !== arr[1]) {\r\n if (arr[2] === arr[0]) {\r\n print(2);\r\n } else {\r\n print(1);\r\n }\r\n } else {\r\n for (var j = 2; j < n; j++) {\r\n if (arr[j] !== arr[0]) {\r\n print(j + 1);\r\n break;\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "var numberOfTests =+(readline()),counter=0\r\nfor(var i=0;i+node)\r\n for(var j=0;j{\r\n return Math.min(a,b)\r\n })\r\n \r\n print(a.indexOf(min)+1)\r\n}"}, {"source_code": "function PrintArray(arr)\r\n{\r\n var str = ''\r\n for(var k=0;k +data);\r\n var hash = {};\r\n for (var i = 0; i < n; i++) {\r\n if (hash.hasOwnProperty(inp[i])) {\r\n hash[inp[i]]++;\r\n } else {\r\n hash[inp[i]] = 1;\r\n }\r\n }\r\n\r\n var ind = 0;\r\n for (var i in hash) {\r\n if (hash[i] === 1) {\r\n ind = i;\r\n }\r\n }\r\n return inp.indexOf(+ind) + 1;\r\n }\r\n\r\n while (t--) {\r\n print(solve());\r\n }"}, {"source_code": "var test = parseInt(readline());\r\nvar inte = 0;\r\n\r\nfor(var i = 0; i < test; i++) {\r\n var foo = parseInt(readline());\r\n var bar = readline();\r\n var barSplited = bar.split(\" \");\r\n for(var j = 0; j < barSplited.length; j++) {\r\n var counter = 0\r\n for(var k = 0; k < barSplited.length; k++) {\r\n if(barSplited[j] == barSplited[k] && j != k) {\r\n counter++\r\n }\r\n }\r\n if(counter == 0) {\r\n inte = j + 1;\r\n }\r\n }\r\n print(inte)\r\n}\r\n\r\n"}, {"source_code": "var tests = Number(readline());\r\n\r\n\r\nfor (var i = 0; i < tests; i++) {\r\n var len = Number(readline());\r\n var n = readline().split(\" \");\r\n var index = 0;\r\n var check = 0;\r\n var is_first = false;\r\n \r\n for (var j = 0; j < len; j++) {\r\n var temp = n[j];\r\n \r\n if (j == 0 && n[j] != n[j+1]) {\r\n if (n[j + 1] == n[j + 2])\r\n is_first = true; \r\n }\r\n \r\n if (temp != n[j + 1])\r\n check++;\r\n\r\n if (check == 2) {\r\n index = j;\r\n break;\r\n }\r\n \r\n \r\n }\r\n \r\n \r\n is_first ? print(1) : print(index + 1);\r\n}"}, {"source_code": "var t=Number(readline());\r\nfor (var i=0; i c[x] != -1)])\r\n \r\n}"}, {"source_code": " 'use strict';\r\n\r\n process.stdin.resume();\r\n process.stdin.setEncoding('utf-8');\r\n\r\n let inputString = '';\r\n let currentLine = 0;\r\n\r\n process.stdin.on('data', inputStdin => {\r\n \tinputString += inputStdin;\r\n });\r\n\r\n process.stdin.on('end', _ => {\r\n \tinputString = inputString.trim().split('\\n').map(string => {\r\n \t\treturn string.trim();\r\n \t});\r\n\r\n \tmain(); \r\n });\r\n\r\n function readline() {\r\n \treturn inputString[currentLine++];\r\n }\r\n\r\n function main() {\r\n\t\t///problem specific code start\r\nlet tc = readline();\r\nwhile(tc--)\r\n{\r\n\tlet arraySize = readline();\r\n\tconst array = readline().split(' ');\r\n const obj = {};\r\n for (let value of array)\r\n {\r\n \tif(value in obj)\r\n \t{\r\n obj[value]++;\r\n \t}\r\n \telse \r\n \t\tobj[value]=1;\r\n }\r\n for(let key in obj)\r\n {\r\n \tif(obj[key]==1)\r\n \t\tconsole.log(array.indexOf(key)+1);\r\n }\r\n\r\n\r\n \t\r\n\r\n} //problem specific code end\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"}, {"source_code": " 'use strict';\r\n\r\n process.stdin.resume();\r\n process.stdin.setEncoding('utf-8');\r\n\r\n let inputString = '';\r\n let currentLine = 0;\r\n\r\n process.stdin.on('data', inputStdin => {\r\n \tinputString += inputStdin;\r\n });\r\n\r\n process.stdin.on('end', _ => {\r\n \tinputString = inputString.trim().split('\\n').map(string => {\r\n \t\treturn string.trim();\r\n \t});\r\n\r\n \tmain(); \r\n });\r\n\r\n function readline() {\r\n \treturn inputString[currentLine++];\r\n }\r\n\r\n function main() {\r\n \t///problem specific code start\r\n /*\r\n \tvar tc=readline();\r\n \twhile(tc--)\r\n \t{\r\n \t\tlet size=readline();\r\n \t\tconst numbers=readline().split(' ');\r\n \t\tfor(let i=0;i {\r\n inputString += inputStdin;\r\n });\r\n \r\n process.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n });\r\n \r\n function readline() {\r\n return inputString[currentLine++];\r\n }\r\n \r\n function main() {\r\n \r\n var tc=readline();\r\nwhile(tc--)\r\n{\r\n\tlet size=readline();\r\n\tconst numbers=readline().split(' ');\r\n\tfor(let i=0;i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const useCases = readline();\r\n\r\n for (let i = 0; i < useCases; i++) {\r\n const arrayLength = readline();\r\n const arrayContent = readline().split(' ');\r\n const arrayContentSorted = arrayContent.slice().sort((a,b) => a - b);\r\n let unique = 0;\r\n\r\n if (arrayContentSorted[0] === arrayContentSorted[1]) {\r\n unique = arrayContentSorted[arrayLength - 1];\r\n } else {\r\n unique = arrayContentSorted[0];\r\n }\r\n\r\n const uniqueIndex = arrayContent.indexOf(unique);\r\n\r\n print(uniqueIndex + 1);\r\n }\r\n}\r\n\r\nfunction print(x) {\r\n // process.stdout.write(\"hello: \"); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n \nlet inputString = \"\";\nlet currentLine = 0;\n \nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n \n// ********** Code Start **********\n\nfunction main() {\n const t = parseInt(readline())\n const results = []\n const arrayInputs = []\n for(let i =0; i {\n if(arr[0] != arr[1]) {\n if(arr[1] == arr[2]) {\n results.push(1)\n }else {\n results.push(2)\n }\n }else {\n let cont = true\n i=2;\n while(cont && i {\n check(arrayInput)\n })\n\n results.forEach(result => console.log(result))\n}\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nconst getSpyIndex = (arrNum) => {\n // console.log(\"input string\", arrNum);\n\n if (arrNum[0] === arrNum[2] && arrNum[1] !== arrNum[2]) {\n return 1;\n }\n for (let i = 2; i < arrNum.length; i++) {\n if (arrNum[0] !== arrNum[i]) {\n if (arrNum[1] === arrNum[i]) {\n return 0;\n } else {\n return i;\n }\n }\n }\n};\n\nfunction main() {\n const numberOfTestCases = 1 * readline();\n // console.log(\"number of test cases\", numberOfTestCases);\n Array.from({ length: numberOfTestCases }).forEach(() => {\n const arrayLength = 1 * readline();\n const arrayString = readline();\n const arr = arrayString.split(\" \");\n const arrNum = arr.map((x) => +x);\n\n console.log(getSpyIndex(arrNum) + 1);\n });\n}\n"}, {"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nconst getSpyIndex = (arrNum) => {\n let index;\n // console.log(\"input string\", arrNum);\n\n arrNum.forEach((x, i) => {\n if (i > 1) {\n if (arrNum[0] !== x) {\n if (arrNum[1] === x) {\n index = 0;\n } else {\n index = i;\n }\n } else if (i === 2) {\n index = 1;\n }\n }\n });\n\n console.log(index + 1);\n};\n\nfunction main() {\n const numberOfTestCases = 1 * readline();\n // console.log(\"number of test cases\", numberOfTestCases);\n Array.from({ length: numberOfTestCases }).forEach(() => {\n const arrayLength = 1 * readline();\n const arrayString = readline();\n const arr = arrayString.split(\" \");\n const arrNum = arr.map((x) => x * 1);\n\n getSpyIndex(arrNum);\n });\n}\n// const arrString = \"3 3 3 3 10 3 3 3 3 3\";\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split('\\n')\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tests = parseInt(readline());\r\n while (tests--) {\r\n let len = parseInt(readline());\r\n let arr = readline().split(' ');\r\n let key = {};\r\n for (let i = 0; i < len; i++) {\r\n if (key[arr[i]]) key[arr[i]].push(i + 1);\r\n else key[arr[i]] = [i + 1];\r\n }\r\n PrintMin(Object.values(key));\r\n }\r\n}\r\n\r\nfunction PrintMin(arr) {\r\n if (arr[0].length === 1) console.log(...arr[0]);\r\n else console.log(...arr[1]);\r\n}\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0];\n var answer = 0;\n for(var j = 1; j <= n * 2; j += 2){\n var num = lines[j + 1].split(' ');\n for(var k = 0; k < num.length; k++){\n var left = k - 1;\n var right = k + 1;\n if(left == -1){\n left = num.length -1;\n } \n if(right == num.length){ \n right = 0;\n }\n if(num[k] != num[left] && num[k] != num[right]){\n console.log(k + 1);\n }\n }\n \n }\n});"}, {"source_code": "let input = '';\r\nprocess.stdin.on('data', (c) => {\r\n input += c;\r\n});\r\n \r\nprocess.stdin.on('end', () => {\r\n const lines = input.split('\\n');\r\n const cases = parseInt(lines[0]);\r\n \r\n let on = true;\r\n for (let i = 1; i < cases * 3; i++) {\r\n const line = lines[i];\r\n // console.log(line);\r\n if (!line) {\r\n return;\r\n }\r\n if (on) {\r\n } else {\r\n const arr = lines[i].split(' ').map(t => t.trim());\r\n let t;\r\n //console.log(arr);\r\n const index = arr.findIndex((item, index) => {\r\n //console.log('t' + t + item);\r\n if (index === 0 && arr[index + 1] !== item && arr[index + 2] !== item) {\r\n return true;\r\n }\r\n if (t === undefined) {\r\n t = item;\r\n return false;\r\n }\r\n \r\n if (item !== t) {\r\n return true;\r\n }\r\n });\r\n \r\n \r\n console.log((index + 1));\r\n }\r\n \r\n on = !on;\r\n }\r\n});"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var a=readline();\r\nwhile(a--){\r\n var t=readline();\r\n var s=readline().split(\" \");\r\n \r\n var c=[];\r\n var ex;\r\n\r\n for(let i=0;i data != ex);\r\n console.log(s.indexOf(ans[0])+1)\r\n}\r\n}\r\n"}, {"source_code": "// Common Template Starts //\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\"\r\nlet currentLine = 0\r\n\r\nprocess.stdin.on(\"data\", inputStdin => inputString += inputStdin)\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => string.trim())\r\n main()\r\n})\r\n\r\nconst readline = () => inputString[currentLine++]\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n let t = parseInt(readline())\r\n while (t--) {\r\n let n = parseInt(readline())\r\n let arr = readline().split(' ').map( Number )\r\n console.log( solve(arr) )\r\n }\r\n}\r\n// Driver Function Ends //\r\n\r\n// MAIN LOGIC\r\nconst solve = (arr) => { \r\n let min = minOfArray( arr ) \r\n let max = maxOfArray( arr ) \r\n let minArr = arr.filter( a => a === min )\r\n\r\n spy = ( minArr.length === 1 ) ? min : max\r\n\r\n for( a in arr ) {\r\n if( arr[a] === spy ) return parseInt( a ) + 1\r\n }\r\n}\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var n = lines[0];\n var e = 0;\n for(i = 1; i <= n * 2; i++){\n if(i % 2 == 1){\n e = lines[i];\n }else{\n var k = lines[i].split(' ').map(Number);\n for(j = 0; j < e; j++){\n var l = j - 1;\n var r = j + 1;\n l = l == -1 ? k.length - 1 : l;\n r = r == k.length ? 0 : r;\n if(k[l] != k[j] && k[j] != k[r]){\n console.log(j + 1);\n break;\n }\n }\n }\n }\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0];\n var answer = 0;\n for(var j = 1; j <= n * 2; j += 2){\n var num = lines[j + 1].split(' ');\n for(var k = 0; k < num.length; k++){\n var left = k - 1;\n var right = k + 1;\n if(left == -1){\n left = num.length -1;\n } \n if(right == num.length){ \n right = 0;\n }\n if(num[k] != num[left] && num[k] != num[right]){\n console.log(k + 1);\n }\n }\n \n }\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\nlet max = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let = i = 0;\n\n let x = readline();\n max = x;\n\n for (let i = 0; i < max * 2; i++) {\n let y = readline();\n if (i % 2 === 1) {\n execute(y.split(\" \"));\n }\n }\n}\n\nfunction execute(x) {\n // without auto '\\n' (newline)\n // process.stdout.write(\"\");\n // with auto '\\n' (newline)\n // console.log(x);\n\n let data = {};\n let spy = null;\n\n if (x.length !== 1) {\n for (let i = 0; i < x.length; i++) {\n if (!data.hasOwnProperty(x[i])) {\n data[`${x[i]}`] = 1;\n } else {\n data[`${x[i]}`] += 1;\n }\n }\n\n for (const el in data) {\n if (data[el] === 1) {\n spy = el;\n }\n }\n\n for (let i = 0; i < x.length; i++) {\n if (x[i] === spy) {\n console.log(i + 1);\n }\n }\n }\n}\n"}, {"source_code": "function processInput(input) {\r\n let opt = {};\r\n let [first, ...second] = [...input.split(\"\\n\")];\r\n opt.n = parseInt(first);\r\n for(var i = 0; i < second.length; i++) {\r\n second[i] = second[i].split(\" \").map(val => parseInt(val));\r\n }\r\n opt.testcases = second;\r\n // console.log(opt);\r\n return opt;\r\n }\r\n \r\n function iterateTC(TC) {\r\n var size = TC.n, arr = TC.testcases, k;\r\n for(var i = 1; i {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2) {\n c++;\n return;\n }\n\n const arr = d.split(\" \").map(Number);\n let guess = arr[0];\n\n if (guess === arr[1]) {\n let inc = 1;\n while (guess === arr[inc]) {\n inc++;\n }\n\n console.log(inc + 1);\n } else {\n if (guess === arr[2]) {\n console.log(2);\n } else {\n console.log(1);\n }\n }\n\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "const readline = require('readline').createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nlet input = [];\r\nlet ans = [];\r\n\r\nreadline.on('line', line => {\r\n input.push(line);\r\n}).on('close', () => {\r\n for (let i = 2; i < input.length; i+=2) {\r\n let nums = input[i].split(' ');\r\n for (let j = 0; j < nums.length; j++) {\r\n if (nums.indexOf(nums[j]) === nums.lastIndexOf(nums[j])) {\r\n ans.push(j+1);\r\n break;\r\n }\r\n }\r\n }\r\n console.log(ans.join('\\n'))\r\n});"}, {"source_code": "let i = ''\r\nprocess.stdin.on('data', c => i += c)\r\nprocess.stdin.on('end', () => {\r\n const {EOL} = require('os')\r\n \r\n const lines = i.split(EOL)\r\n const NoL = lines[0]*2\r\n \r\n let LoA = false\r\n let crewmate = 0\r\n \r\n let n = 1\r\n while(NoL >= n){\r\n if(!LoA){\r\n LoA = lines[n]\r\n \r\n }else{\r\n let number = lines[n].split(\" \")\r\n \r\n if(number[0] == number[1]){\r\n crewmate = number[0]\r\n \r\n }else if(number[0] == number[2]){\r\n crewmate = number[0]\r\n }else{\r\n crewmate = number[1]\r\n }\r\n \r\n \r\n let a = 0\r\n while(LoA > a){\r\n if(number[a] != crewmate){\r\n console.log(number.indexOf(number[a])+1)\r\n break;\r\n }\r\n a++\r\n }\r\n \r\n LoA = false\r\n }\r\n n++ \r\n }\r\n})\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nfunction solve() {\r\n let n = nextInt();\r\n const cnt = af(101).fill(0);\r\n const a = af(n);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = nextInt();\r\n cnt[a[i]]++;\r\n }\r\n for (let i = 1; i <= 100; i++) {\r\n if (cnt[i] == 1) {\r\n for (let j = 0; j < n; j++) {\r\n if (a[j] == i) {\r\n return j + 1;\r\n }\r\n }\r\n }\r\n }\r\n return INIT;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n printf(\"%d\\n\", solve());\r\n }\r\n}\r\n"}, {"source_code": "\"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nconst getSpyIndex = (arrNum) => {\r\n let index;\r\n // console.log(\"input string\", arrNum);\r\n\r\n arrNum.forEach((x, i) => {\r\n if (i > 1) {\r\n if (arrNum[0] !== x) {\r\n if (arrNum[1] === x) {\r\n index = 0;\r\n } else {\r\n index = i;\r\n }\r\n } else if (i === 2) {\r\n index = 1;\r\n }\r\n }\r\n });\r\n\r\n console.log(index + 1);\r\n};\r\n\r\nfunction main() {\r\n const numberOfTestCases = 1 * readline();\r\n // console.log(\"number of test cases\", numberOfTestCases);\r\n Array.from({ length: numberOfTestCases }).forEach(() => {\r\n const arrayLength = 1 * readline();\r\n const arrayString = readline();\r\n const arr = arrayString.split(\" \");\r\n const arrNum = arr.map((x) => x * 1);\r\n\r\n getSpyIndex(arrNum);\r\n });\r\n}\r\n"}, {"source_code": "/**\r\n * Bismillahir Rahmanir Rahim\r\n * This code has been taken from: https://codeforces.com/blog/entry/69610\r\n */\r\n process.stdin.resume();\r\n process.stdin.setEncoding('utf-8');\r\n \r\n let inputString = '';\r\n let currentLine = 0;\r\n \r\n process.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n });\r\n \r\n process.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n });\r\n \r\n function readLine() {\r\n return inputString[currentLine++];\r\n }\r\n \r\n \r\n /****** BELOW HERE START WRITING YOUR CODE IN main() FUNCTION ***************************************/\r\n /**\r\n * Use \"readLine()\" function for input, which will return a string consisting the entire line, so accordingly split the string \r\n * when required.\r\n *\r\n * I am using console.log() to output\r\n */\r\n// function main() {\r\n// let t = readLine();\r\n// t = parseInt(t);\r\n// console.log(\"mai yahan aaya\")\r\n// while(t--) {\r\n// let line = readLine();\r\n// line = line.split(\" \");\r\n// let n = parseInt(line[0]);\r\n// let m = parseInt(line[1]);\r\n// if(n === 1) {\r\n// console.log(\"0\");\r\n// } else if (n === 2) {\r\n// console.log(m);\r\n// } else {\r\n// console.log(2*m);\r\n// }\r\n// }\r\n// }\r\n\r\nfunction main() {\r\n\t\r\n\tlet t = parseInt(readLine());\r\n\t// t = parseInt(t);\r\n\twhile(t--) {\r\n\t\tlet n = readLine();\r\n\t\tn = parseInt(n);\r\n\t\tlet s = readLine().split(\" \").map(item=>parseInt(item));\r\n\t\tconsole.log(solve(n,s)+1);\r\n\t\t\r\n\t}\r\n // console.log(t);\r\n}\r\n\r\nfunction solve(n, s) {\r\n\tfor (let i = 0; i < n-2; i++) {\r\n\t\tif (s[i] == s[i+1] && s[i] == s[i+2]) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (s[i] == s[i+1]) return i+2;\r\n\t\tif (s[i] == s[i+2]) return i+1;\r\n\t\tif (s[i+1] == s[i+2]) return i;\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\tlet t = nl.num();\n let ans = [];\n for(let i = 0; i < t; i++){\n\t\tnl.num();\n\t\tlet s = nl.nums();\n\t\tlet a = s[0];\n\t\tlet b = s[1];\n\t\tlet c = s[2];\n\t\tlet x = 0;\n\t\tif (a == b) {\n\t\t\tx = a;\n\t\t} else if (b == c) {\n\t\t\tx = b;\n\t\t} else {\n\t\t\tx = a;\n\t\t}\n\t\t\n\t\tlet y = 0;\n\t\ts.forEach((e, i) => {\n\t\t\tif (e != x) {\n\t\t\t\ty = i + 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t\tans.push(y);\n }\n \n\tconsole.log(ans.join(\"\\n\"));\n \n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "input()\r\n//-------------------\r\n\r\nfunction input () {\r\n let i = ''\r\n process.stdin.on('data', c => i += c)\r\n process.stdin.on('end', () => {\r\n const {EOL} = require('os')\r\n const lines = i.split(EOL) /*your input text, split by lines*/\r\n //console.log(lines);\r\n solve(lines)\r\n })\r\n\r\n}\r\n\r\nfunction solve (arr) {\r\n var d =+arr[0]\r\n for (var i =1 ;i <=d ;i++){\r\n var mas =arr[2*i].split(\" \")\r\n var mno =new Set(mas)\r\n \r\n for (var e of mno){\r\n var k =mas.indexOf(e)\r\n var kk =mas.lastIndexOf(e)\r\n if (k == kk){\r\n console.log(k+1)\r\n break\r\n \r\n }\r\n }\r\n \r\n }\r\n \r\n \r\n\r\n\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", inputStdin => {\r\n\tinputString += inputStdin;\r\n});\r\n\r\n\r\nprocess.stdin.on(\"end\", a => {\r\n\tinputString = inputString.trim().split(\"\\n\").map(str => str.trim());\r\n\tmain();\r\n});\r\n\r\nfunction readLine() {\r\n\treturn inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n\tlet t = parseInt(readLine().split(\" \")[0]);\r\n\t\r\n\twhile(t-->0) {\t\r\n\t\tlet n = parseInt(readLine().split(\" \")[0]);\r\n\t\t\r\n\t\tlet arr = new Array(n);\r\n\t\tlet num = readLine().split(\" \");\r\n\t\tfor(let i=0;i {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let t = readline();\n while(t--)\n {\n let num_of_elements = readline(); \n let elements = readline();\n elements = elements.split(' ')\n let prev_occ = elements[0];\n for(let i=1;i {\r\ndata += chunk;\r\n});\r\n\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n \r\n let testCases = parseInt(readLine());\r\n while(testCases--)\r\n {\r\n let n = parseInt(readLine());\r\n let arr = get_ints();\r\n let my_map = new Map();\r\n for(let i = 0 ; i < n ; i++)\r\n my_map.get(arr[i]) ? my_map.set(arr[i], my_map.get(arr[i]) + 1) : my_map.set(arr[i], 1)\r\n let ans;\r\n for([key,value] of my_map){\r\n if(value === 1) ans = key;\r\n }\r\n for(let i = 0; i < n; i++){\r\n if(arr[i] === ans){\r\n console.log(i + 1);\r\n break;\r\n }\r\n }\r\n }\r\n});\r\n\r\nfunction get_ints() { \r\n return readLine().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction print(c){\r\n return console.log(c)\r\n}\r\n\r\nfunction isEqual(arr){\r\n let flag = true;\r\n for(let i = 0 ; i < arr.length - 1; i++){\r\n if(arr[i] !== arr[i + 1]){\r\n flag = false;\r\n break;\r\n }\r\n }\r\n return flag;\r\n}\r\n"}, {"source_code": "// https://codeforces.com/problemset/problem/1512/A\n\nprocess.stdin.setEncoding('utf-8')\nconst readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n }\n)\n\nlet count = -1\nlet inputArr = []\n\nrl.on('line', data => {\n if (count === -1) {\n count = +data * 2\n } else if (count !== 0) {\n inputArr.push(data.trim())\n count--;\n }\n\n if (count === 0) {\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\n\n for (let i = 0; i < inputArr.length; i += 2) {\n solution(inputArr[i], inputArr[i + 1])\n }\n\n process.exit(0)\n }\n})\n\n/**\nTEST CASES\n4\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\n */\nconst solution = (n, arr) => {\n const key0 = arr[0];\n const key1 = arr[1];\n const key2 = arr[2];\n\n if (key0 === key1 && key0 !== key2) {\n console.log(3);\n return;\n } else if (key0 === key2 && key0 !== key1) {\n console.log(2);\n return;\n } else if (key1 === key2 && key0 !== key1) {\n console.log(1);\n return;\n }\n\n let result = 1;\n\n for (let i=1; i {\r\n return parseInt(__lineDB[__lineIdx++], 10);\r\n },\r\n readLine: () => {\r\n return __lineDB[__lineIdx++];\r\n }\r\n};\r\nlet __lineDB = [];\r\nlet __lineIdx = 0;\r\nconst isDebug = process.argv[2] === 'readizDebug';\r\nif (!isDebug) {\r\n global.console = {\r\n log: () => {},\r\n warn: () => {},\r\n info: () => {},\r\n debug: () => {},\r\n error: () => {}\r\n };\r\n const rl = require('readline').createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n rl.on('line', (line) => {\r\n __lineDB.push(line);\r\n });\r\n rl.on('close', () => {\r\n process.stdout.write(solution(scanner) + '\\n');\r\n });\r\n} else {\r\n __lineDB = require('fs').readFileSync(process.argv[1].replace('.js', '_input.txt')).toString().split('\\n');\r\n while (__lineIdx < __lineDB.length) {\r\n process.stdout.write('--------------------------------------------\\n');\r\n process.stdout.write('New Start + Log\\n');\r\n process.stdout.write('--------------------------------------------\\n');\r\n const start = __lineIdx;\r\n const answer = solution(scanner);\r\n const end = __lineIdx;\r\n process.stdout.write('----------------------\\n');\r\n process.stdout.write('Input\\n')\r\n process.stdout.write('----------------------\\n');\r\n process.stdout.write(__lineDB.slice(start, end).join('\\n') + '\\n');\r\n process.stdout.write('----------------------\\n');\r\n process.stdout.write('Answer\\n')\r\n process.stdout.write('----------------------\\n');\r\n process.stdout.write(answer + '\\n');\r\n }\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextStrArray(N);\r\n\t\tvar map = {};\r\n\t\tfor(var j = 0; j < N; j++){\r\n\t\t\tif(map[list[j]] == null){\r\n\t\t\t\tmap[list[j]] = 0;\r\n\t\t\t}\r\n\t\t\tmap[list[j]]++;\r\n\t\t}\r\n\t\tvar key = Object.keys(map);\r\n\t\tvar min;\r\n\t\tmyerr(map);\r\n\t\tif(map[key[0]] < map[key[1]]){\r\n\t\t\tmin = key[0];\r\n\t\t}else{\r\n\t\t\tmin = key[1];\r\n\t\t}\r\n\t\tmyerr(min);\r\n\t\tmyout(list.indexOf(min) + 1);\r\n\t}\r\n}"}, {"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n, a) => {\r\n let m = new Map();\r\n for (const e of a) m.set(e, m.get(e) + 1 || 1);\r\n for (let i = 0; i < n; i++) {\r\n if (m.get(a[i]) == 1) return pr(i + 1);\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i][0], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve(n, arr) {\r\n const res = arr.filter((el, i, arr) => arr.indexOf(el) === arr.lastIndexOf(el))\r\n console.log(arr.indexOf(res[0]) + 1)\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nvar maxN = 21\r\nvar mod = 1000000007\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n const xx = readline();\r\n\r\n Array(Number(xx)).fill(1).map((t, i) => {\r\n const n = parseInt(readline());\r\n // var [n, p, k] = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var min = 0\r\n var object = {}\r\n for (let j = 0; j < n; j++) {\r\n if (!object[a[j]]) object[a[j]] = 0\r\n object[a[j]]++\r\n }\r\n for (let j = 0; j < n; j++) {\r\n if (object[a[j]] === 1) return console.log(j + 1)\r\n }\r\n\r\n })\r\n}\r\n"}], "negative_code": [{"source_code": "var integer = readline();\r\nvar array = readline().split(\" \");\r\nvar i;\r\nvar k;\r\nvar counter=0;\r\nvar item;\r\nfor(i=0; i b?'0':'1'\r\n if(str[current] == '?')\r\n {\r\n if(str[inversed]!='?')\r\n {\r\n str[current] = str[inversed];\r\n if(str[inversed] == '0')\r\n {\r\n a = parseInt(a) - 1 \r\n }\r\n else\r\n {\r\n b = parseInt(b) - 1\r\n }\r\n }\r\n else\r\n {\r\n str[current] = next;\r\n str[inversed] = next;\r\n if(a>b)\r\n {\r\n a = parseInt(a) - 2 \r\n }\r\n else\r\n {\r\n b = parseInt(b) - 2\r\n }\r\n }\r\n }\r\n else if(str[current] == '0')\r\n {\r\n if(str[inversed] == '1')\r\n {\r\n return \"-1\";\r\n }\r\n else if(str[inversed] == '?')\r\n {\r\n str[inversed] = '0';\r\n a = parseInt(a) - 1; \r\n }\r\n }\r\n else if(str[current] == '1')\r\n {\r\n if(str[inversed] == '0')\r\n {\r\n return \"-1\";\r\n }\r\n else if(str[inversed] == '?')\r\n {\r\n str[inversed] = '1';\r\n b = parseInt(b) - 1; \r\n }\r\n }\r\n if(a<0 || b<0)\r\n {\r\n return \"-1\";\r\n }\r\n }\r\n\r\n return str.join(\"\");\r\n}\r\n\r\nvar arr = []\r\nvar t = readline();\r\n\r\nfor(var indT=0;indT {\r\n inputString += inputStdin;\r\n });\r\n process.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n });\r\n function readline() {\r\n return inputString[currentLine++];\r\n }\r\n \r\n // ********** Code Start **********\r\n \r\n function main() {\r\n \t/*\r\n var a=readline();\r\n while(a--){\r\n var t=readline();\r\n var s=readline().split(\" \");\r\n \r\n var c=[];\r\n var ex;\r\n \r\n for(let i=0;i data != ex);\r\n console.log(s.indexOf(ans[0])+1)\r\n }\r\n */\r\n var tc=readline();\r\nwhile(tc--)\r\n{\r\n\tlet size=readline();\r\n\tconst numbers=readline().split(' ');\r\n\tfor(let i=0;i {\r\n inputString += inputStdin;\r\n });\r\n process.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n });\r\n function readline() {\r\n return inputString[currentLine++];\r\n }\r\n \r\n // ********** Code Start **********\r\n \r\n function main() {\r\n \t/*\r\n var a=readline();\r\n while(a--){\r\n var t=readline();\r\n var s=readline().split(\" \");\r\n \r\n var c=[];\r\n var ex;\r\n \r\n for(let i=0;i data != ex);\r\n console.log(s.indexOf(ans[0])+1)\r\n }\r\n */\r\n var tc=readline();\r\nwhile(tc--)\r\n{\r\n\tlet size=readline();\r\n\tconst numbers=readline().split(' ');\r\n\tfor(let i=0;i {\r\n inputString += inputStdin;\r\n });\r\n process.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n });\r\n function readline() {\r\n return inputString[currentLine++];\r\n }\r\n \r\n // ********** Code Start **********\r\n \r\n function main() {\r\n \t/*\r\n var a=readline();\r\n while(a--){\r\n var t=readline();\r\n var s=readline().split(\" \");\r\n \r\n var c=[];\r\n var ex;\r\n \r\n for(let i=0;i data != ex);\r\n console.log(s.indexOf(ans[0])+1)\r\n }\r\n */\r\n var tc=readline();\r\nwhile(tc--)\r\n{\r\n\tlet size=readline();\r\n\tconst numbers=readline().split(' ');\r\n\tfor(let i=0;i {\r\n inputString += inputStdin;\r\n });\r\n process.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n });\r\n function readline() {\r\n return inputString[currentLine++];\r\n }\r\n \r\n // ********** Code Start **********\r\n \r\n function main() {\r\n \t/*\r\n var a=readline();\r\n while(a--){\r\n var t=readline();\r\n var s=readline().split(\" \");\r\n \r\n var c=[];\r\n var ex;\r\n \r\n for(let i=0;i data != ex);\r\n console.log(s.indexOf(ans[0])+1)\r\n }\r\n */\r\n var tc=readline();\r\nwhile(tc--)\r\n{\r\n\tlet size=readline();\r\n\tconst numbers=readline().split(' ');\r\n\tfor(let i=0;i a - b);\r\n let unique = 0;\r\n\r\n if (arrayContentSorted[0] === arrayContentSorted[1]) {\r\n unique = arrayContentSorted[arrayLength - 1];\r\n } else {\r\n unique = arrayContentSorted[0];\r\n }\r\n\r\n const uniqueIndex = arrayContent.indexOf(unique);\r\n\r\n print(uniqueIndex + 1);\r\n }\r\n}"}, {"source_code": "function main() {\r\n const useCases = readline();\r\n\r\n for (let i = 0; i < useCases; i++) {\r\n const arrayLength = readline();\r\n let unique = 0\r\n const arrayContent = readline().split(' ')\r\n const arrayContentSorted = arrayContent.slice().sort((a,b) => a - b);\r\n if (arrayContentSorted[0] === arrayContentSorted[1]) {\r\n unique = arrayContentSorted[arrayLength - 1]\r\n } else {\r\n unique = arrayContentSorted[0]\r\n }\r\n const uniqueIndex = arrayContent.indexOf(unique)\r\n console.log(uniqueIndex + 1)\r\n }\r\n}"}, {"source_code": "function main() {\r\n const useCases = readline();\r\n\r\n for (let i = 0; i < useCases; i++) {\r\n const arrayLength = readline();\r\n let unique = 0\r\n const arrayContent = readline().split(' ')\r\n const arrayContentSorted = arrayContent.slice().sort((a,b) => a - b);\r\n if (arrayContentSorted[0] === arrayContentSorted[1]) {\r\n unique = arrayContentSorted[arrayLength - 1]\r\n } else {\r\n unique = arrayContentSorted[0]\r\n }\r\n const uniqueIndex = arrayContent.indexOf(unique)\r\n print(uniqueIndex + 1)\r\n }\r\n}"}, {"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nconst getSpyIndex = (arrNum) => {\n let index;\n // console.log(\"input string\", arrNum);\n\n for (let i = 2; i < arrNum.length; i++) {\n if (arrNum[0] !== arrNum[i]) {\n if (arrNum[1] === arrNum[i]) {\n index = 0;\n } else {\n index = i;\n }\n break;\n } else if (i === 2) {\n index = 1;\n break;\n }\n }\n\n console.log(index + 1);\n};\n\nfunction main() {\n const numberOfTestCases = 1 * readline();\n // console.log(\"number of test cases\", numberOfTestCases);\n Array.from({ length: numberOfTestCases }).forEach(() => {\n const arrayLength = 1 * readline();\n const arrayString = readline();\n const arr = arrayString.split(\" \");\n const arrNum = arr.map((x) => +x);\n\n getSpyIndex(arrNum);\n });\n}\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split('\\n')\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tests = parseInt(readline());\r\n while (tests--) {\r\n let len = parseInt(readline());\r\n let arr = readline().split(' ').map(Number);\r\n let left = 0;\r\n let right = len - 1;\r\n for (let i = 0; i < len; i++) {\r\n if (arr[left] === arr[right]) {\r\n left++;\r\n right--;\r\n } else {\r\n if (arr[left] === arr[left + 1]) {\r\n console.log(right + 1);\r\n break;\r\n }\r\n console.log(left + 1);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split('\\n')\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tests = parseInt(readline());\r\n while (tests--) {\r\n let len = parseInt(readline());\r\n let arr = readline().split(' ').map(Number);\r\n let left = 0;\r\n let right = len - 1;\r\n for (let i = 0; i < len; i++) {\r\n if (arr[left] === arr[right]) {\r\n left++;\r\n right--;\r\n } else {\r\n if (arr[left + 1] !== arr[right]) {\r\n console.log(right + 1);\r\n break;\r\n }\r\n console.log(left + 1);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var number = lines[0].split(' ');\n var boyGirl = lines[1].split('');\n var answer = '';\n while(number[1]--){\n for(j = 1; j < number[0]; j++){\n if(boyGirl[j] == 'G' && boyGirl[j - 1] == 'B'){\n boyGirl[j] = 'B';\n boyGirl[j - 1] = 'G';\n j++;\n }\n }\n }\n answer = boyGirl.toString();\n answer.split(',');\n var a = '';\n for(k = 0; k < Number(number[0]) * 2 - 1;k++){\n if(k % 2 === 0){\n a += answer[k];\n }\n }\n console.log(a);\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n for(var j = 1; j <= lines[0] * 2; j += 2){\n var a = lines[j].split(' ');\n for(var k = 0; k <= a.length; k++){\n var l = k - 1;\n var r = k + 1;\n if(l == -1){\n l = a.length;\n } \n if(r == a.length){ \n r = 0;\n }\n if(a[k] != a[l] && a[k] != a[r]){\n console.log(k + 1);\n }\n }\n \n }\n});"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var a=readline();\r\nwhile(a--){\r\n var t=readline();\r\n var s=readline().split(\" \");\r\n \r\n var c=[];\r\n var ex;\r\n\r\n for(let i=0;i data != ex);\r\n console.log(s.indexOf(ans[0]))\r\n}\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var a=readline();\r\nwhile(a--){\r\n var t=readline();\r\n var s=readline().split(\" \");\r\n var c=[];\r\n var ex;\r\n\r\n for(let i=0;i data != ex);\r\n console.log(ans[0])\r\n}\r\n}\r\n"}, {"source_code": "// Common Template Starts //\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\"\r\nlet currentLine = 0\r\n\r\nprocess.stdin.on(\"data\", inputStdin => inputString += inputStdin)\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => string.trim())\r\n main()\r\n})\r\n\r\nconst readline = () => inputString[currentLine++]\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n let t = parseInt(readline())\r\n while (t--) {\r\n let n = parseInt(readline())\r\n let arr = readline().split(' ').map( Number )\r\n console.log( solve(arr) )\r\n }\r\n}\r\n// Driver Function Ends //\r\n\r\n// MAIN LOGIC\r\nconst solve = (arr) => { \r\n let freq = new Array( 100 ).fill( 0 )\r\n \r\n for( let a of arr ) {\r\n freq[a]++\r\n }\r\n\r\n return ( arr.indexOf( freq.indexOf(1) ) + 1 )\r\n}\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\nlet maxLine = 8;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n for (let i = 0; i <= maxLine; i++) {\n let x = readline();\n execute(x.split(\" \"));\n }\n}\n\nfunction execute(x) {\n // without auto '\\n' (newline)\n // process.stdout.write(\"\");\n // with auto '\\n' (newline)\n // console.log(x);\n\n let data = {};\n let spy = null;\n\n if (x.length !== 1) {\n for (let i = 0; i < x.length; i++) {\n if (!data.hasOwnProperty(x[i])) {\n data[`${x[i]}`] = 1;\n } else {\n data[`${x[i]}`] += 1;\n }\n }\n\n for (const el in data) {\n if (data[el] === 1) {\n spy = el;\n }\n }\n\n for (let i = 0; i < x.length; i++) {\n if (x[i] === spy) {\n console.log(i + 1);\n }\n }\n }\n}\n"}, {"source_code": "function solve(arr, N) {\r\n const a = arr[0];\r\n const b = arr[1];\r\n const c = arr[2];\r\n if (a == b && b == c) {\r\n for (let i = 4; i < N; i++) {\r\n if (arr[i] != a) {\r\n return i + 1;\r\n }\r\n }\r\n } else if (a == b && b != c) {\r\n return 3;\r\n } else if (b == c && a != b) {\r\n return 1;\r\n } else {\r\n return 2;\r\n }\r\n}\r\n\r\nfunction processData(input) {\r\n //Enter your code here\r\n input = input.split('\\n');\r\n const T = Number(input[0].trim());\r\n let i = 1;\r\n for (let t = 0; t < T; t++) {\r\n const N = Number(input[i++].trim());\r\n const arr = input[i++].trim().split(' ').map(Number);\r\n const ans = solve(arr, N);\r\n console.log(ans);\r\n }\r\n}\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n_input = \"\";\r\nprocess.stdin.on(\"data\", function (input) {\r\n _input += input;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n processData(_input);\r\n});\r\n"}], "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 + 7).", "input_spec": "Input contains several test cases. The first line contains two integers t and k (1 ≤ t, k ≤ 105), where t represents the number of test cases. The next t lines contain two integers ai and bi (1 ≤ ai ≤ bi ≤ 105), 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 + 7).", "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": "var input = readline().split(' ').map(Number), t = input[0], k = input[1];\nvar res = [];\nvar sum = [];\nres[0] = 1;\nfor (var i = 1; i <= 100000; i++) {\n res[i] = (i - k >= 0) ? ((res[i-1] + res[i-k]) % 1000000007) : res[i-1];\n}\nvar currentSum = 0;\nsum[0] = 0;\nfor (var i = 1; i <= 100000; i++) {\n currentSum = (currentSum + res[i]) % 1000000007;\n sum[i] = currentSum;\n}\nvar ans = '';\nfor (var i = 0; i < t; i++) {\n input = readline().split(' ').map(Number), a = input[0], b = input[1];\n var diff = sum[b] - sum[a-1];\n if (diff < 0) diff += 1000000007;\n ans += (diff + '\\n');\n}\n\n\nwrite(ans);\n"}, {"source_code": "var xx = readline().split(' ');\nvar t = parseInt(xx[0]);\nvar k = parseInt(xx[1]);\nvar MOD = 1000000007;\nvar a = new Array();\nvar b = new Array();\nvar n = 100000;\nfor(var i=1;i= 0) ? ((res[i-1] + res[i-k]) % 1000000007) : res[i-1];\n}\nvar currentSum = 0;\nsum[0] = 0;\nfor (var i = 1; i < 100000; i++) {\n currentSum = (currentSum + res[i]) % 1000000007;\n sum[i] = currentSum;\n}\nvar ans = '';\nfor (var i = 0; i < t; i++) {\n input = readline().split(' ').map(Number), a = input[0], b = input[1];\n var diff = sum[b] - sum[a-1];\n ans += (diff + '\\n');\n}\n\nwrite(ans);\n"}, {"source_code": "var input = readline().split(' ').map(Number), t = input[0], k = input[1];\nvar res = [];\nvar sum = [];\nres[0] = 1;\nfor (var i = 1; i < 100000; i++) {\n res[i] = (i - k >= 0) ? ((res[i-1] + res[i-k]) % 1000000007) : res[i-1];\n}\nvar currentSum = 0;\nsum[0] = 0;\nfor (var i = 1; i < 100000; i++) {\n currentSum = (currentSum + res[i]) % 1000000007;\n sum[i] = currentSum;\n}\nvar ans = '';\nfor (var i = 0; i < t; i++) {\n input = readline().split(' ').map(Number), a = input[0], b = input[1];\n var diff = sum[b] - sum[a-1];\n if (diff < 0) diff += 1000000007;\n ans += (diff + '\\n');\n}\n\n\nwrite(ans);\n"}], "src_uid": "16c016c0735be1815c7b94c5c50516f1"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ elements, each element is either $$$0$$$ or $$$1$$$.You can make operations of $$$2$$$ kinds. Pick an index $$$i$$$ and change $$$a_i$$$ to $$$1-a_i$$$. Rearrange the array $$$a$$$ however you want. Find the minimum number of operations required to make $$$a$$$ equal to $$$b$$$.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 400$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$) — the length of the arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ space-separated integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), representing the array $$$a$$$. The third line of each test case contains $$$n$$$ space-separated integers $$$b_1,b_2,\\ldots,b_n$$$ ($$$b_i$$$ is $$$0$$$ or $$$1$$$), representing the array $$$b$$$.", "output_spec": "For each test case, print the minimum number of operations required to make $$$a$$$ equal to $$$b$$$.", "sample_inputs": ["5\n\n3\n\n1 0 1\n\n0 0 1\n\n4\n\n1 1 0 0\n\n0 1 1 1\n\n2\n\n1 1\n\n1 1\n\n4\n\n1 0 0 1\n\n0 1 1 0\n\n1\n\n0\n\n1"], "sample_outputs": ["1\n2\n0\n1\n1"], "notes": "NoteIn the first case, we need only one operation: change $$$a_1$$$ to $$$1-a_i$$$. Now $$$a = [0, 0]$$$ which is equal to $$$b$$$.In the second case, the optimal way is to rearrange $$$a$$$ to get the array $$$[0, 1, 11$$$. Now $$$a = [0, 0, 1]$$$ which is equal to $$$b$$$.In the second case, one of optimal ways would be to first change $$$a_3$$$ to $$$1 - a_3$$$, then rearrange $$$a$$$.In the third case, no operation is needed.In the fourth case, the optimal way is to rearrange $$$a$$$ to get the array $$$[0, 1, 1, 0]$$$."}, "positive_code": [{"source_code": "// Common Template Starts //\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\"\r\nlet currentLine = 0\r\n\r\nprocess.stdin.on(\"data\", inputStdin => inputString += inputStdin)\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => string.trim())\r\n main()\r\n})\r\n\r\nconst readline = () => inputString[currentLine++]\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n let t = parseInt(readline())\r\n while (t--) {\r\n let n = parseInt(readline())\r\n let a = readline() \r\n let b = readline() \r\n console.log( solve( n, a, b ) )\r\n }\r\n}\r\n// Driver Function Ends //\r\n\r\n// MAIN LOGIC\r\nconst solve = (n, a, b) => { \r\n if( a === b ) return 0\r\n if( n === 1 && a !== b ) return 1\r\n\r\n a = a.split(' ').map( Number )\r\n b = b.split(' ').map( Number )\r\n \r\n let ones_a = 0\r\n for(let i = 0; i < n; i++) {\r\n if( a[i] == 1 ) ones_a++\r\n }\r\n \r\n let ones_b = 0\r\n for(let i = 0; i < n; i++) {\r\n if( b[i] == 1 ) ones_b++\r\n }\r\n \r\n let diff = Math.abs(ones_a - ones_b)\r\n\r\n let res = 0\r\n for(let i = 0; i < n; i++) {\r\n if(a[i] != b[i]) res++\r\n }\r\n\r\n return Math.min( res, diff + 1 )\r\n}\r\n\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n b = rns(n);\r\n let x = a.reduce((a, b) => a + b, 0),\r\n y = b.reduce((a, b) => a + b, 0);\r\n let dif = x - y;\r\n let res = Math.abs(dif);\r\n for (let i = 0; i < n && dif; i++) {\r\n if (dif > 0) {\r\n if (a[i] !== b[i] && a[i]) {\r\n a[i] = 0;\r\n dif--;\r\n }\r\n } else if (dif < 0) {\r\n if (a[i] !== b[i] && !a[i]) {\r\n a[i] = 1;\r\n dif++;\r\n }\r\n }\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] !== b[i]) {\r\n res++;\r\n break;\r\n }\r\n }\r\n return res;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "5ccef7fbfd5e85d7fc7ef92f9ebc4088"} {"nl": {"description": "You talked to Polycarp and asked him a question. You know that when he wants to answer \"yes\", he repeats Yes many times in a row.Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.Determine if it is true that the given string $$$s$$$ is a substring of YesYesYes... (Yes repeated many times in a row).", "input_spec": "The first line of input data contains the singular $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases in the test. Each test case is described by a single string of Latin letters $$$s$$$ ($$$1 \\le |s| \\le 50$$$) — the part of Polycarp's answer that you heard, where $$$|s|$$$ — is the length of the string $$$s$$$.", "output_spec": "Output $$$t$$$ lines, each of which is the answer to the corresponding test case. As an answer, output \"YES\" if the specified string $$$s$$$ is a substring of the string YesYesYes...Yes (the number of words Yes is arbitrary), 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\n\nYES\n\nesYes\n\ncodeforces\n\nes\n\nse\n\nYesY\n\nesYesYesYesYesYesYe\n\nseY\n\nYess\n\nsY\n\no\n\nYes"], "sample_outputs": ["NO\nYES\nNO\nYES\nNO\nYES\nYES\nNO\nNO\nYES\nNO\nYES"], "notes": null}, "positive_code": [{"source_code": "\"use strict\";\r\nexports.__esModule = true;\r\nvar readline_1 = require(\"readline\");\r\nvar yesMap = {\r\n\tY: \"e\",\r\n\te: \"s\",\r\n\ts: \"Y\",\r\n};\r\nfunction isValidSubString(s) {\r\n\tif (s === \"Y\" || s === \"e\" || s === \"s\") {\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\nfunction findYesSubString(lines) {\r\n\tvar testCases = Number(lines[0]);\r\n\tvar mainString;\r\n\tvar isPartOfYes;\r\n\tfor (var i = 1; i <= testCases; i++) {\r\n\t\tisPartOfYes = false;\r\n\t\tmainString = lines[i];\r\n\t\tvar char = void 0;\r\n\t\t// mainString = mainString.replace(\"Yes\", \"\");\r\n\t\tfor (var j = 0; j < mainString.length; j++) {\r\n\t\t\tchar = mainString[j];\r\n\t\t\tif (mainString.length === 1 && isValidSubString(char)) {\r\n\t\t\t\tisPartOfYes = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (mainString.length === j + 1) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t// console.log(i, mainString, yesMap[char], mainString[j + 1], char);\r\n\t\t\tif (isValidSubString(char) && yesMap[char] === mainString[j + 1]) {\r\n\t\t\t\tisPartOfYes = true;\r\n\t\t\t} else {\r\n\t\t\t\tisPartOfYes = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (isPartOfYes) {\r\n\t\t\tconsole.log(\"YES\");\r\n\t\t} else {\r\n\t\t\tconsole.log(\"NO\");\r\n\t\t}\r\n\t}\r\n}\r\nvar rl = readline_1.createInterface(process.stdin, process.stdout);\r\nvar input = [];\r\nrl.on(\"line\", function (line) {\r\n\treturn input.push(line);\r\n}).on(\"close\", function () {\r\n\treturn findYesSubString(input);\r\n});\r\nvar a = \"s\";\r\n"}, {"source_code": " const fs = require(\"fs\");\r\n const input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\n let currentline = 0;\r\n function readline(){\r\n return input[currentline++];\r\n }\r\n function alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n }\r\n function Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n }\r\n function max(x,y) {\r\n return x >=y ? x : y;\r\n }\r\n function min(x,y) {\r\n return x <=y ? x : y;\r\n }\r\n function abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n }\r\n var T = readline();\r\n var inf = 1000000000000;\r\n for(var tc=1;tc<=T;tc++) {\r\n \tvar n = readline();\r\n \tvar N = n.length;\r\n \tvar ok = false;\r\n \tvar ref = [\"Y\",\"e\",\"s\"];\r\n \tvar r = ref.indexOf(n[0]);\r\n \tif(r!==-1) {\r\n \t\tvar j = 0;\r\n \t\twhile(j {\n\tinputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map((string) => {\n\t\t\treturn string.trim();\n\t\t});\n\n\tmain();\n});\n\nfunction readline() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = parseInt(readline());\n\n\tfor (let i = 0; i < t; i++) {\n\t\tlet s = readline();\n\t\tlet yes = ['Y', 'e', 's'];\n\t\tlet index = -1;\n\t\tlet i = 0;\n\n\t\t// s es substring de YesYesYes\n\n\t\tlet esSubstring = true;\n\n\t\tif (s[0] != 'Y' && s[0] != 'e' && s[0] != 's') {\n\t\t\tesSubstring = false;\n\t\t}\n\n\t\tif (s[0] == 'Y') {\n\t\t\tindex = 0;\n\t\t} else if (s[0] == 'e') {\n\t\t\tindex = 1;\n\t\t}\n\t\tif (s[0] == 's') {\n\t\t\tindex = 2;\n\t\t}\n\n\t\twhile (esSubstring && i < s.length) {\n\t\t\tif (s[i] != yes[index]) {\n\t\t\t\tesSubstring = false;\n\t\t\t}\n\t\t\tif (index == 2) {\n\t\t\t\tindex = 0;\n\t\t\t} else {\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\tif (esSubstring) {\n\t\t\tconsole.log('YES');\n\t\t} else {\n\t\t\tconsole.log('NO');\n\t\t}\n\t}\n}\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\nfunction main() {\r\n const testCases = Number(readline());\r\n const str = 'Yes'.repeat(50);\r\n for (let i = 0; i < testCases; i++) {\r\n let chunk = readline();\r\n if (findChunk(str, chunk)) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n}\r\n\r\nfunction findChunk(str, chunk) {\r\n return str.indexOf(chunk) > -1\r\n}"}, {"source_code": "const readline = require('readline');\r\nconst { stdin: input, stdout: output } = require('process')\r\nconst rl = readline.createInterface({ input, output })\r\n\r\nlet lines = []\r\n\r\nconst createReadLine = () => {\r\n i = 0;\r\n return () => lines[i++]\r\n}\r\nconst int = (num, radix=10) => parseInt(num, radix)\r\n\r\nrl.on('line', line => lines.push(line))\r\n\r\nrl.on(\"close\", () => {\r\n const readLine = createReadLine();\r\n let t = int(readLine());\r\n while (t--) {\r\n let str = readLine();\r\n let len = str.length\r\n let yes = 'Yes'.repeat(len)\r\n if (yes.includes(str)) {\r\n console.log('YES')\r\n } else {\r\n console.log('NO')\r\n }\r\n }\r\n});\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const str = lines[l++]\n output[i] = solve(str) ? 'YES' : 'NO'\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(str) {\n const n = str.length\n let a = Array(n)\n let b = Array(n)\n let c = Array(n)\n const s = 'Yes'\n for (let i = 0; i < n; i++) {\n a[i] = s[i % 3]\n b[i] = s[(i + 1) % 3]\n c[i] = s[(i + 2) % 3]\n }\n a = a.join('')\n b = b.join('')\n c = c.join('')\n // console.log(n, a, b, c)\n return a === str || b === str || c === str\n}\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n let s = read();\r\n if (s[0] !== 'Y' && s[0] !== 'e' && s[0] !== 's') return 'NO';\r\n let i = 0,\r\n j = 0;\r\n if (s[0] === 'e') j = 1;else if (s[0] === 's') j = 2;\r\n const s1 = 'Yes';\r\n while (i < s.length) {\r\n if (s[i] !== s1[j]) return 'NO';\r\n j = (j + 1) % 3;\r\n i++;\r\n }\r\n return 'YES';\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n let s = solve(r);\r\n if (s === undefined) s = '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar V = \"\";\r\n\tfor(var i = 0; i < 10000; i++){\r\n\t\tV += \"Yes\";\r\n\t}\r\n\twhile(hasNext()){\r\n\t\tvar s = next();\r\n\t\tif(V.indexOf(s) != -1){\r\n\t\t\tmyout(\"Yes\");\r\n\t\t}else{\r\n\t\t\tmyout(\"No\");\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "var input = readline();\r\n\r\nfor(var i=0; i -1;\n print(b ? \"Yes\" : \"NO\");\n}\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nexports.__esModule = true;\r\nvar readline_1 = require(\"readline\");\r\nvar yesMap = {\r\n\tY: \"e\",\r\n\te: \"s\",\r\n\ts: \"Y\",\r\n};\r\nfunction isValidSubString(s) {\r\n\tif (s === \"Y\" || s === \"e\" || s === \"s\") {\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\nfunction findYesSubString(lines) {\r\n\tvar testCases = Number(lines[0]);\r\n\tvar mainString;\r\n\tvar isPartOfYes;\r\n\tfor (var i = 1; i <= testCases; i++) {\r\n\t\tisPartOfYes = false;\r\n\t\tmainString = lines[i];\r\n\t\tvar char = void 0;\r\n\t\t// mainString = mainString.replace(\"Yes\", \"\");\r\n\t\tfor (var j = 0; j < mainString.length; j++) {\r\n\t\t\tchar = mainString[j];\r\n\t\t\tif (mainString.length === j + 1) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t// console.log(i, mainString, yesMap[char], mainString[j + 1], char);\r\n\t\t\tif (isValidSubString(char) && yesMap[char] === mainString[j + 1]) {\r\n\t\t\t\tisPartOfYes = true;\r\n\t\t\t} else {\r\n\t\t\t\tisPartOfYes = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (isPartOfYes) {\r\n\t\t\tconsole.log(\"YES\");\r\n\t\t} else {\r\n\t\t\tconsole.log(\"NO\");\r\n\t\t}\r\n\t}\r\n}\r\nvar rl = readline_1.createInterface(process.stdin, process.stdout);\r\nvar input = [];\r\nrl.on(\"line\", function (line) {\r\n\treturn input.push(line);\r\n}).on(\"close\", function () {\r\n\treturn findYesSubString(input);\r\n});\r\nvar a = \"s\";\r\n"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\nvar T = readline();\r\nvar inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n\tvar n = readline();\r\n\tvar N = n.length;\r\n\tvar ok = false;\r\n\tvar ref = [\"Y\",\"e\",\"s\"];\r\n\tvar r = ref.indexOf(n[0]);\r\n\tif(r!==-1) {\r\n\t\tvar j = 0;\r\n\t\twhile(j {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n let [max, sum] = [-Infinity, 0];\n readLine()\n .split(\" \")\n .forEach((n) => {\n n = parseInt(n);\n sum += n;\n max = Math.max(max, n);\n });\n\n const value = Math.ceil(sum / (len - 1));\n if (max > value) {\n let output = Math.abs((len - 1) * max - sum);\n console.log(output);\n } else {\n let output = Math.abs(sum - (len - 1) * value);\n console.log(output);\n }\n }\n}\n"}, {"source_code": "/*\nYou are asked to watch your nephew who likes to play with toy blocks in a strange way.\n\nHe has n boxes and the i-th box has ai blocks. His game consists of two steps:\n\nhe chooses an arbitrary box i;\nhe tries to move all blocks from the i-th box to other boxes.\nIf he can make the same number of blocks in each of n−1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.\nYou don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put?\n\nInput\nThe first line contains a single integer t (1≤t≤1000) — the number of test cases.\n\nThe first line of each test case contains the integer n (2≤n≤105) — the number of boxes.\n\nThe second line of each test case contains n integers a1,a2,…,an (0≤ai≤109) — the number of blocks in each box.\n\nIt's guaranteed that the sum of n over test cases doesn't exceed 105.\n\ninputCopy\n3\n3\n3 2 2 -> 3. 1 -> 2 || 2 (2,3,2) || (2,2,3) 2. 1->\n4\n2 2 3 2\n3\n0 3 0\noutputCopy\n1\n0\n3\n\nIn the first test case, you can, for example, put one extra block into the first box and make a=[4,2,2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box (0,4,4). If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. (4,0,4) || (4,4,0)\n\nIn the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal.\n\nIn the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a=[2,3,1].\n*/\n\n'use-strict'\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet data = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', chunk => {\ndata += chunk;\n});\n\nprocess.stdin.on('end', () =>{\n data = data.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n let testCases = parseInt(data.shift());\n\n while(testCases--) {\n\n const n = parseInt(data.shift());\n\n const arr = get_ints();\n\n const res = b(n,arr);\n\n console.log(res)\n }\n});\n\nfunction get_ints() { \n return data.shift().split(' ').map(Number);\n}\n \nfunction readLine() { \n return data[currentLine++];\n}\n \nfunction b(n, arr)\n{\n arr.sort((a,b) => b - a);\n\n const max = arr[0];\n\n const sum = arr.reduce((a, b) => a + b);\n\n const k = Math.max(Math.ceil(sum/(n - 1)), max)\n\n return (n - 1) * k - sum;\n}\n\nmodule.exports = b;"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n B();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [x,y] = ti(readline().split(' '));\n \n let min = Math.min(x,y);\n let max = Math.max(x,y);\n if(max === min){\n console.log(max+min);\n }else{\n console.log(2*min+(1+(max-min-1)*2));\n }\n }\n}\n\nfunction B(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let a = ti(readline().split(' '));\n a.sort((a,b) => a-b);\n\n let sum = 0;\n for(let i = 0; i < a.length; i++)\n sum += a[i];\n\n let x = sum-a[0];\n let d = a[n-1]*(n-1)-x;\n\n if(a[0] > d){\n let diff = a[0]-d;\n console.log(diff % (n-1) === 0 ? 0 : ((n-1) - (diff % (n-1))));\n }else{\n console.log(d-a[0]);\n }\n }\n}"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n B();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [x,y] = ti(readline().split(' '));\n \n let min = Math.min(x,y);\n let max = Math.max(x,y);\n if(max === min){\n console.log(max+min);\n }else{\n console.log(2*min+(1+(max-min-1)*2));\n }\n }\n}\n\nfunction B(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let a = ti(readline().split(' '));\n a.sort((a,b) => a-b);\n\n let sum = 0;\n for(let i = 0; i < a.length; i++)\n sum += a[i];\n\n let x = sum-a[0];\n let d = a[n-1]*(n-1)-x;\n\n if(a[0] > d){\n let diff = a[0]-d;\n console.log(diff % (n-1));\n }else{\n console.log(d-a[0]);\n }\n }\n}"}], "src_uid": "e75b88ce4341062c20b6014da1152d29"} {"nl": {"description": "A permutation of length $$$n$$$ 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).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \\le i \\le j \\le n$$$) — $$$(p_i \\text{ OR } p_{i+1} \\text{ OR } \\ldots \\text{ OR } p_{j-1} \\text{ OR } p_{j}) \\ge j-i+1$$$, where $$$\\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.", "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 good permutation of length $$$n$$$ on a separate line. ", "sample_inputs": ["3\n1\n3\n7"], "sample_outputs": ["1\n3 1 2\n4 3 5 2 7 1 6"], "notes": "NoteFor $$$n = 3$$$, $$$[3,1,2]$$$ is a good permutation. Some of the subarrays are listed below. $$$3\\text{ OR }1 = 3 \\geq 2$$$ $$$(i = 1,j = 2)$$$ $$$3\\text{ OR }1\\text{ OR }2 = 3 \\geq 3$$$ $$$(i = 1,j = 3)$$$ $$$1\\text{ OR }2 = 3 \\geq 2$$$ $$$(i = 2,j = 3)$$$ $$$1 \\geq 1$$$ $$$(i = 2,j = 2)$$$ Similarly, you can verify that $$$[4,3,5,2,7,1,6]$$$ is also good."}, "positive_code": [{"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n3\n1\n3\n7\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction lcm(a, b) {\n return (a / gcd(a, b) * b);\n}\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const x = readline();\n var cases = parseInt(x);\n for(var i=1;i<=cases;i++){\n var line2 = readline();\n var currentNumber = parseInt(line2);\n console.log(getGoodPermutation(currentNumber));\n }\n \n}\nfunction getGoodPermutation(x) {\n var strs = [];\n for(var i=1;i<=x;i++){\n strs.push(i);\n }\n return strs.join(\" \");\n}"}, {"source_code": "var readline=require(\"readline\");\nvar rl=readline.createInterface({\n input:process.stdin,\n output:process.stdout\n});\nvar arr=[];\nrl.on('line',function(inp){\n arr.push(parseInt(inp));\n var T=arr[0];\n if(arr.length>1){\n var n=parseInt(arr[arr.length-1]);\n var str=\"1\";\n for(var i=2;i<=n;i++) str+=\" \"+i;\n console.log(str);\n }\n if(arr.length===(T+1)) process.exit(0);\n});"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n const arr = [];\n for (let i = 0; i < len; i++) {\n arr.push(i + 1);\n }\n console.log(arr.join(\" \"));\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n \tvar N = nextInt();\n \tvar list = [];\n \tfor(var j = N; j > 0; j--){\n \t\tlist.push(j);\n \t}\n \toutput[i] = myconv(list, 8);\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n\tdata = data.split('\\n');\n\tconst testCases = data[0] * 1;\n\tlet i = 1;\n\twhile (i <= testCases) {\n let n = data[i] * 1;\n let arr = [];\n for (let i = n; i > 0; i -= 1) arr.push(i);\n console.log(arr.join(' '));\n i += 1;\n\t}\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.split(/\\n/);\n main(); \n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const t = Number(readLine())\n for (let i = 0; i < t; i++) {\n const n = Number(readLine())\n console.log(Array(n).fill(0).map((_, i) => i + 1).join(' '))\n }\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = [];\n\t\tfor (let i = n; i > 0; i--) {\n\t\t\tarr.push(i);\n\t\t}\n\n\t\tconsole.log(arr.join(' '));\n\t}\n}\n"}, {"source_code": "function main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var n = +readline();\n var arr = [];\n for (var j = n; j > 0; j--) {\n arr.push(j);\n }\n print(arr.join(' '));\n }\n}\n\nmain();"}], "negative_code": [], "src_uid": "1b3ac752bc9c0b5e20a76f028d4b3c15"} {"nl": {"description": "Alice has an empty grid with $$$n$$$ rows and $$$m$$$ columns. Some of the cells are marked, and no marked cells are adjacent to the edge of the grid. (Two squares are adjacent if they share a side.) Alice wants to fill each cell with a number such that the following statements are true: every unmarked cell contains either the number $$$1$$$ or $$$4$$$; every marked cell contains the sum of the numbers in all unmarked cells adjacent to it (if a marked cell is not adjacent to any unmarked cell, this sum is $$$0$$$); every marked cell contains a multiple of $$$5$$$. Alice couldn't figure it out, so she asks Bob to help her. Help Bob find any such grid, or state that no such grid exists.", "input_spec": "The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 500$$$) — the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.' or 'X' — an unmarked and a marked cell, respectively. No marked cells are adjacent to the edge of the grid.", "output_spec": "Output \"'NO\" if no suitable grid exists. Otherwise, output \"'YES\"'. Then output $$$n$$$ lines of $$$m$$$ space-separated integers — the integers in the grid.", "sample_inputs": ["5 5\n.....\n.XXX.\n.X.X.\n.XXX.\n.....", "5 5\n.....\n.XXX.\n.XXX.\n.XXX.\n.....", "3 2\n..\n..\n..", "9 9\n.........\n.XXXXX.X.\n.X...X...\n.X.XXXXX.\n.X.X.X.X.\n.X.XXX.X.\n.X.....X.\n.XXXXXXX.\n........."], "sample_outputs": ["YES\n4 1 4 4 1\n4 5 5 5 1\n4 5 1 5 4\n1 5 5 5 4\n1 4 4 1 4", "NO", "YES\n4 1\n4 1\n1 4", "YES\n4 4 4 1 4 1 4 1 4\n1 5 5 5 5 5 4 10 1\n4 5 1 4 1 5 4 4 4\n4 5 1 5 5 0 5 5 1\n4 5 1 5 4 5 1 5 4\n4 5 1 5 5 5 4 5 1\n1 5 4 4 1 1 4 5 1\n4 5 5 5 5 5 5 5 4\n1 1 1 1 4 4 1 1 4"], "notes": "NoteIt can be shown that no such grid exists for the second test."}, "positive_code": [{"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst prt = (x) => process.stdout.write(x + \" \")\r\nconst assert = (condition) => { if (!condition) throw new Error(\"Assertion failed\"); }\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst int = parseInt;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg2 = Math.log2;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };\r\nconst initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\nconst ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);\r\nconst isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };\r\nconst initializeGraph = (n) => { let G = []; for (let i = 0; i < n; i++) { G.push([]); } return G; };\r\nconst addEdgeToG = (G, Edges) => { for (const [x, y] of Edges) { G[x].push(y); G[y].push(x); } };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 09/05/21 evening\r\n * https://codeforces.com/contest/1567/problem/F\r\n */\r\n\r\n// const dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\n\r\nconst dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];\r\nconst solve = (n, m, g) => {\r\n // pr(n, m)\r\n // pr(g)\r\n let adj = initializeGraph(n * m);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n let q = [];\r\n for (const [dx, dy] of dir) {\r\n let x = i + dx, y = j + dy;\r\n // pr(\"ijxy\", i, j, x, y)\r\n if (x < 0 || x >= n || y < 0 || y >= m) continue;\r\n // pr(\"xy\", x, y)\r\n if (g[x][y] == '.') {\r\n q.push(x * m + y);\r\n }\r\n }\r\n if (q.length & 1) return pr('NO');\r\n for (let k = 0; k < q.length; k += 2) {\r\n adj[q[k]].push(q[k + 1]);\r\n adj[q[k + 1]].push(q[k]);\r\n }\r\n }\r\n }\r\n }\r\n // pr(adj)\r\n let res = initialize2DArrayNew(n, m);\r\n let que = [];\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (res[i][j] > 0 || g[i][j] == 'X') continue;\r\n res[i][j] = 1;\r\n que.push(i * m + j);\r\n while (que.length) {\r\n let cur = que.shift();\r\n for (const v of adj[cur]) {\r\n let d = int(v / m);\r\n if (res[d][v % m] == 0) {\r\n res[d][v % m] = res[int(cur / m)][cur % m] ^ 5;\r\n que.push(v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n pr('YES');\r\n // pr(res);\r\n for (let i = 0; i < n; i++) {\r\n let data = [];\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n for (const [dx, dy] of dir) {\r\n let x = i + dx, y = j + dy;\r\n if (x < 0 || x >= n || y < 0 || y >= m) continue;\r\n if (g[x][y] == '.') {\r\n res[i][j] += res[x][y];\r\n }\r\n }\r\n }\r\n data.push(res[i][j]);\r\n // j == m - 1 ? pr(res[i][j]) : prt(res[i][j])\r\n }\r\n pr(data.join(\" \"))\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n // rl.on('line', (line) => {\r\n // input.push(line.split(\" \"));\r\n // });\r\n // rl.on('close', () => {\r\n // let a = input.shift();\r\n // // solve(a[0] - '0', a[2] - '0', input); // wrong of m\r\n // solve(a[0] - '0', a.slice(2).join(\"\") - '0', input); // wrong n \r\n // });\r\n rl.on('line', (line) => {\r\n input.push(line);\r\n });\r\n rl.on('close', () => {\r\n let a = input.shift().split(\" \");\r\n input = input.map(s => s.split(\"\"))\r\n solve(a[0] - '0', a[1] - '0', input);\r\n });\r\n};\r\n\r\nmain()"}], "negative_code": [{"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst prt = (x) => process.stdout.write(x + \" \")\r\nconst assert = (condition) => { if (!condition) throw new Error(\"Assertion failed\"); }\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst int = parseInt;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg2 = Math.log2;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };\r\nconst initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\nconst ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);\r\nconst isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };\r\nconst initializeGraph = (n) => { let G = []; for (let i = 0; i < n; i++) { G.push([]); } return G; };\r\nconst addEdgeToG = (G, Edges) => { for (const [x, y] of Edges) { G[x].push(y); G[y].push(x); } };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 09/05/21 evening\r\n * https://codeforces.com/contest/1567/problem/F\r\n */\r\n\r\n// const dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\n\r\nconst dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];\r\nconst solve = (n, m, g) => {\r\n // pr(n, m)\r\n // pr(g)\r\n let adj = initializeGraph(n * m);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n let q = [];\r\n for (const [dx, dy] of dir) {\r\n let x = i + dx, y = j + dy;\r\n // pr(\"ijxy\", i, j, x, y)\r\n if (x < 0 || x >= n || y < 0 || y >= m) continue;\r\n // pr(\"xy\", x, y)\r\n if (g[x][y] == '.') {\r\n q.push(x * m + y);\r\n }\r\n }\r\n if (q.length & 1) return pr('NO');\r\n for (let k = 0; k < q.length; k += 2) {\r\n adj[q[k]].push(q[k + 1]);\r\n adj[q[k + 1]].push(q[k]);\r\n }\r\n }\r\n }\r\n }\r\n // pr(adj)\r\n let res = initialize2DArrayNew(n, m);\r\n let que = [];\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (res[i][j] > 0 || g[i][j] == 'X') continue;\r\n res[i][j] = 1;\r\n que.push(i * m + j);\r\n while (que.length) {\r\n let cur = que.shift();\r\n for (const v of adj[cur]) {\r\n let d = int(v / m);\r\n if (res[d][v % m] == 0) {\r\n res[d][v % m] = res[int(cur / m)][cur % m] ^ 5;\r\n que.push(v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n pr('YES');\r\n // pr(res);\r\n for (let i = 0; i < n; i++) {\r\n let data = [];\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n for (const [dx, dy] of dir) {\r\n let x = i + dx, y = j + dy;\r\n if (x < 0 || x >= n || y < 0 || y >= m) continue;\r\n if (g[x][y] == '.') {\r\n res[i][j] += res[x][y];\r\n }\r\n }\r\n }\r\n data.push(res[i][j]);\r\n // j == m - 1 ? pr(res[i][j]) : prt(res[i][j])\r\n }\r\n pr(data.join(\" \"))\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\"\"));\r\n });\r\n rl.on('close', () => {\r\n let a = input.shift();\r\n // solve(a[0] - '0', a[2] - '0', input); // wrong of m\r\n\r\n // pr(a.slice(2).join(\"\") - '0')\r\n solve(a[0] - '0', a.slice(2).join(\"\") - '0', input); // wrong of m\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst prt = (x) => process.stdout.write(x + \" \")\r\nconst assert = (condition) => { if (!condition) throw new Error(\"Assertion failed\"); }\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst int = parseInt;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg2 = Math.log2;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };\r\nconst initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\nconst ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);\r\nconst isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };\r\nconst initializeGraph = (n) => { let G = []; for (let i = 0; i < n; i++) { G.push([]); } return G; };\r\nconst addEdgeToG = (G, Edges) => { for (const [x, y] of Edges) { G[x].push(y); G[y].push(x); } };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 09/05/21 evening\r\n * https://codeforces.com/contest/1567/problem/F\r\n */\r\n\r\nconst dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\nconst solve = (n, m, g) => {\r\n // r(n, m, g)\r\n let adj = initializeGraph(n * m);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n let q = [];\r\n for (const [x, y] of dir) {\r\n let dx = i + x, dy = j + y;\r\n if (g[dx][dy] == '.') {\r\n q.push(dx * m + dy);\r\n }\r\n }\r\n if (q.length & 1) return pr('NO');\r\n for (let k = 0; k < q.length; k += 2) {\r\n adj[q[k]].push(q[k + 1]);\r\n adj[q[k + 1]].push(q[k]);\r\n }\r\n }\r\n }\r\n }\r\n // pr(adj)\r\n let res = initialize2DArrayNew(n, m);\r\n let que = [];\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (res[i][j] > 0 || g[i][j] == 'X') continue;\r\n res[i][j] = 1;\r\n que.push(i * m + j);\r\n while (que.length) {\r\n let cur = que.shift();\r\n for (const v of adj[cur]) {\r\n let d = int(v / m);\r\n if (res[d][v % m] == 0) {\r\n res[d][v % m] = res[int(cur / m)][cur % m] ^ 5;\r\n que.push(v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n pr('YES');\r\n // pr(res);\r\n for (let i = 0; i < n; i++) {\r\n let data = [];\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n for (const [x, y] of dir) {\r\n let dx = i + x, dy = j + y;\r\n if (g[dx][dy] == '.') {\r\n res[i][j] += res[dx][dy];\r\n }\r\n }\r\n }\r\n data.push(res[i][j]);\r\n // j == m - 1 ? pr(res[i][j]) : prt(res[i][j])\r\n }\r\n pr(data.join(\" \"))\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\"\"));\r\n });\r\n rl.on('close', () => {\r\n let a = input.shift();\r\n solve(a[0] - '0', a[2] - '0', input);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst prt = (x) => process.stdout.write(x + \" \")\r\nconst assert = (condition) => { if (!condition) throw new Error(\"Assertion failed\"); }\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst int = parseInt;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg2 = Math.log2;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };\r\nconst initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\nconst ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);\r\nconst isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };\r\nconst initializeGraph = (n) => { let G = []; for (let i = 0; i < n; i++) { G.push([]); } return G; };\r\nconst addEdgeToG = (G, Edges) => { for (const [x, y] of Edges) { G[x].push(y); G[y].push(x); } };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 09/05/21 evening\r\n * https://codeforces.com/contest/1567/problem/F\r\n */\r\n\r\nconst dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\nconst solve = (n, m, g) => {\r\n // r(n, m, g)\r\n let adj = initializeGraph(n * m);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n let q = [];\r\n for (const [x, y] of dir) {\r\n let dx = i + x, dy = j + y;\r\n if (g[dx][dy] == '.') {\r\n q.push(dx * m + dy);\r\n }\r\n }\r\n if (q.length & 1) return pr('NO');\r\n for (let k = 0; k < q.length; k += 2) {\r\n adj[q[k]].push(q[k + 1]);\r\n adj[q[k + 1]].push(q[k]);\r\n }\r\n }\r\n }\r\n }\r\n // pr(adj)\r\n let res = initialize2DArrayNew(n, m);\r\n let que = [];\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (res[i][j] > 0 || g[i][j] == 'X') continue;\r\n res[i][j] = 1;\r\n que.push(i * m + j);\r\n while (que.length) {\r\n let cur = que.shift();\r\n for (const v of adj[cur]) {\r\n let d = int(v / m);\r\n if (res[d][v % m] == 0) {\r\n res[d][v % m] = res[int(cur / m)][cur % m] ^ 5;\r\n que.push(v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n pr('YES');\r\n // pr(res);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n for (const [x, y] of dir) {\r\n let dx = i + x, dy = j + y;\r\n if (g[dx][dy] == '.') {\r\n res[i][j] += res[dx][dy];\r\n }\r\n }\r\n }\r\n j == m - 1 ? pr(res[i][j]) : prt(res[i][j])\r\n }\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\"\"));\r\n });\r\n rl.on('close', () => {\r\n let a = input.shift();\r\n solve(a[0] - '0', a[2] - '0', input);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst assert = (condition) => { if (!condition) throw new Error(\"Assertion failed\"); }\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst int = parseInt;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg2 = Math.log2;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };\r\nconst initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\nconst ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);\r\nconst isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };\r\nconst initializeGraph = (n) => { let G = []; for (let i = 0; i < n; i++) { G.push([]); } return G; };\r\nconst addEdgeToG = (G, Edges) => { for (const [x, y] of Edges) { G[x].push(y); G[y].push(x); } };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 09/05/21 evening\r\n * https://codeforces.com/contest/1567/problem/F\r\n */\r\n\r\nconst dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\nconst solve = (n, m, g) => {\r\n // r(n, m, g)\r\n let adj = initializeGraph(n * m);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n let q = [];\r\n for (const [x, y] of dir) {\r\n let dx = i + x, dy = j + y;\r\n if (g[dx][dy] == '.') {\r\n q.push(dx * m + dy);\r\n }\r\n }\r\n if (q.length & 1) return pr('NO');\r\n for (let k = 0; k < q.length; k += 2) {\r\n adj[q[k]].push(q[k + 1]);\r\n adj[q[k + 1]].push(q[k]);\r\n }\r\n }\r\n }\r\n }\r\n // pr(adj)\r\n let res = initialize2DArrayNew(n, m);\r\n let que = [];\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (res[i][j] > 0 || g[i][j] == 'X') continue;\r\n res[i][j] = 1;\r\n que.push(i * m + j);\r\n while (que.length) {\r\n let cur = que.shift();\r\n for (const v of adj[cur]) {\r\n let d = int(v / m);\r\n if (res[d][v % m] == 0) {\r\n res[d][v % m] = res[int(cur / m)][cur % m] ^ 5;\r\n que.push(v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n pr('YES');\r\n // pr(res);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == 'X') {\r\n for (const [x, y] of dir) {\r\n let dx = i + x, dy = j + y;\r\n if (g[dx][dy] == '.') {\r\n res[i][j] += res[dx][dy];\r\n }\r\n }\r\n }\r\n if (j == m - 1) pr(res[i][j], 1);\r\n }\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\"\"));\r\n });\r\n rl.on('close', () => {\r\n let a = input.shift();\r\n solve(a[0] - '0', a[2] - '0', input);\r\n });\r\n};\r\n\r\nmain()"}], "src_uid": "acbcf0b55f204a12d861936c8a60a8b0"} {"nl": {"description": "You are given a grid with $$$n$$$ rows and $$$m$$$ columns. Rows and columns are numbered from $$$1$$$ to $$$n$$$, and from $$$1$$$ to $$$m$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$. Initially, you are standing in the top left corner $$$(1, 1)$$$. Your goal is to reach the bottom right corner $$$(n, m)$$$.You can move in four directions from $$$(a, b)$$$: up to $$$(a-1, b)$$$, down to $$$(a+1, b)$$$, left to $$$(a, b-1)$$$ or right to $$$(a, b+1)$$$.You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach $$$(n, m)$$$?", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) — the number of the test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^9$$$) — the size of the grid.", "output_spec": "For each test case, print a single integer: $$$-1$$$ if it is impossible to reach $$$(n, m)$$$ under the given conditions, otherwise the minimum number of moves.", "sample_inputs": ["6\n\n1 1\n\n2 1\n\n1 3\n\n4 2\n\n4 6\n\n10 5"], "sample_outputs": ["0\n1\n-1\n6\n10\n17"], "notes": "NoteTest case $$$1$$$: $$$n=1$$$, $$$m=1$$$, and initially you are standing in $$$(1, 1)$$$ so $$$0$$$ move is required to reach $$$(n, m) = (1, 1)$$$.Test case $$$2$$$: you should go down to reach $$$(2, 1)$$$.Test case $$$3$$$: it is impossible to reach $$$(1, 3)$$$ without moving right two consecutive times, or without leaving the grid.Test case $$$4$$$: an optimal moving sequence could be: $$$(1, 1) \\to (1, 2) \\to (2, 2) \\to (2, 1) \\to (3, 1) \\to (3, 2) \\to (4, 2)$$$. It can be proved that this is the optimal solution. So the answer is $$$6$$$."}, "positive_code": [{"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n var n = nextInt();\r\n\t\tvar m = nextInt();\r\n\r\n let max = Math.max(n, m), min = Math.min(n, m);\r\n\r\n if (min === 1) {\r\n if (max === 1) {\r\n myout(0);\r\n } else if (max === 2) {\r\n myout(1);\r\n } else {\r\n myout(-1);\r\n }\r\n continue\r\n } \r\n \r\n if (max === min + 1 || max === min) {\r\n myout(max + min - 2);\r\n continue;\r\n } \r\n\r\n let diff = max - min;\r\n let res = 0;\r\n if (diff % 2 === 1) {\r\n res += 1\r\n }\r\n\r\n res += min*2 - 2 + Math.floor(diff / 2) * 4;\r\n myout(res)\r\n // output in nodeJs\r\n // console.log(arr)\r\n\t}\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n var n = nextInt();\r\n\t\tvar m = nextInt();\r\n\r\n let max = Math.max(n, m), min = Math.min(n, m);\r\n\r\n if (min === 1) {\r\n if (max === 1) {\r\n myout(0);\r\n } else if (max === 2) {\r\n myout(1);\r\n } else {\r\n myout(-1);\r\n }\r\n continue\r\n } \r\n \r\n if (max === min + 1 || max === min) {\r\n myout(max + min - 2);\r\n continue;\r\n } \r\n\r\n let diff = max - min;\r\n let res = 0;\r\n if (diff % 2 === 1) {\r\n res += 1\r\n }\r\n\r\n res += min*2 - 2 + Math.floor(diff / 2) * 4;\r\n myout(res)\r\n // output in nodeJs\r\n // console.log(arr)\r\n\t}\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n var n = nextInt();\r\n\t\tvar m = nextInt();\r\n\r\n let max = Math.max(n, m), min = Math.min(n, m);\r\n\r\n if (min === 1) {\r\n if (max === 1) {\r\n myout(0);\r\n } else if (max === 2) {\r\n myout(1);\r\n } else {\r\n myout(-1);\r\n }\r\n continue\r\n } \r\n \r\n if (max === min + 1 || max === min) {\r\n myout(max + min - 2);\r\n continue;\r\n } \r\n\r\n let diff = max - min;\r\n let res = 0;\r\n if (diff % 2 === 1) {\r\n res += 1\r\n }\r\n\r\n res += min*2 - 2 + Math.floor(diff / 2) * 4;\r\n myout(res)\r\n // output in nodeJs\r\n // console.log(arr)\r\n\t}\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n'); \r\n main(); \r\n});\r\n\r\nfunction readLine(){\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main(){\r\n // input in nodeJs\r\n\tlet test = parseInt(readLine(),10);\r\n\twhile(test--){\r\n\t\tlet [n, m] = readLine().split(\" \").map(ele => parseInt(ele, 10));\r\n \r\n let max = Math.max(n, m), min = Math.min(n, m);\r\n\r\n if (min === 1) {\r\n if (max === 1) {\r\n console.log(0);\r\n } else if (max === 2) {\r\n console.log(1);\r\n } else {\r\n console.log(-1);\r\n }\r\n continue\r\n } \r\n \r\n if (max === min + 1 || max === min) {\r\n console.log(max + min - 2);\r\n continue;\r\n } \r\n\r\n let diff = max - min;\r\n let res = 0;\r\n if (diff % 2 === 1) {\r\n res += 1\r\n }\r\n\r\n res += min*2 - 2 + Math.floor(diff / 2) * 4;\r\n console.log(res)\r\n // output in nodeJs\r\n // console.log(arr)\r\n\t}\r\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet s = \"\";\nprocess.stdin.on(\"data\", (data) => {\n s += data;\n});\n\nprocess.stdin.on(\"end\", () => {\n s = s.trim().split(\"\\n\");\n\n main();\n});\n\nfunction main() {\n let t = Number(s[0]);\n\n let i = 1;\n while (t--) {\n const [m, n] = s[i].split(\" \").map(Number);\n solve(m, n);\n i++;\n }\n}\n\nfunction solve(m, n) {\n if (m === 1 || n === 1) {\n if (Math.abs(m - n) === 1) {\n console.log(1);\n return;\n }\n if (m + n > 2) {\n console.log(-1);\n return;\n }\n }\n\n if (m < n) {\n [m, n] = [n, m];\n }\n\n let count = 0;\n const diag = 2 * (n - 1);\n\n count += diag;\n\n const remaining = m - n;\n const twoJumps = Math.floor(remaining / 2);\n count += twoJumps * 4;\n count += remaining % 2;\n\n console.log(count);\n}\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(n, m) {\r\n if (n > m) {\r\n return solve(m, n);\r\n } else {\r\n if (n === 1 && m > 2) console.log(-1);else if ((n & 1) === (m & 1)) console.log(m * 2 - 2);else console.log(m * 2 - 3);\r\n }\r\n}\r\n\r\nfunction main(inputs) {\r\n const _ = Number(inputs[0]);\r\n\r\n for (let __ = 1; __ <= _; __++) {\r\n const [n, m] = inputs[__].trim().split(' ').map(Number);\r\n\r\n solve(n, m);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nmain(inputs);\r\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n for(let i=1;i<=t;i++)\r\n {\r\n let [x,y]=line[i].split(' ').map(x=>{return parseInt(x)});\r\n x--;\r\n y--;\r\n if(x>y) [x,y]=[y,x];\r\n if(x===0)\r\n {\r\n if(y<=1) console.log(y);\r\n else console.log(-1);\r\n }\r\n else\r\n {\r\n let ans=y+x+(y-x-1);\r\n if((y-x-1)&1) ans++;\r\n console.log(ans);\r\n }\r\n }\r\n})"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n var n = k[0], m = k[1];\n if(n < m){\n var temp = n;\n n = m;\n m = temp;\n }\n if(m == 1 && n >= 3){\n console.log(-1);\n }else{\n console.log(2 * n - Math.floor((n + m) % 2) - 2);\n }\n }\n});"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let [n, m] = readline().split(' ').map(Number);\r\n if (m > n) [m, n] = [n, m];\r\n\r\n if (m === 1 && n > 2) {\r\n output(-1);\r\n continue;\r\n }\r\n\r\n output(2*n-2-(n+m)%2);\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst lineReader = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet inputPos = 0;\r\nconst inputWords = [];\r\nlineReader.on('line', (line) => {\r\n inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));\r\n});\r\nlineReader.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(inputWords[inputPos++]));\r\n}\r\nfunction nextStr() {\r\n return inputWords[inputPos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nconst INF = Infinity;\r\nfunction solve(n, m) {\r\n if (n < m) {\r\n [n, m] = [m, n];\r\n }\r\n if (m == 1 && n > 2) {\r\n return INIT;\r\n }\r\n let ans = m + m - 2;\r\n n -= m;\r\n let pairs = n - (n % 2);\r\n ans += pairs * 2;\r\n if ((n % 2) == 1) {\r\n ans++;\r\n }\r\n return ans;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n let n = nextInt();\r\n let m = nextInt();\r\n printf(\"%d\\n\", solve(n, m));\r\n }\r\n}\r\n"}, {"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const [n, m] = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n m,\n };\n testCases.push(testCase);\n }\n}\n\nfunction solution(testCase, index) {\n const { n, m } = testCase;\n\n const mini = Math.min(m - 1, n - 1);\n const maxi = Math.max(m - 1, n - 1);\n const diff = Math.abs(m - n);\n\n let result =\n mini == 0 && maxi > 1\n ? -1\n : mini * 2 + Math.floor(diff / 2) * 4 + (diff % 2);\n console.log(result);\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\n\n\nconst calc = (n, m)=>{\n if (n === 1 && m === 1) return 0;\n if (n === 1 && m > 2 || n > 2 && m === 1) return -1;\n if (n === 1 && m === 2 || n === 2 && m === 1) return 1;\n\n let diag = (Math.min(n, m) - 1) * 2;\n // console.log('DEBUG diag', diag);\n if (n === m) return diag;\n\n let diff = Math.abs(n - m);\n\n\n let x1 = Math.floor((diff + 1) / 2);\n let x2 = Math.floor(diff / 2);\n // console.log('DEBUG x1', x1);\n // console.log('DEBUG x2', x2);\n\n let min = Math.min(n, m);\n let divBy2 = min % 2;\n // console.log('DEBUG divBy2', divBy2);\n\n // let ones = divBy2 ? x2 : x1;\n // let threes = divBy2 ? x1 : x2;\n let ones = x1;\n let threes = x2;\n\n // console.log('DEBUG ones', ones);\n // console.log('DEBUG threes', threes);\n\n let res = diag + ones + threes * 3;\n\n return res;\n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let [n, m] = ra();\n \n console.log(`${calc(n, m)}`);\n }\n}"}, {"source_code": "'use strict';\n\nconst { checkPrime } = require('crypto');\nconst { Z_FIXED } = require('zlib');\n\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst l = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\n \nconst ra = ()=>readline().split(' ').map(a=>+a)\n\nconst calc = (n, m)=>{\n if (n>m)\n return calc(m, n);\n // n1)\n return -1;\n let ans = n*2;\n m -= n;\n if (m==0)\n return ans;\n l({ans, m})\n return ans + Math.floor((m)/2)*4 + m%2;\n if (m%3==2){\n }\n ans++;\n m--;\n ans += m*2\n if (0)\n if (m%2) \n ans++;\n return ans;\n};\n \nfunction main() {\n let T = +readline()\n while (T--){\n let [n, m] = ra();\n l('ans')\n print(calc(n, m));\n }\n}\n \nE.calc = calc;"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar M = nextInt();\r\n\t\tvar H = Math.min(N, M);\r\n\t\tvar W = Math.max(N, M);\r\n\t\tif(H == 1 && W >= 3){\r\n\t\t\tmyout(-1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tvar output = (H - 1) + (W - 1);\r\n\t\tif(W - H >= 2){\r\n\t\t\tvar diff = W - H;\r\n\t\t\toutput += Math.floor(diff / 2) * 2;\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet s = \"\";\nprocess.stdin.on(\"data\", (data) => {\n s += data;\n});\n\nprocess.stdin.on(\"end\", () => {\n s = s.trim().split(\"\\n\");\n\n main();\n});\n\nfunction main() {\n let t = Number(s[0]);\n\n let i = 1;\n while (t--) {\n const [m, n] = s[i].split(\" \").map(Number);\n solve(m, n);\n i++;\n }\n}\n\nfunction solve(m, n) {\n if (m === 1 || n === 1) {\n if (m - n === 1) {\n console.log(1);\n return;\n }\n if (m + n > 2) {\n console.log(-1);\n return;\n }\n }\n\n if (m < n) {\n [m, n] = [n, m];\n }\n\n let count = 0;\n const diag = 2 * (n - 1);\n\n count += diag;\n\n const remaining = m - n;\n const twoJumps = Math.floor(remaining / 2);\n count += twoJumps * 4;\n count += remaining % 2;\n\n console.log(count);\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet s = \"\";\nprocess.stdin.on(\"data\", (data) => {\n s += data;\n});\n\nprocess.stdin.on(\"end\", () => {\n s = s.trim().split(\"\\n\");\n\n main();\n});\n\nfunction main() {\n let t = Number(s[0]);\n\n let i = 1;\n while (t--) {\n const [m, n] = s[i].split(\" \").map(Number);\n solve(m, n);\n i++;\n }\n}\n\nfunction solve(m, n) {\n if (m === 1 && n === 1) {\n console.log(0);\n return 0;\n }\n if (m === 1 || n === 1) {\n console.log(-1);\n return;\n }\n\n let sx = 1,\n sy = 1;\n\n let count = 0;\n const defOptions = [\n [1, 0],\n [0, 1],\n ];\n let i = 0;\n while (sx !== m && sy !== n) {\n sx += defOptions[i][0];\n sy += defOptions[i][1];\n i = (i + 1) % 2;\n count++;\n }\n\n const diff = sx === m ? n - sy : m - sx;\n const q = Math.floor(diff / 2);\n const r = diff % 2;\n count += q * 4 + r;\n\n console.log(count);\n}\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(n, m) {\r\n if (m === n) {\r\n console.log(n * (n - 1));\r\n } else if (n > m) {\r\n return solve(m, n);\r\n } else {\r\n if (n === 1 && m > 2) console.log(-1);else if ((n & 1) === (m & 1)) console.log(m * 2 - 2);else console.log(m * 2 - 3);\r\n }\r\n}\r\n\r\nfunction main(inputs) {\r\n const _ = Number(inputs[0]);\r\n\r\n for (let __ = 1; __ <= _; __++) {\r\n const [n, m] = inputs[__].trim().split(' ').map(Number);\r\n\r\n solve(n, m);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nmain(inputs);\r\n"}], "src_uid": "6f0d3a7971ffc2571838ecd8bf14238d"} {"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 — $$$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}$$$ — 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$$$) — 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": "var fl = readline().split(' ').map(v=>+v);\nvar p = fl[0]; var t = fl[1];\n\nvar taxists = [];\nvar data = readline().split(' ').map(v=>+v);\n\nvar cnt = 0, prevCoord = 0, prevInd =-1;\nreadline().split(' ').forEach((v, ind)=> {\n if(!(+v)) {\n cnt++;\n } else {\n var coord = data[ind]\n var people = 0;\n\n if(prevInd < 0) {\n people = cnt\n } else {\n for(var i = prevInd + 1; i < ind; i++) {\n if(data[i] - prevCoord <= coord - data[i]) {\n taxists[taxists.length - 1] ++;\n } else {\n people++;\n }\n }\n }\n\n taxists.push(people)\n\n prevInd = ind;\n prevCoord = coord;\n\n cnt = 0;\n }\n})\n\ntaxists[taxists.length - 1] += cnt;\n\nprint(taxists.join(' '));"}], "negative_code": [], "src_uid": "56ea328f84b2930656ff5eb9b8fda8e0"} {"nl": {"description": "You are given a matrix of size $$$n \\times n$$$ filled with lowercase English letters. You can change no more than $$$k$$$ letters in this matrix.Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $$$2n - 1$$$.Find the lexicographically smallest string that can be associated with a path after changing letters in at most $$$k$$$ cells of the matrix.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$, if the first different letter in $$$a$$$ and $$$b$$$ is smaller in $$$a$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2000$$$, $$$0 \\le k \\le n^2$$$) — the size of the matrix and the number of letters you can change. Each of the next $$$n$$$ lines contains a string of $$$n$$$ lowercase English letters denoting one row of the matrix.", "output_spec": "Output the lexicographically smallest string that can be associated with some valid path after changing no more than $$$k$$$ letters in the matrix.", "sample_inputs": ["4 2\nabcd\nbcde\nbcad\nbcde", "5 3\nbwwwz\nhrhdh\nsepsp\nsqfaf\najbvw", "7 6\nypnxnnp\npnxonpm\nnxanpou\nxnnpmud\nnhtdudu\nnpmuduh\npmutsnz"], "sample_outputs": ["aaabcde", "aaaepfafw", "aaaaaaadudsnz"], "notes": "NoteIn the first sample test case it is possible to change letters 'b' in cells $$$(2, 1)$$$ and $$$(3, 1)$$$ to 'a', then the minimum path contains cells $$$(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$$$. The first coordinate corresponds to the row and the second coordinate corresponds to the column."}, "positive_code": [{"source_code": "var fl = readline().split(' ').map(v=>+v);\nvar side = fl[0];\nvar change = fl[1];\n\nvar matrix = [];\nfor(var i = 0; i < side; i++) {\n matrix.push(readline());\n}\n\nvar symbA = 'a';\nvar dirs = [{x: 1, y: 0}, {x: 0, y: 1}];\n\nvar paths = [{x: 0, y: 0, change: change}];\nvar line = matrix[0][0];\n\nif(change && line !== symbA) {\n paths[0].change--;\n line = symbA;\n}\n\nfor(var step = 2; step < side * 2; step++) {\n var min = {letter: '|', paths: []};\n var previous = null;\n\n for(var i = 0; i < paths.length; i++) {\n var path = paths[i];\n for(var j = 0; j < 2; j++) {\n var dir = dirs[j];\n var x = path.x + dir.x, y = path.y + dir.y;\n if(x === side || y === side) {\n previous = null;\n continue;\n }\n\n var letter = matrix[y][x];\n var change = path.change;\n\n if(change && letter !== symbA) {\n change--;\n letter = symbA;\n }\n\n var newPath = {x: x, y: y, change: change};\n if (letter < min.letter) {\n min.letter = letter;\n min.paths = [];\n previous = null;\n } else if (letter > min.letter) {\n previous = null;\n continue;\n }\n\n var code = x - y;\n if(j === 0 && previous) {\n if(previous.code === code) {\n if(previous.change >= change) {\n newPath = null;\n } else {\n min.paths.pop();\n }\n }\n } else if (j === 1) {\n previous = {code: code, change: change};\n }\n if(newPath) {\n min.paths.push(newPath)\n }\n }\n }\n\n paths = min.paths;\n line += min.letter;\n}\n\nprint(line);"}], "negative_code": [], "src_uid": "24afabd9cbbe287ea83c780f1797297c"} {"nl": {"description": "Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$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$$$) — 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$$$) — 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$$$) — 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": "const input = [];\n\nfunction splbsi(line) {\n return line.split(\" \").map((x) => parseInt(x));\n}\n\nconst readLine = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nreadLine.on(\"line\", (line) => {\n input.push(line);\n});\n\nreadLine.on(\"close\", () => {\n for (let i = 1; i < input.length; i += 2) {\n const [n, k] = splbsi(input[i]);\n const arr = splbsi(input[i + 1]);\n\n const nums = new Set(arr);\n\n if (nums.size > k) {\n console.log(-1);\n continue;\n }\n\n const res = [...nums];\n for (let j = 0; j < k - nums.size; j += 1) {\n res.push(1);\n }\n\n const answer = [];\n for (let i = 0; i < n; i += 1) {\n answer.push(...res);\n }\n\n console.log(answer.length);\n console.log(answer.join(\" \"));\n }\n});\n"}, {"source_code": "const processData = (lines) => {\n const nums = +lines[0]\n for (let i =0; i +x)\n const arr = lines[i*2+2].split(' ').map(x => +x)\n const ns = new Set()\n for (const num of arr) {\n ns.add(num)\n }\n const s = Array.from(ns)\n if (s.length > k) {\n console.log(-1)\n } else {\n let diff = k - s.length\n while (diff) {\n s.push(s[0])\n diff--\n }\n console.log(n * s.length)\n console.log(arr.reduce((r) => r.concat(s), []).join(' '))\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var unique = new Set(numbers);\n\n if(unique.size > limit) {\n console.log(-1);\n continue;\n }\n\n const output = [];\n for(let i=0;i parseInt(x));\n}\n\nconst readLine = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nreadLine.on(\"line\", (line) => {\n input.push(line);\n});\n\nreadLine.on(\"close\", () => {\n for (let i = 1; i < input.length; i += 2) {\n const [n, k] = splbsi(input[i]);\n const arr = splbsi(input[i + 1]);\n\n const nums = new Set(arr);\n\n if (nums.size > k) {\n console.log(-1);\n continue;\n }\n\n const res = [];\n for (let j = 0; j < n; j += 1) {\n res.push(...[...nums, 1]);\n }\n\n console.log(n * k);\n console.log(res.join(\" \"));\n }\n});\n"}, {"source_code": "const input = [];\n\nfunction splbsi(line) {\n return line.split(\" \").map((x) => parseInt(x));\n}\n\nconst readLine = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nreadLine.on(\"line\", (line) => {\n input.push(line);\n});\n\nreadLine.on(\"close\", () => {\n for (let i = 1; i < input.length; i += 2) {\n const [n, k] = splbsi(input[i]);\n const arr = splbsi(input[i + 1]);\n\n const nums = new Set(arr);\n\n if (nums.size > k) {\n console.log(-1);\n continue;\n }\n\n const res = [];\n for (let j = 0; j < n; j += 1) {\n res.push(...[...nums, 1]);\n }\n\n console.log(res.length);\n console.log(res.join(\" \"));\n }\n});\n"}, {"source_code": "const input = [];\n\nfunction splbsi(line) {\n return line.split(\" \").map((x) => parseInt(x));\n}\n\nconst readLine = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nreadLine.on(\"line\", (line) => {\n input.push(line);\n});\n\nreadLine.on(\"close\", () => {\n for (let i = 1; i < input.length; i += 2) {\n const [n, k] = splbsi(input[i]);\n const arr = splbsi(input[i + 1]);\n\n const nums = new Set(arr);\n\n if (nums.size > k) {\n console.log(-1);\n continue;\n }\n\n const res = [];\n while (res.length <= n) {\n res.push(...nums);\n }\n\n console.log(res.length);\n console.log(res.join(\" \"));\n }\n});\n"}, {"source_code": "const processData = (lines) => {\n const nums = +lines[0]\n for (let i =0; i +x)\n const arr = lines[i*2+2].split(' ').map(x => +x)\n const ns = new Set()\n for (const num of arr) {\n ns.add(num)\n }\n const s = Array.from(ns)\n if (s.length > k) {\n console.log(-1)\n } else {\n console.log(n * s.length)\n console.log(arr.reduce((r) => r.concat(s), []).join(' '))\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var oldNumber = [...numbers];\n numbers.sort((a,b) => a-b);\n\n if(numbers.join(\"\") === oldNumber.join(\"\")) {\n console.log(-1);\n } else {\n let max = Math.max.apply(null, oldNumber);\n let output = [];\n\n for(let i=0;i {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var unique = new Set(numbers);\n\n if(unique.size === numbers.length) {\n console.log(-1);\n continue;\n }\n\n const output = [];\n console.log(n*limit);\n for(let i=0;i<= n;i++) {\n output.push(...Array.from(unique));\n if(!unique.has(1)) {\n output.push(1);\n }\n }\n console.log(output.join(\" \"));\n\n }\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var oldNumber = [...numbers];\n numbers.sort((a,b) => a-b);\n\n if(numbers.join(\"\") === oldNumber.join(\"\")) {\n console.log(-1);\n } else {\n let max = Math.max.apply(null, oldNumber);\n limit = limit * 2;\n let output = [];\n\n for(let i=0;i {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var unique = new Set(numbers);\n\n if(unique.size >= limit) {\n console.log(-1);\n continue;\n }\n\n const output = [];\n for(let i=0;i {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var unique = new Set(numbers);\n\n if(unique.size === numbers.length) {\n console.log(-1);\n continue;\n }\n\n const output = [];\n for(let i=0;i {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var oldNumber = [...numbers];\n numbers.sort((a,b) => a-b);\n\n if(numbers.join(\"\") === oldNumber.join(\"\")) {\n console.log(-1);\n } else {\n let max = Math.max.apply(null, oldNumber);\n let output = [];\n\n for(let i=0;i {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 1 2\n 2 3\n 2 4\n 4 5\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r parseInt(x));\n var numbers = readline().split(\" \").map(x=> parseInt(x));\n var unique = new Set(numbers);\n\n if(unique.size === numbers.length) {\n console.log(-1);\n continue;\n }\n\n const output = [];\n console.log(n*limit);\n for(let i=0;i<= n;i++) {\n output.push(Array.from(unique));\n if(!unique.has(1)) {\n output.push(1);\n }\n }\n console.log(output.join(\" \"));\n\n }\n}"}], "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 + 2 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 ≤ n ≤ 15 and 1 ≤ m ≤ 100) — 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 + 2 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 — 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": "function readInts() {\n return readline().split(' ').map(function (v) { return parseInt(v); });\n}\nfunction min(_a, _b) {\n var l1 = _a[0], r1 = _a[1];\n var l2 = _b[0], r2 = _b[1];\n // console.log('min', [l1, r1], [l2, r2]);\n return [l1 < l2 ? l1 : l2, r1 < r2 ? r1 : r2];\n}\nfunction solve(n, m, rooms) {\n var _a, _b, _c;\n var first = true;\n var _d = [0, 0], l = _d[0], r = _d[1];\n var f = 0;\n while (f < n) {\n var room = rooms[f];\n var leftmost = room.indexOf('1');\n if (leftmost < 0) {\n if (!first)\n _a = min([l + 1, r + 1], [r + m + 2, l + m + 2]), l = _a[0], r = _a[1];\n }\n else {\n var rightmost = room.lastIndexOf('1');\n if (first) {\n _b = [rightmost, m - leftmost + 1], l = _b[0], r = _b[1];\n first = false;\n }\n else {\n _c = min([m + 2 + r, m + 2 + l], [rightmost * 2 + 1 + l, (m - leftmost + 1) * 2 + 1 + r]), l = _c[0], r = _c[1];\n }\n }\n // console.log({ f, l, r });\n f++;\n }\n return l;\n}\n// function show(n: number, m: number, rooms: string[]) {\n// console.log({n, m, rooms}, '-->', solve(n, m, rooms))\n// }\n// show(2, 2, [\n// '0010',\n// '0100']);\n// show(3, 4, [\n// '001000',\n// '000010',\n// '000010']);\n// show(4, 3, [\n// '01110',\n// '01110',\n// '01110',\n// '01110'])\nvar _a = readInts(), n = _a[0], m = _a[1];\nvar rooms = [];\nfor (var i = 0; i < n; i++)\n rooms.push(readline());\nprint(solve(n, m, rooms));\n"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar m = parseInt(arr[1]);\nvar v = Array(n);\nvar count = 0;\nvar ef = 0;\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline();\n var line = arr.substr(1,m);\n // var line = Array(m).fill(0);\n // for (var j = 0; j < m; j ++)\n // {\n // line[j] = arr.charAt(j+1)=='1'?1:0;\n // }\n // v.splice(v, 0, line);\n if (line.indexOf('1') != -1)\n {\n v[count++] = line;\n }\n else if (count !== 0)\n {\n ef ++;\n }\n}\nn = count;\n// print(JSON.stringify(v));\n\nif (n === 0)\n{\n print(0);\n}\nvar dp = [Array(n+2).fill(0), Array(n+2).fill(0)];\nfor (var i = 0; i < n; i ++)\n{\n var r = v[n-1-i].lastIndexOf('1');\n var l = v[n-1-i].indexOf('1');\n // print(l, r);\n if (i === 0)\n {\n if (n == 1)\n {\n print(r+1 + ef);\n }\n else\n {\n dp[0][i] = (r+1)*2 + 1;\n dp[1][i] = m + 2;\n }\n }\n else if (i == n-1)\n {\n print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)) + ef);\n }\n else\n {\n dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;\n dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;\n }\n // print(JSON.stringify(dp));\n}\n"}], "negative_code": [{"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar m = parseInt(arr[1]);\nvar v = Array(n);\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline();\n var line = arr.substr(1,m);\n // var line = Array(m).fill(0);\n // for (var j = 0; j < m; j ++)\n // {\n // line[j] = arr.charAt(j+1)=='1'?1:0;\n // }\n // v.splice(v, 0, line);\n v[n-i-1] = line;\n}\n// print(JSON.stringify(v));\n\nvar dp = [Array(n+2).fill(0), Array(n+2).fill(0)];\nfor (var i = 0; i < n; i ++)\n{\n var r = v[i].lastIndexOf('1');\n var l = v[i].indexOf('1');\n // print(l, r);\n if (i === 0)\n {\n dp[0][i] = (r+1)*2 + 1;\n dp[1][i] = m + 2;\n }\n else if (i == n-1)\n {\n print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)));\n }\n else\n {\n dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;\n dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;\n }\n // print(JSON.stringify(dp));\n}"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar m = parseInt(arr[1]);\nvar v = Array(n);\nvar count = 0;\nvar ef = 0;\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline();\n var line = arr.substr(1,m);\n // var line = Array(m).fill(0);\n // for (var j = 0; j < m; j ++)\n // {\n // line[j] = arr.charAt(j+1)=='1'?1:0;\n // }\n // v.splice(v, 0, line);\n if (line.indexOf('1') != -1)\n {\n v[count++] = line;\n }\n else if (count !== 0)\n {\n ef ++;\n }\n}\nn = count;\n// print(JSON.stringify(v));\n\nvar dp = [Array(n+2).fill(0), Array(n+2).fill(0)];\nfor (var i = 0; i < n; i ++)\n{\n var r = v[n-1-i].lastIndexOf('1');\n var l = v[n-1-i].indexOf('1');\n // print(l, r);\n if (i === 0)\n {\n dp[0][i] = (r+1)*2 + 1;\n dp[1][i] = m + 2;\n }\n else if (i == n-1)\n {\n print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)) + ef);\n }\n else\n {\n dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;\n dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;\n }\n // print(JSON.stringify(dp));\n}"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar m = parseInt(arr[1]);\nvar v = Array(n);\nvar count = 0;\nvar ef = 0;\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline();\n var line = arr.substr(1,m);\n // var line = Array(m).fill(0);\n // for (var j = 0; j < m; j ++)\n // {\n // line[j] = arr.charAt(j+1)=='1'?1:0;\n // }\n // v.splice(v, 0, line);\n if (line.indexOf('1') != -1)\n {\n v[count++] = line;\n }\n else if (count !== 0)\n {\n ef ++;\n }\n}\nn = count;\n// print(JSON.stringify(v));\n\nvar dp = [Array(n+2).fill(0), Array(n+2).fill(0)];\nfor (var i = 0; i < n; i ++)\n{\n var r = v[n-1-i].lastIndexOf('1');\n var l = v[n-1-i].indexOf('1');\n // print(l, r);\n if (i === 0)\n {\n if (n == 1)\n {\n print(r+1 + ef);\n }\n else\n {\n dp[0][i] = (r+1)*2 + 1;\n dp[1][i] = m + 2;\n }\n }\n else if (i == n-1)\n {\n print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)) + ef);\n }\n else\n {\n dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;\n dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;\n }\n // print(JSON.stringify(dp));\n}\n"}], "src_uid": "55070f8e5dba8a6ec669a53a169e557d"} {"nl": {"description": "You are given two integers $$$A$$$ and $$$B$$$, calculate the number of pairs $$$(a, b)$$$ such that $$$1 \\le a \\le A$$$, $$$1 \\le b \\le B$$$, and the equation $$$a \\cdot b + a + b = conc(a, b)$$$ is true; $$$conc(a, b)$$$ is the concatenation of $$$a$$$ and $$$b$$$ (for example, $$$conc(12, 23) = 1223$$$, $$$conc(100, 11) = 10011$$$). $$$a$$$ and $$$b$$$ should not contain leading zeroes.", "input_spec": "The first line contains $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. Each test case contains two integers $$$A$$$ and $$$B$$$ $$$(1 \\le A, B \\le 10^9)$$$.", "output_spec": "Print one integer — the number of pairs $$$(a, b)$$$ such that $$$1 \\le a \\le A$$$, $$$1 \\le b \\le B$$$, and the equation $$$a \\cdot b + a + b = conc(a, b)$$$ is true.", "sample_inputs": ["3\n\n1 11\n\n4 2\n\n191 31415926"], "sample_outputs": ["1\n0\n1337"], "notes": "NoteThere is only one suitable pair in the first test case: $$$a = 1$$$, $$$b = 9$$$ ($$$1 + 9 + 1 \\cdot 9 = 19$$$)."}, "positive_code": [{"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n const t = readInt(arr)\n\n for(let i = 0; i < t; i++) {\n const [A, B] = readInts(arr, i)\n // wr(arr[i], A, B)\n\n let st = B.toString()\n let len = st.length\n\n if(Math.pow(10, len) - 1 > B) len --\n\n wr(A * len)\n\n }\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a, i) {\n if(i === undefined) return parseInt(a.shift())\n else return parseInt(a[i])\n}\nfunction readInts(a, i) {\n if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))\n else return arr[i].split(' ').map(a => parseInt(a))\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n var t = parseInt(readline());\n var A, B;\n for (var i = 0; i < t; i++)\n {\n var line = readline().split(' ')\n A = parseInt(line[0]);\n B = parseInt(line[1]);\n console.log(A * (('' + (B + 1)).length - 1));\n }\n\n}"}, {"source_code": "'use strict'\nvar t=Number(readline());\n\nwhile(t--){\n var s=readline().replace(/\\r$/, '').split(' ').map(Number);\n var a=s[0];\n var b=s[1];\n\n var cnt=0,nine=0;\n\n while((nine*10+9)<=b){\n nine*=10;\n nine+=9;\n cnt++;\n }\n var ans=Number(a*cnt);\n print(ans);\n}"}, {"source_code": "var t = parseInt(readline(), 10),\n ab = [], b = 0;\n \nfor(var i=1; i<=t; i++) {\n ab = readline().split(' ').map(el => parseInt(el, 10));\n var a = ab[0];\n var B = ab[1];\n \n if(B < 9) b = 0;\n else if(B < 99) b = 1;\n else if(B < 999) b = 2;\n else if(B < 9999) b = 3;\n else if(B < 99999) b = 4;\n else if(B < 999999) b = 5;\n else if(B < 9999999) b = 6;\n else if(B < 99999999) b = 7;\n else if(B < 999999999) b = 8;\n else b = 9;\n \n print(a*b);\n}"}], "negative_code": [{"source_code": "'use strict'\nvar t=Number(readline());\n\nwhile(t--){\n var s=readline().replace(/\\r$/, '').split(' ').map(Number);\n var a=s[0];\n var b=s[1];\n\n var cnt=0,nine=0;\n\n while((nine*10+9)<=b){\n nine*=10;\n nine+=9;\n cnt++;\n print(\"pp\");\n }\n var ans=Number(a*cnt);\n print(ans);\n}"}], "src_uid": "dc67dd2102c70ea476df642b863ae8d3"} {"nl": {"description": "Asya loves animals very much. Recently, she purchased $$$n$$$ kittens, enumerated them from $$$1$$$ and $$$n$$$ and then put them into the cage. The cage consists of one row of $$$n$$$ cells, enumerated with integers from $$$1$$$ to $$$n$$$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were $$$n - 1$$$ partitions originally. Initially, each cell contained exactly one kitten with some number.Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day $$$i$$$, Asya: Noticed, that the kittens $$$x_i$$$ and $$$y_i$$$, located in neighboring cells want to play together. Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells. Since Asya has never putted partitions back, after $$$n - 1$$$ days the cage contained a single cell, having all kittens.For every day, Asya remembers numbers of kittens $$$x_i$$$ and $$$y_i$$$, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into $$$n$$$ cells.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 150\\,000$$$) — the number of kittens. Each of the following $$$n - 1$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n$$$, $$$x_i \\ne y_i$$$) — indices of kittens, which got together due to the border removal on the corresponding day. It's guaranteed, that the kittens $$$x_i$$$ and $$$y_i$$$ were in the different cells before this day.", "output_spec": "For every cell from $$$1$$$ to $$$n$$$ print a single integer — the index of the kitten from $$$1$$$ to $$$n$$$, who was originally in it. All printed integers must be distinct. It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.", "sample_inputs": ["5\n1 4\n2 5\n3 1\n4 5"], "sample_outputs": ["3 1 4 2 5"], "notes": "NoteThe answer for the example contains one of several possible initial arrangements of the kittens.The picture below shows how the cells were united for this initial arrangement. Note, that the kittens who wanted to play together on each day were indeed in adjacent cells. "}, "positive_code": [{"source_code": "var nums = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = nums[0];\nvar rank = Array(n).fill(0);\nvar ppp = Array(n).fill(0);\nvar vectors = Array(n).fill([]);\nfor (var i=0; i\n #'hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0'\n #'a,5,A,0,a,0,A,0,a,0,A,0'\n 'A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0'\n\nprint = console.log\n */\n\n(function() {\n var depthstack, el, i, j, layers, len, line, name, numbers, text;\n\n line = readline().split(',');\n\n text = line.filter(function(x, i) {\n return i % 2 === 0;\n });\n\n numbers = line.filter(function(x, i) {\n return i % 2 === 1;\n }).map(Number);\n\n layers = [];\n\n depthstack = [Infinity];\n\n for (i = j = 0, len = text.length; j < len; i = ++j) {\n el = text[i];\n if (layers[name = depthstack.length - 1] == null) {\n layers[name] = [];\n }\n layers[depthstack.length - 1].push(text[i]);\n depthstack[depthstack.length - 1] -= 1;\n depthstack.push(numbers[i]);\n while (depthstack[depthstack.length - 1] === 0) {\n depthstack.pop();\n }\n }\n\n print(layers.length);\n\n print(layers.map(function(x) {\n return x.join(' ');\n }).join('\\n'));\n\n}).call(this);\n"}, {"source_code": "\"use strict\";\n\nvar atLevel = {};\n\nfunction addForLevel (text, level) {\n if (!(level in atLevel)) {\n atLevel[level] = []; \n }\n atLevel[level].push(text);\n}\n\nfunction parseComment (tokens, pos, level) {\n var text = tokens[pos++];\n var kids = parseInt(tokens[pos++]);\n addForLevel (text, level);\n var positions = [kids];\n while (true) {\n while (positions.length > 0 && positions[positions.length - 1] === 0)\n positions.pop();\n if (positions.length === 0)\n break; \n text = tokens[pos++];\n kids = parseInt(tokens[pos++]);\n positions[positions.length - 1]--;\n addForLevel (text, positions.length);\n positions.push(kids)\n }\n return pos;\n}\n\nfunction parseAll (s) {\n var tokens = s.split(',');\n var pos = 0;\n while (pos < tokens.length) \n pos = parseComment(tokens, pos, 0);\n}\n\nvar s = readline();\nparseAll(s);\nvar level = 0;\nwhile (level in atLevel) \n level++;\nprint(level);\nfor (var i = 0; i < level; i++)\n print(atLevel[i].join(' '));\n "}], "negative_code": [], "src_uid": "da08dd34ac3c05af58926f70abe5acd0"} {"nl": {"description": "Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase \"how are you\" he can type \"hhoow aaaare yyoouu\". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. ", "input_spec": "The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. ", "output_spec": "Print the given string after it is processed. It is guaranteed that the result will contain at least one character.", "sample_inputs": ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"], "sample_outputs": ["wre", "rezy", "a"], "notes": null}, "positive_code": [{"source_code": "const {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n let L = ipt.split(EOL).slice(0, -1)[0]\n let l = []\n for (let i = 0; i < L.length; i++) {\n while (L[i] == l[l.length - 1]) {\n i++\n l.pop()\n }\n l.push(L[i])\n }\n console.log(l.join(''))\n})"}, {"source_code": "readline = require('readline')\nlet stdinInput = '';\n\nfunction IO_IN_FILE(){\n //file\n var fs = require('fs');\n const inputfile = '_in.txt';\n const outputfile = '_out.txt';\n fs.writeFileSync(outputfile, '');\n var myInterface = readline.createInterface({\n input: fs.createReadStream(inputfile),\n });\n myInterface.on('line', function (line) {\n stdinInput += line+'\\n';\n }).on('close', () => {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input;});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n\n // let l = []\n // let len = s.length;\n // for (let i = 0; i < len; i++) {\n // while (s[i] == l[l.length - 1]) {\n // i++\n // l.pop()\n // }\n // l.push(s[i])\n // }\n // console.log(l.join(''))\n\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n a.pop();\n n--;\n }else{\n a.push(s[i]);\n n++;\n }\n }else{\n a.push(s[i]);\n n++;\n }\n }\n // console.log(a.join(''))\n // for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input;});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n\n // let l = []\n // let len = s.length;\n // for (let i = 0; i < len; i++) {\n // while (s[i] == l[l.length - 1]) {\n // i++\n // l.pop()\n // }\n // l.push(s[i])\n // }\n // console.log(l.join(''))\n\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n a.pop();\n n--;\n }else{\n a.push(s[i]);\n n++;\n }\n }else{\n a.push(s[i]);\n n++;\n }\n }\n console.log(a.join(''))\n // for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input;});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n\n let l = []\n let len = s.length;\n for (let i = 0; i < len; i++) {\n while (s[i] == l[l.length - 1]) {\n i++\n l.pop()\n }\n l.push(s[i])\n }\n console.log(l.join(''))\n\n // let len = s.length;\n // let a = [], n;\n // n=0;\n // for(let i=0; i0){\n // if(s[i]==a[n-1]){\n // n--;\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }\n \n // for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input;});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n\n let l = []\n for (let i = 0; i < s.length; i++) {\n while (s[i] == l[l.length - 1]) {\n i++\n l.pop()\n }\n l.push(s[i])\n }\n console.log(l.join(''))\n\n // let len = s.length;\n // let a = [], n;\n // n=0;\n // for(let i=0; i0){\n // if(s[i]==a[n-1]){\n // n--;\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }\n \n // for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input;});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n\n // let l = []\n // let len = s.length;\n // for (let i = 0; i < len; i++) {\n // while (s[i] == l[l.length - 1]) {\n // i++\n // l.pop()\n // }\n // l.push(s[i])\n // }\n // console.log(l.join(''))\n\n\n let len = s.length;\n let a = [], n;\n n=0;\nfor(let i=0; i0){\n if(s[i]==a[n-1]){\n a.pop();\n n--;\n }else{\n a.push(s[i]);\n n++;\n }\n }else{\n a.push(s[i]);\n n++;\n }\n}\n// console.log(a.join(''))\n// for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i ipt += s)\nprocess.stdin.on('end', () => {\n let L = ipt.split(EOL).slice(0, -1)[0]\n let l\n do {\n l = L\n L = L.replace(/(\\w)\\1+/g, '')\n } while (l != L)\n console.log(L)\n})"}, {"source_code": "readline = require('readline')\nlet stdinInput = '';\n\nfunction IO_IN_FILE(){\n //file\n var fs = require('fs');\n const inputfile = '_in.txt';\n const outputfile = '_out.txt';\n fs.writeFileSync(outputfile, '');\n var myInterface = readline.createInterface({\n input: fs.createReadStream(inputfile),\n });\n myInterface.on('line', function (line) {\n stdinInput += line+'\\n';\n }).on('close', () => {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input;});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n console.log(a);\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n \n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n console.log(this.lines);\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n console.log(s);\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n console.log(a);\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n \n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s1, s2;\nfunction main() {\n const is = new Scanner();\n \n while((s1 = is.nextLine())!==false){\n solve(s1);\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n// var readline = require('readline');\n\n// const myInterface = readline.createInterface({\n// input: process.stdin,\n// output: process.stdout\n// });\n\n// // var fs = require('fs');\n// // fs.writeFileSync('_out.txt', '');\n// // var myInterface = readline.createInterface({\n// // input: fs.createReadStream('_in.txt'),\n// // });\n\n\n// myInterface.on('line', function (line) {\n// solve(line);\n \n// }).on('close', () => {\n// process.exit(0);\n// })\n\nfunction solve(s){\n // let a = [300000];\n // let n=0;\n let len = s.length;\n // for(let i=0; i0){\n // if(s[i]==a[n-1]){\n // n--;\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }\n // // console.log(n);\n // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s1, s2;\nfunction main() {\n const is = new Scanner();\n \n while((s1 = is.nextLine())!==false){\n solve(s1);\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n// var readline = require('readline');\n\n// const myInterface = readline.createInterface({\n// input: process.stdin,\n// output: process.stdout\n// });\n\n// // var fs = require('fs');\n// // fs.writeFileSync('_out.txt', '');\n// // var myInterface = readline.createInterface({\n// // input: fs.createReadStream('_in.txt'),\n// // });\n\n\n// myInterface.on('line', function (line) {\n// solve(line);\n \n// }).on('close', () => {\n// process.exit(0);\n// })\n\nfunction solve(s1){\n // let a = [300000];\n // let n=0;\n let len = s1.length;\n // for(let i=0; i0){\n // if(s[i]==a[n-1]){\n // n--;\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }\n // // console.log(n);\n // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n console.log(a);\n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n // console.log(n);\n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n console.log(a);\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n \n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; console.log(input)});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n console.log(this.lines);\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n console.log(s);\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n console.log(a);\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n \n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input;});\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n\n // let l = []\n // let len = s.length;\n // for (let i = 0; i < len; i++) {\n // while (s[i] == l[l.length - 1]) {\n // i++\n // l.pop()\n // }\n // l.push(s[i])\n // }\n // console.log(l.join(''))\n\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n \n // for(let i=0; i0){\n// if(s[i]==a[n-1]){\n// a.pop();\n// n--;\n// }else{\n// a.push(s[i]);\n// n++;\n// }\n// }else{\n// a.push(s[i]);\n// n++;\n// }\n// }\n// // console.log(a.join(''))\n// // for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n console.log(n);\n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s1, s2;\nfunction main() {\n const is = new Scanner();\n \n while((s1 = is.nextLine())!==false){\n solve(s1);\n }\n}\n\n\n\n\n\n\n\n\n// var readline = require('readline');\n\n// const myInterface = readline.createInterface({\n// input: process.stdin,\n// output: process.stdout\n// });\n\n// // var fs = require('fs');\n// // fs.writeFileSync('_out.txt', '');\n// // var myInterface = readline.createInterface({\n// // input: fs.createReadStream('_in.txt'),\n// // });\n\n\n// myInterface.on('line', function (line) {\n// solve(line);\n \n// }).on('close', () => {\n// process.exit(0);\n// })\n\nfunction solve(s){\n // let a = [300000];\n // let n=0;\n let len = s.length;\n // for(let i=0; i0){\n // if(s[i]==a[n-1]){\n // n--;\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }else{\n // a[n] = s[i];\n // n++;\n // }\n // }\n // // console.log(n);\n // for(let i=0; i {\n main(); \n process.exit(0);\n })\n\n process.stdout.write = function(data1){\n fs.appendFileSync(outputfile, data1, 'utf8');\n }\n}\n\nfunction IO_STD(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('readable', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n if(this.index >= this.lines.length-1)\n return false;\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n let checkarr = this.nextLine();\n if(checkarr===false)\n return false;\n const array = checkarr.split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// IO_IN_FILE();\nIO_STD();\n\n\nlet ntest, s;\nfunction main() {\n const is = new Scanner();\n \n while((s = is.nextLine())!==false){\n console.log(s);\n let len = s.length;\n let a = [], n;\n n=0;\n for(let i=0; i0){\n if(s[i]==a[n-1]){\n n--;\n }else{\n a[n] = s[i];\n n++;\n console.log(a);\n }\n }else{\n a[n] = s[i];\n n++;\n }\n }\n \n for(let i=0; i {\n// process.exit(0);\n// })\n\n// function solve(s){\n// // let a = [300000];\n// // let n=0;\n// let len = s.length;\n// // for(let i=0; i0){\n// // if(s[i]==a[n-1]){\n// // n--;\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }else{\n// // a[n] = s[i];\n// // n++;\n// // }\n// // }\n// // // console.log(n);\n// // for(let i=0; i {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const n = Number(readline())\n const a = readline().split(' ').map(Number)\n \n helper(n, a)\n}\n\nfunction helper(n, a) {\n let clone = [...a]\n clone.sort((a1, a2) => a2 - a1)\n let map = new Map()\n\n for (let i = 0; i < n; i++) {\n if (!map.has(clone[i])) {\n map.set(clone[i], i + 1)\n }\n }\n\n let result = ''\n for (let i = 0; i < n; i++) {\n result += map.get(a[i]) + ' '\n }\n\n console.log(result.substring(0, result.length))\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction printResult(x) {\n process.stdout.write(x);\n}\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n const arr = readLine().split(' ').map((item, i, a) => new List(parseInt(item, 10), i));\n\n const result = gukiZAndContest(n, arr);\n printResult(result);\n}\n\nfunction List(value, pos) {\n this.value = value;\n this.pos = pos;\n}\n\nfunction compare(a, b) {\n if (a.value < b.value) return 1;\n if (a.value > b.value) return -1;\n return 0;\n}\n\nconst gukiZAndContest = (n, a) => {\n a.sort(compare);\n\n const result = new Array(n);\n let ranking = 1;\n result[a[0].pos] = ranking;\n for (let i = 0; i < n - 1; i++) {\n if (a[i].value > a[i + 1].value) ranking = i + 2;\n result[a[i + 1].pos] = ranking;\n }\n\n return result.join(' ');\n};"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n const ans = [];\n\n for (let i = 0; i < arr.length; i++) {\n let counter = 1;\n for (let j = 0; j < arr.length; j++) {\n if (arr[i] < arr[j]) {\n counter++;\n }\n }\n ans.push(counter);\n }\n\n console.log(ans.join(' '));\n c++;\n});\n"}, {"source_code": "var n = +readline(), a = readline().split(\" \"), s = a.concat(), places = [];\ns.sort(function(a,b){return b-a});\n\nfor(i = 0, p = 1; i < n ; i++){\n\tplaces[a.indexOf(s[i])] = p;\n\tif( (i != n-1) && (s[i] != s[i+1]) ){\n\t\tp = i+2;\n\t}\n\tdelete a[a.indexOf(s[i])];\n}\nwrite(places.join(\" \"));"}, {"source_code": "function main(n,arr){\n\n\n var ansstr = \"\";\n\n for(var i = 0 ; i < n ; i++){\n var ans = 1;\n for(var j = 0 ; j < n ; j++){\n if(arr[i] this.arr[ i ] ) {\n \t\t\tcn++ ;\n \t\t}\n \t}\n \tthis.brr.push( cn ) ;\n }\n res = '' ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( i > 0 ) {\n \t\tres += ' ' ;\n \t}\n \tres += this.brr[ i ] ;\n }\n print( res ) ;\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n this.arr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n this.arr.push( irObj.nextInt() ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.arr = new Array();\n this.adjList = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 );\n this.adjList.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adjList = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adjList.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "function toi(x){return parseInt(x);}\n(function(){\n var n=+readline();\n var a=readline().split(\" \").map(toi);\n var res=a.map(function(x){ return 1+a.filter(function(y){return y>x;}).length});\n print(res.join(\" \"));\n})();\n"}, {"source_code": "function main(){\n\tvar n = nextInt();\n\tvar a = new Array(n);\n\tvar ans = new Array(n);\n\tvar i;\n\tfor(i =0; i str[i]) {\n\t\t\tcount++;\n\t\t};\n\t};\n\n\tarr.push(count + 1);\n};\n\nprint(arr.join(' '));"}], "negative_code": [], "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 ​​of for all i from 1 to n. The expression ⌊ x⌋ 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 = 46, 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 ≤ n ≤ 105, 0 ≤ k ≤ 107) — 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 ≤ ai ≤ 100), 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 — 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 +  lfloor frac{100}{10} rfloor = 10 + 10 =  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": "/******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n\n\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(1);\n\tvar List = __webpack_require__(2);\n\tvar _a = List.map(parseInt, readline().split(' ')), n = _a[0], k = _a[1];\n\tvar a = List.map(parseInt, readline().split(' '));\n\tvar count = List.replicate(101, 0);\n\tfor (var i = 0; i < a.length; i++) {\n\t count[a[i]]++;\n\t}\n\tfunction enhance(ten, digit, delta) {\n\t var skills = count[ten + digit];\n\t if (skills == 0 || k < delta)\n\t return;\n\t var points = Math.floor(k / delta);\n\t var chosen = Prelude_1.min(skills, points);\n\t count[ten + digit] -= chosen;\n\t count[ten + 10] += chosen;\n\t k -= chosen * delta;\n\t}\n\tfor (var digit = 9; digit > 0; digit--) {\n\t var delta = 10 - digit;\n\t for (var x = 0; x <= 90 && k >= delta; x += 10) {\n\t enhance(x, digit, delta);\n\t }\n\t}\n\tfor (var x = 0; x <= 90; x += 10) {\n\t enhance(x, 0, 10);\n\t}\n\tvar result = 0;\n\tfor (var x = 0; x <= 100; x++) {\n\t result += count[x] * Math.floor(x / 10);\n\t}\n\tprint(result);\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction min(a, b) {\n\t return a < b ? a : b;\n\t}\n\texports.min = min;\n\tfunction max(a, b) {\n\t return a < b ? b : a;\n\t}\n\texports.max = max;\n\tfunction curry(f) {\n\t return function (x) { return function (y) { return f(x, y); }; };\n\t}\n\texports.curry = curry;\n\tfunction uncurry(f) {\n\t return function (x, y) { return f(x)(y); };\n\t}\n\texports.uncurry = uncurry;\n\tfunction id(x) {\n\t return x;\n\t}\n\texports.id = id;\n\tfunction constant(x) {\n\t return function (_) { return x; };\n\t}\n\texports.constant = constant;\n\tfunction flip(f) {\n\t return function (y) { return function (x) { return f(x)(y); }; };\n\t}\n\texports.flip = flip;\n\tfunction flip2(f) {\n\t return function (y, x) { return f(x, y); };\n\t}\n\texports.flip2 = flip2;\n\tfunction compose(g, f) {\n\t return function (x) { return g(f(x)); };\n\t}\n\texports.compose = compose;\n\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(1);\n\tfunction add(xs, ys) {\n\t return xs.concat(ys);\n\t}\n\texports.add = add;\n\tfunction head(xs) {\n\t return xs[0];\n\t}\n\texports.head = head;\n\tfunction last(xs) {\n\t return xs[xs.length - 1];\n\t}\n\texports.last = last;\n\tfunction tail(xs) {\n\t return xs.slice(1);\n\t}\n\texports.tail = tail;\n\tfunction init(xs) {\n\t return xs.slice(0, xs.length - 1);\n\t}\n\texports.init = init;\n\tfunction map(f, xs) {\n\t var result = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t result[i] = f(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.map = map;\n\tfunction reverse(xs) {\n\t return xs.slice().reverse();\n\t}\n\texports.reverse = reverse;\n\tfunction intersperse(x, xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = new Array(xs.length + xs.length - 1);\n\t for (var i = 0; i + 1 < xs.length; i++) {\n\t result[i + i] = xs[i];\n\t result[i + i + 1] = x;\n\t }\n\t result[result.length - 1] = xs[xs.length - 1];\n\t return result;\n\t}\n\texports.intersperse = intersperse;\n\tfunction intercalate(xs, xss) {\n\t return concat(intersperse(xs, xss));\n\t}\n\texports.intercalate = intercalate;\n\tfunction foldl(f, initial, xs) {\n\t var result = initial;\n\t for (var i = 0; i < xs.length; i++) {\n\t result = f(result, xs[i]);\n\t }\n\t return result;\n\t}\n\texports.foldl = foldl;\n\tfunction foldr(f, initial, xs) {\n\t var result = initial;\n\t for (var i = xs.length - 1; i >= 0; i--) {\n\t result = f(xs[i], result);\n\t }\n\t return result;\n\t}\n\texports.foldr = foldr;\n\tfunction concat(xss) {\n\t var total = sum(map(function (xs) { return xs.length; }, xss));\n\t var result = new Array(total);\n\t var m = 0;\n\t for (var i = 0; i < xss.length; i++) {\n\t var xs = xss[i];\n\t for (var j = 0; j < xs.length; j++) {\n\t result[m++] = xs[j];\n\t }\n\t }\n\t return result;\n\t}\n\texports.concat = concat;\n\tfunction sum(xs) {\n\t var result = 0;\n\t for (var i = 0; i < xs.length; i++) {\n\t result += xs[i];\n\t }\n\t return result;\n\t}\n\texports.sum = sum;\n\tfunction product(xs) {\n\t var result = 1;\n\t for (var i = 0; i < xs.length; i++) {\n\t result *= xs[i];\n\t }\n\t return result;\n\t}\n\texports.product = product;\n\tfunction maximum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result < xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.maximum = maximum;\n\tfunction minimum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result > xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.minimum = minimum;\n\tfunction replicate(n, x) {\n\t var result = new Array(n);\n\t for (var i = 0; i < result.length; i++) {\n\t result[i] = x;\n\t }\n\t return result;\n\t}\n\texports.replicate = replicate;\n\tfunction take(n, xs) {\n\t return xs.slice(0, n);\n\t}\n\texports.take = take;\n\tfunction drop(n, xs) {\n\t return xs.slice(n);\n\t}\n\texports.drop = drop;\n\tfunction splitAt(n, xs) {\n\t return [take(n, xs), drop(n, xs)];\n\t}\n\texports.splitAt = splitAt;\n\tfunction takeWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(0, i);\n\t }\n\t }\n\t return xs.slice();\n\t}\n\texports.takeWhile = takeWhile;\n\tfunction dropWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(i);\n\t }\n\t }\n\t return [];\n\t}\n\texports.dropWhile = dropWhile;\n\tfunction group(xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = [];\n\t var last = [xs[0]];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (last[0] === xs[i]) {\n\t last.push(xs[i]);\n\t }\n\t else {\n\t result.push(last);\n\t last = [xs[i]];\n\t }\n\t }\n\t result.push(last);\n\t return result;\n\t}\n\texports.group = group;\n\tfunction filter(f, xs) {\n\t var result = [];\n\t for (var i = 0; i < xs.length; i++) {\n\t if (f(xs[i]))\n\t result.push(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.filter = filter;\n\tfunction zip(xs, ys) {\n\t var n = Prelude_1.min(xs.length, ys.length);\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = [xs[i], ys[i]];\n\t }\n\t return result;\n\t}\n\texports.zip = zip;\n\tfunction unzip(xs) {\n\t var r1 = new Array(xs.length);\n\t var r2 = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t r1[i] = xs[i][0];\n\t r2[i] = xs[i][1];\n\t }\n\t return [r1, r2];\n\t}\n\texports.unzip = unzip;\n\n\n/***/ }\n/******/ ]);"}, {"source_code": "function quickSort(low, high) {\n var i = low; \n var j = high;\n var middle = data_help[ Math.round(( low + high ) / 2) ]; // middle - опорный элемент; в нашей реализации он находится посередине между low и high\n \n do {\n while(data_help[i] > middle)\n {\n ++i; // ищем элементы для правой части\n } \n while(data_help[j] < middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n\n\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data[i]=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i= (10 - b[i].mod) ) {\n\t\tvar add = Math.min((10 - b[i].mod)%10, k);\n\t\t//write(\"add = \" + add + \"\\n\");\n\t\ta[b[i].i] += add;\n\t\tk -= add;\n\t}\n}\n\na.sort();\nfor (var i = 0; i < n; i++) {\n\tif (a[i] < 100 && k > 0) {\n\t\tvar add = Math.min(100 - a[i],k);\n\t\ta[i] += add;\n\t\tk -= add;\n\t}\n}\n\nanswer = 0;\nfor (var i = 0; i < n; i++) {\n\tanswer += Math.floor(a[i]/10);\n}\n\nwrite(answer);\n\n\n//write(\"b[i].mod = \" + b[i].mod + \"\\n\");\n\n"}], "negative_code": [{"source_code": "function quickSort(low, high) {\n var i = low; \n var j = high;\n var middle = data_help[ Math.round(( low + high ) / 2) ]; // middle - опорный элемент; в нашей реализации он находится посередине между low и high\n \n do {\n while(data_help[i] < middle)\n {\n ++i; // ищем элементы для правой части\n } \n while(data_help[j] > middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(data_help, low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort( i, high);\n } \n }\nvar input=readline().split(' ');\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i0){\n for(i=0;i=100){\n sum+=Math.round(data[i]/10);\n data.splice(i,1);\n n--;\n i--;\n continue;\n }\n var help=Math.round((1-data_help[i])*10);\n if(k>=help){\n data[i]=data[i]+help;\n k=k-help;\n }\n else {\n k=0;\n break;\n }\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=Math.round(data[i]/10);\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n ++i; // ищем элементы для правой части\n } \n while(data_help[j] < middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n\n\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=10;\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=10;\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=10;\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(data_help, low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort( i, high);\n } \n }\nvar input=readline().split(' ');\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\nvar data=[];\nvar data_help=[];\nfor(i=0;i0){\n for(i=0;i=100){\n data.splice(i,1);\n n--;\n i--;\n continue;\n }\n var help=Math.round((1-data_help[i])*10);\n if(k>=help){\n data[i]=data[i]+help;\n k=k-help;\n }\n else {\n k=0;\n break;\n }\n }\n}\nvar sum=0;\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(data_help, low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort( i, high);\n } \n }\nvar input=readline().split(' ');\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\nvar data=[];\nvar data_help=[];\ndata.length=n;\nfor(i=0;i0){\n for(i=0;i=100){\n data.splice(i,1);\n n--;\n i--;\n continue;\n }\n var help=Math.round((1-data_help[i])*10);\n if(k>=help){\n data[i]=data[i]+help;\n k=k-help;\n }\n else {\n k=0;\n break;\n }\n }\n}\nvar sum=0;\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(data_help, low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort( i, high);\n } \n }\nvar input=readline().split(' ');\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\nvar data=[];\nvar data_help=[];\ndata.length=n;\ndata_help.length=n;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n k=k-help;\n }\n else \n break;\n}\nvar sum=0;\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=Math.floor(data[i]/10);\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=10;\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=10;\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(data_help, low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort( i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\nvar input=readline().split(' ');\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]==100){\n sum+=Math.round(data[i]/10);\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data[i]=data[i]+help;\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(data_help, low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort( i, high);\n } \n }\nvar input=readline().split(' ');\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=100){\n sum+=Math.round(data[i]/10);\n data.splice(i,1);\n n--;\n i--;\n continue;\n }\n var help=Math.round((1-data_help[i])*10);\n if(k>=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data[i]=data[i]+help;\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=10;\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort(i, high);\n } \n }\n//40 108\n//20 100 99 50 8 78 44 67 91 75 93 53 96 81 96 86 81 0 58 9 51 63 70 73 80 79 28 82 4 15 60 74 19 17 54 81 11 67 71 66\n\nvar input=readline().split(' ');\n//var input=['40','108'];\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\n//input=['20','100' ,'99' ,'50' ,'8','78' ,'44' ,'67' ,'91', '75', '93', '53', '96' ,'81', '96', '86', '81', '0', '58', '9', '51', '63', '70', '73', '80', '79', '28', '82', '4', '15' ,'60' ,'74', '19', '17', '54', '81' ,'11', '67', '71', '66'];\nvar data=[];\nvar data_help=[];\nvar sum=0;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n data_help[i]=0;\n k=k-help;\n if(data[i]>=100){\n sum+=Math.floor(data[i]/10);\n data.splice(i,1);\n data_help.splice(i,1);\n n--;\n i--;\n }\n }\n else {\n break;\n }\n}\nfor(i=0;i=help){\n data=(data[i]+help);\n k=k-help;\n }\n else {\n data[i]+=k;\n break;\n }\n}\nfor(i=0;i middle)\n {\n --j; // ищем элементы для левой части\n }\n if(i <= j){ \n // перебрасываем элементы\n var temp = data_help[i];\n data_help[i] = data_help[j];\n data_help[j] = temp;\n\n var temp2=data[i];\n data[i]=data[j];\n data[j]=temp2;\n // следующая итерация\n i++; j--;\n }\n } \n while(i < j);\n \n if(low < j){\n // рекурсивно вызываем сортировку для левой части\n quickSort(data_help, low, j);\n } \n\n if(i < high){\n // рекурсивно вызываем сортировку для правой части\n quickSort( i, high);\n } \n }\nvar input=readline().split(' ');\nvar n=parseInt(input[0]);\nvar k=parseInt(input[1]);\ninput=readline().split(' ');\nvar data=[];\nvar data_help=[];\ndata.length=n;\ndata_help.length=n;\nfor(i=0;i=help){\n data[i]=data[i]+help;\n k=k-help;\n }\n else {\n k=0;\n break;\n }\n}\n}\nvar sum=0;\nfor(i=0;i= (10 - b[i].mod) ) {\n\t\tvar add = Math.min(10-b[i].mod, k);\n\t\ta[b[i].i] += add;\n\t\tk -= add;\n\t}\n}\n\na.sort();\nfor (var i = 0; i < n; i++) {\n\tif (a[i] < 100 && k > 0) {\n\t\tvar add = Math.min(100 - a[i],k);\n\t\ta[i] += add;\n\t\tk -= add;\n\t}\n}\n\nanswer = 0;\nfor (var i = 0; i < n; i++) {\n\tanswer += Math.floor(a[i]/10);\n}\n\nwrite(answer);\n\n\n//write(\"b[i].mod = \" + b[i].mod + \"\\n\");\n\n"}], "src_uid": "b4341e1b0ec0b7341fdbe6edfe81a0d4"} {"nl": {"description": "$$$2^k$$$ teams participate in a playoff tournament. The tournament consists of $$$2^k - 1$$$ games. They are held as follows: first of all, the teams are split into pairs: team $$$1$$$ plays against team $$$2$$$, team $$$3$$$ plays against team $$$4$$$ (exactly in this order), and so on (so, $$$2^{k-1}$$$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $$$2^{k-1}$$$ teams remain. If only one team remains, it is declared the champion; otherwise, $$$2^{k-2}$$$ games are played: in the first one of them, the winner of the game \"$$$1$$$ vs $$$2$$$\" plays against the winner of the game \"$$$3$$$ vs $$$4$$$\", then the winner of the game \"$$$5$$$ vs $$$6$$$\" plays against the winner of the game \"$$$7$$$ vs $$$8$$$\", and so on. This process repeats until only one team remains.For example, this picture describes the chronological order of games with $$$k = 3$$$: Let the string $$$s$$$ consisting of $$$2^k - 1$$$ characters describe the results of the games in chronological order as follows: if $$$s_i$$$ is 0, then the team with lower index wins the $$$i$$$-th game; if $$$s_i$$$ is 1, then the team with greater index wins the $$$i$$$-th game; if $$$s_i$$$ is ?, then the result of the $$$i$$$-th game is unknown (any team could win this game). Let $$$f(s)$$$ be the number of possible winners of the tournament described by the string $$$s$$$. A team $$$i$$$ is a possible winner of the tournament if it is possible to replace every ? with either 1 or 0 in such a way that team $$$i$$$ is the champion.You are given the initial state of the string $$$s$$$. You have to process $$$q$$$ queries of the following form: $$$p$$$ $$$c$$$ — replace $$$s_p$$$ with character $$$c$$$, and print $$$f(s)$$$ as the result of the query. ", "input_spec": "The first line contains one integer $$$k$$$ ($$$1 \\le k \\le 18$$$). The second line contains a string consisting of $$$2^k - 1$$$ characters — the initial state of the string $$$s$$$. Each character is either ?, 0, or 1. The third line contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, the $$$i$$$-th line contains an integer $$$p$$$ and a character $$$c$$$ ($$$1 \\le p \\le 2^k - 1$$$; $$$c$$$ is either ?, 0, or 1), describing the $$$i$$$-th query.", "output_spec": "For each query, print one integer — $$$f(s)$$$.", "sample_inputs": ["3\n0110?11\n6\n5 1\n6 ?\n7 ?\n1 ?\n5 ?\n1 1"], "sample_outputs": ["1\n2\n3\n3\n5\n4"], "notes": null}, "positive_code": [{"source_code": "\r\nconst memo = [];\r\n\r\n\r\nconst trace = (arr, index) => {\r\n\tif (index >= arr.length) {\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tif (memo[index] !== undefined) {\r\n\t\treturn memo[index];\r\n\t}\r\n\r\n\tif (arr[index] === '1') {\r\n\t\tconst res = trace(arr, index*2+1);\r\n\t\tmemo[index] = res;\r\n\t\treturn res;\r\n\t}\r\n\r\n\tif (arr[index] === '0') {\r\n\t\tconst res = trace(arr, index*2+2);\r\n\t\tmemo[index] = res;\r\n\t\treturn res;\r\n\t}\r\n\r\n\tconst res = trace(arr, index*2+1) +\r\n\t\ttrace(arr, index*2+2);\r\n\r\n\tmemo[index] = res;\r\n\treturn res;\r\n}\r\n\r\nconst traceTop = (index) => {\r\n\tif (index < 0)\r\n\t\treturn;\r\n\r\n\tmemo[index] = undefined;\r\n\r\n\tif (index%2 === 0) {\r\n\t\treturn traceTop((index - 2)/2);\r\n\t}\r\n\r\n\treturn traceTop((index-1)/2);\r\n}\r\n\r\nlet input = '';\r\nprocess.stdin.on('data', str => input += str)\r\nprocess.stdin.on('end', () => {\r\n\tconst [, s, qCount, ...queries] = input.trim().split('\\n');\r\n\r\n\tconst line = s.trim().split('').reverse();\r\n\r\n\tfor (let i=0; i x.split(' '))\n console.log(solve(str, updates));\n l += n\n }\n});\n\nlet C2TMAP // ch index -> tree index\nlet T2CMAP\nfunction solve(str, updates) {\n const chs = str.split('')\n const nodes = []\n createTree(nodes, chs)\n return updates.map(([i, ch]) => {\n const idx = +i - 1\n chs[idx] = ch\n updateTree(nodes, chs, idx)\n return nodes[0].v\n }).join('\\n')\n}\n\n// 0123 45 6\n// -> 6 45 0123\nfunction createIndexMap(total) {\n T2CMAP = {}\n C2TMAP = {}\n\n let step = 2\n let chIdx = 0\n while (step <= total) {\n const limit = total / step // count of each level\n let treeIdx = limit - 1\n for (let i = 0; i < limit; i++) {\n T2CMAP[treeIdx] = chIdx\n C2TMAP[chIdx] = treeIdx\n chIdx++\n treeIdx++\n }\n step *= 2\n }\n}\n\nfunction createTree(nodes, chs) {\n const total = chs.length + 1\n createIndexMap(total)\n\n let step = total\n let l, r, limit\n while (step >= 1) {\n l = 0\n limit = total / step\n for (let i = 0; i < limit; i++) {\n r = l + step - 1\n const node = {\n l, \n r,\n v: 1,\n i: nodes.length\n }\n nodes[node.i] = node\n\n l = r + 1\n }\n step /= 2\n }\n\n // init v\n for (let i = 0; i < chs.length; i++) {\n const node = nodes[C2TMAP[i]]\n node.v = getMerge(nodes, chs, node)\n }\n}\n\nfunction updateTree(nodes, chs, idx) {\n let node = nodes[C2TMAP[idx]]\n while (1) {\n node.v = getMerge(nodes, chs, node)\n if (node.i === 0) break\n node = nodes[Math.floor((node.i - 1) / 2)]\n }\n}\n\nfunction getMerge(nodes, chs, node) {\n const ch = chs[T2CMAP[node.i]]\n const left = nodes[node.i * 2 + 1]\n const right = nodes[node.i * 2 + 2]\n if (ch === '0') {\n return left.v\n } else if (ch === '1') {\n return right.v\n } else {\n return left.v + right.v\n }\n}\n"}], "negative_code": [{"source_code": "\r\nconst trace = (arr, index) => {\r\n\tif (index > arr.length) {\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tif (arr[index] === '1') {\r\n\t\treturn trace(arr, index*2+1);\r\n\t}\r\n\r\n\tif (arr[index] === '0') {\r\n\t\treturn trace(arr, index*2+2);\r\n\t}\r\n\r\n\treturn trace(arr, index*2+1) +\r\n\t\ttrace(arr, index*2+2);\r\n}\r\n\r\n\r\nconst solve = (str) => {\r\n\tconst reverse = [...str].reverse();\r\n\r\n\treturn trace(reverse, 0);\r\n}\r\n\r\nlet input = '';\r\nprocess.stdin.on('data', str => input += str)\r\nprocess.stdin.on('end', () => {\r\n\tconst [, s, qCount, ...queries] = input.trim().split('\\n');\r\n\r\n\tconst line = s.trim().split('');\r\n\r\n\tfor (let i=0; i {\r\n\tif (index > arr.length) {\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tif (arr[index] === '1') {\r\n\t\treturn trace(arr, index*2+1);\r\n\t}\r\n\r\n\tif (arr[index] === '0') {\r\n\t\treturn trace(arr, index*2+2);\r\n\t}\r\n\r\n\treturn trace(arr, index*2+1) +\r\n\t\ttrace(arr, index*2+2);\r\n}\r\n\r\n\r\nconst solve = (str) => {\r\n\tconst reverse = [...str].reverse();\r\n\r\n\treturn trace(reverse, 0);\r\n}\r\n\r\nlet input = '';\r\nprocess.stdin.on('data', str => input += str)\r\nprocess.stdin.on('end', () => {\r\n\tconst [k, s, qCount, ...queries] = input.trim().split('\\n');\r\n\r\n\tconst line = s.split('');\r\n\r\n\tfor (let i=0; i x.split(' '))\n console.log(solve(str, updates));\n l += n\n }\n});\n \nfunction solve(str, updates) {\n const chs = str.split('')\n return updates.map(([i, ch]) => {\n chs[+i - 1] = ch\n return cal(chs)\n }).join('\\n')\n}\n\nfunction cal(chs) {\n let base = chs.length + 1\n let count = Array(base).fill(1)\n let next = []\n let pos = 0\n while (base > 1) {\n base /= 2\n for (let i = 0; i < base; i++) {\n const ch = chs[pos++]\n if (ch === '0') {\n next.push(count[i])\n } else if (ch === '1') {\n next.push(count[i + 1])\n } else {\n next.push(count[i] + count[i + 1])\n }\n }\n // console.log(next)\n count = next\n next = []\n }\n return count[0]\n}\n"}], "src_uid": "0eee4b8f074e02311329d5728138c7fe"} {"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, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.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 + 1 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 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — 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": "\nvar n = +readline();\nvar a = readline().split(' ').map(function(v){\n\treturn +v;\n});\n\na.sort(function(a,b){ return a===b?0:a>b?1:-1; });\n\nif(n===1){\n\tprint(-1);\n}else{\n\tvar k = {};\n\tfor(var i=1; i 1 ) ans = [];\n }\n \n print( ans.length );\n print( ans.join(' ') );\n }\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar integers = tokenizeIntegers(readline());\n\tvar cardNum = integers[0];\n\tvar cards = tokenizeIntegers(readline());\n\tcards.sort(function(a, b) { return a-b; });\n\n\tif (cardNum == 1) {\n\t\tprint(-1);\n\t}\n\telse if (cardNum == 2) {\n\t\tvar a = cards[0], b = cards[1];\n\t\tif (a == b) {\n\t\t\tprint(1);\n\t\t\tprint(a);\n\t\t}\n\t\telse if ((b-a)%2 == 1) {\n\t\t\tprint(2);\n\t\t\tprint(a-(b-a), b+(b-a));\n\t\t}\n\t\telse {\n\t\t\tprint(3);\n\t\t\tprint(a-(b-a), (a+b)/2, b+(b-a));\n\t\t}\n\t}\n\telse {\n\t\tvar gaps = [];\n\t\tfor (var i = 1; i < cardNum; i += 1) {\n\t\t\tgaps.push(cards[i]-cards[i-1]);\n\t\t}\n\n\t\tgaps.sort(function(a, b) { return a-b; });\n\t\tvar small = gaps[0], big = gaps[gaps.length-1];\n\n\t\tif (small == big) {\n\t\t\tif (small == 0) {\n\t\t\t\tprint(1);\n\t\t\t\tprint(cards[0]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprint(2);\n\t\t\t\tprint(cards[0]-small, cards[cardNum-1]+small);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (gaps[gaps.length-2] != small) {\n\t\t\t\tprint(0);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (2*small != big) {\n\t\t\t\tprint(0);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (var i = 1; i < cardNum; i += 1) {\n\t\t\t\tif (cards[i]-cards[i-1] == big) {\n\t\t\t\t\tprint(1);\n\t\t\t\t\tprint(cards[i-1]+small);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nmain();\n"}], "negative_code": [{"source_code": "\nvar n = +readline();\nvar num = readline().split(' ').map(function(v){\n\treturn +v;\n});\n\nvar _flg=false;\nnum.sort(function(a,b){\n\tif(a==b){\n\t\t_flg=true;\n\t\treturn 0;\n\t}else if(a>b){\n\t\treturn 1;\n\t}else{\n\t\treturn -1;\n\t}\n});\nif(n==1){\n\tprint(-1);\n}else if(_flg){\n\tprint(0);\n}else{\n\nvar arr = [];\nfor(var i=1;ib?1:-1; });\n\nif(n===1){\n\tprint(-1);\n}else{\n\tvar k = {};\n\tfor(var i=1; ib){\n\t\treturn 1;\n\t}else{\n\t\treturn -1;\n\t}\n});\nif(n==1){\n\tprint(-1);\n}else if(_flg>1){\n\tif(num.length==_flg){\n\t\tprint(1);\n\t\tprint(num[0]);\n\t}else{\n\t\tprint(0);\t\n\t}\n}else{\n\nvar arr = [];\nfor(var i=1;i2 ){\n\tprint(0);\n}else if(k.length===2){\n\tif(k[0]*2==k[1]||k[1]*2==k[0]){\n\t\tvar ret=[];\n\t\tvar g = Math.min(+k[0], +k[1]);\n\t\tfor(var i=0;ib){\n\t\treturn 1;\n\t}else{\n\t\treturn -1;\n\t}\n});\nif(n==1){\n\tprint(-1);\n}else if(_flg){\n\tif(num.length==2){\n\t\tprint(1);\n\t\tprint(num[0]);\n\t}else{\n\t\tprint(0);\t\n\t}\n}else{\n\nvar arr = [];\nfor(var i=1;i2 ){\n\tprint(0);\n}else if(k.length===2){\n\tif(k[0]*2==k[1]||k[1]*2==k[0]){\n\t\tvar ret=[];\n\t\tvar g = Math.min(+k[0], +k[1]);\n\t\tfor(var i=0;ib?1:-1; });\n\nif(n===1){\n\tprint(-1);\n}else{\n\tvar k = {};\n\tfor(var i=1; ib){\n\t\treturn 1;\n\t}else{\n\t\treturn -1;\n\t}\n});\nif(n==1){\n\tprint(-1);\n}else if(_flg){\n\tprint(0);\n}else{\n\nvar arr = [];\nfor(var i=1;ib){\n\t\treturn 1;\n\t}else{\n\t\treturn -1;\n\t}\n});\nif(n==1){\n\tprint(-1);\n}else if(_flg){\n\tprint(0);\n}else{\n\nvar arr = [];\nfor(var i=1;i2 ){\n\tprint(0);\n}else if(k.length===2){\n\tif(k[0]*2==k[1]||k[1]*2==k[0]){\n\t\tvar ret=[];\n\t\tvar g = Math.min(+k[0], +k[1]);\n\t\tfor(var i=0;i 1 ) ans = [];\n }\n \n print( ans.length );\n print( ans.join(' ') );\n }\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar integers = tokenizeIntegers(readline());\n\tvar cardNum = integers[0];\n\tvar cards = tokenizeIntegers(readline());\n\tcards.sort(function(a, b) { return a-b; });\n\n\tif (cardNum == 1) {\n\t\tprint(-1);\n\t}\n\telse if (cardNum == 2) {\n\t\tvar a = cards[0], b = cards[1];\n\t\tif (a == b) {\n\t\t\tprint(1);\n\t\t\tprint(a);\n\t\t}\n\t\telse if ((b-a)%2 == 1) {\n\t\t\tprint(2);\n\t\t\tprint(a-(b-a), b+(b-a));\n\t\t}\n\t\telse {\n\t\t\tprint(3);\n\t\t\tprint(a-(b-a), (a+b)/2, b+(b-a));\n\t\t}\n\t}\n\telse {\n\t\tvar gaps = [];\n\t\tfor (var i = 1; i < cardNum; i += 1) {\n\t\t\tgaps.push(cards[i]-cards[i-1]);\n\t\t}\n\n\t\tgaps.sort(function(a, b) { return a-b; });\n\t\tvar small = gaps[0], big = gaps[gaps.length-1];\n\n\t\tif (small == big) {\n\t\t\tif (small == 0) {\n\t\t\t\tprint(1);\n\t\t\t\tprint(cards[0]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprint(2);\n\t\t\t\tprint(cards[0]-small, cards[cardNum-1]+small);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (gaps[gaps.length-2] != small) {\n\t\t\t\tprint(0);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (var i = 1; i < cardNum; i += 1) {\n\t\t\t\tif (cards[i]-cards[i-1] == big) {\n\t\t\t\t\tprint(1);\n\t\t\t\t\tprint(cards[i-1]+small);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar integers = tokenizeIntegers(readline());\n\tvar cardNum = integers[0];\n\tvar cards = tokenizeIntegers(readline());\n\tcards.sort(function(a, b) { return a-b; });\n\n\tif (cardNum == 1) {\n\t\tprint(-1);\n\t}\n\telse if (cardNum == 2) {\n\t\tvar a = cards[0], b = cards[1];\n\t\tif (a == b) {\n\t\t\tprint(1);\n\t\t\tprint(a);\n\t\t}\n\t\telse if ((b-a)%2 == 1) {\n\t\t\tprint(2);\n\t\t\tprint(a-(b-a), b+(b-a));\n\t\t}\n\t\telse {\n\t\t\tprint(3);\n\t\t\tprint(a-(b-a), (a+b)/2, b+(b-a));\n\t\t}\n\t}\n\telse {\n\t\tvar gaps = [];\n\t\tfor (var i = 1; i < cardNum; i += 1) {\n\t\t\tgaps.push(cards[i]-cards[i-1]);\n\t\t}\n\n\t\tgaps.sort(function(a, b) { return a-b; });\n\t\tvar small = gaps[0], big = gaps[gaps.length-1];\n\n\t\tif (small == big) {\n\t\t\tif (small == 0) {\n\t\t\t\tprint(1);\n\t\t\t\tprint(cards[0]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprint(2);\n\t\t\t\tprint(cards[0]-small, cards[cardNum-1]+small);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (gaps[gaps.length-2] != small) {\n\t\t\t\tprint(0);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (2*small != big) {\n\t\t\t\tprint(0);\n\t\t\t}\n\t\t\tfor (var i = 1; i < cardNum; i += 1) {\n\t\t\t\tif (cards[i]-cards[i-1] == big) {\n\t\t\t\t\tprint(1);\n\t\t\t\t\tprint(cards[i-1]+small);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nmain();\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$$$) — 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": "n=Number(readline());a=readline().split(' ').map(Number);\ne=a.reduce((r, i) => r + i, 0)/2;i=0;\nwhile (e > 0) e -= a[i++];\nprint(i);\n"}, {"source_code": "var a = parseInt(readline());\nvar b = readline().split(' ').map(function (i) { return parseInt(i); });\nvar c = b.reduce((a, b) => a + b);\nvar d = c / 2;\nvar e = 0;\nfor (var i = 0; i < b.length; i++) {\n e = e + b[i];\n if (e >= d) break;\n}\nprint(i + 1);"}, {"source_code": "var row = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = row[0];\n\nvar a = [];\nvar total = 0;\nrow = readline().split(\" \").map(function(x) { return parseInt(x); });\nfor(var i = 0; i < n; i++) {\n\ta.push(row[i]);\n\ttotal += parseInt(row[i]);\n}\n\nvar current = 0;\nfor(var i = 0; i < n; i++) {\n current += a[i];\n\tif(total / current <= 2) {\n\t write(i + 1);\n\t break;\n\t}\n}"}, {"source_code": "function main() {\n var n = Number(readline());\n var a = readline()\n .split(' ')\n .map(l => Number(l));\n var sum = [a[0]];\n\n for (var i = 1; i < a.length; i++) {\n sum[i] = sum[i - 1] + a[i];\n }\n\n var equator = sum[sum.length - 1] / 2;\n\n for (var i = 0; i < sum.length; i++) {\n if (sum[i] >= equator) {\n return print(i + 1);\n }\n }\n}\n\nmain();\n"}, {"source_code": "function main() {\n var n = readline();\n var a = readline().split(' ').map(l => Number(l));\n \n var sum = 0;\n for(var i = 0; i < n; i++)\n sum += a[i];\n \n var cnt = 0;\n for(var i = 0; i < n; i++) {\n cnt += a[i];\n \n if(2 * cnt >= sum)\n return print(i + 1), 0;\n }\n \n return 0;\n}\n\nmain();"}], "negative_code": [{"source_code": "var a = readline();\nvar b = readline();\nprint(a);"}, {"source_code": "function main() {\n var n = Number(readline());\n var a = readline()\n .split(' ')\n .map(l => Number(l));\n var sum = [a[0]];\n\n for (var i = 1; i < a.length; i++) {\n sum[i] = sum[i - 1] + a[i];\n }\n\n var equator = sum[sum.length - 1] / 2;\n\n for (var i = 1; i < sum.length; i++) {\n if (sum[i] >= equator) {\n return print(i + 1);\n }\n }\n}\n\nmain();\n"}, {"source_code": "function main() {\n var n = Number(readline());\n var a = readline()\n .split(' ')\n .map(l => Number(l));\n var sum = [a[0]];\n\n for (var i = 1; i < a.length; i++) {\n sum[i] = sum[i - 1] + a[i];\n }\n\n var closest = sum[0];\n var closestIndex = 0;\n\n for (var i = 1; i < sum.length; i++) {\n var iClose = Math.abs(sum[i] - sum[sum.length - 1] / 2);\n if (iClose < closest) {\n closest = iClose;\n closestIndex = i;\n }\n }\n\n print(closestIndex + 1);\n}\n\nmain();\n"}], "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$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$) — 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$$$) — the first array. The third line contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le n$$$) — 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": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tc: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[i - 1][0] > AB[i][0] || AB[i - 1][1] > AB[i][1]) {\r\n results.push(\"-1\");\r\n continue tc;\r\n }\r\n }\r\n\r\n ops = [];\r\n for (let i = 0; i < N; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([j + 1, i + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr1 = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr2 = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let res = [];\r\n const sort = (arr, arr1) => {\r\n for (let i = 0; i < n; i++) {\r\n let min = i;\r\n for (let j = i + 1; j < n; j++) {\r\n if (arr[min] > arr[j]) min = j;\r\n }\r\n if (min === i) continue;\r\n res.push(`${min + 1} ${i + 1}`);\r\n [arr[i], arr[min]] = [arr[min], arr[i]];\r\n [arr1[i], arr1[min]] = [arr1[min], arr1[i]];\r\n }\r\n for (let i = 1; i < n; i++) {\r\n if (arr1[i - 1] > arr1[i]) return false;\r\n }\r\n return true;\r\n };\r\n const print = () => {\r\n console.log(res.length);\r\n if (res.length === 0) return;\r\n for (let i = 0; i < res.length; i++) console.log(res[i]);\r\n };\r\n if (sort(arr1, arr2)) {\r\n print();\r\n continue;\r\n }\r\n if (sort(arr2, arr1)) {\r\n print();\r\n continue;\r\n }\r\n console.log(-1);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst calc = (testN)=>{\n // READING:\n let [n] = ra();\n let A = ra();\n let B = ra();\n LT({n, A, B});\n // PROCESSING:\n let P = [];\n for (let i=0; i{\n swaps.push((i+1)+' '+(j+1));\n let tmp = A[i];\n A[i] = A[j];\n A[j] = tmp;\n tmp = B[i];\n B[i] = B[j];\n B[j] = tmp;\n };\n for (let i=0; iB[j+1]){\n swap(j, j+1);\n }\n } else {\n if (A[j]B[j+1])\n return void print(-1);\n } else {\n if (B[j] lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\n/*---------------------------------------------------*/\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst calc = (t)=>{\n /* read */\n let n = +readline();\n let a = ra();\n let b = ra();\n\n let moves = [];\n\n for (let i = 0; i < n; i++) {\n let minidx = i;\n let j = i + 1;\n for (; j < n; j++) {\n if (a[j] < a[minidx]) {\n minidx = j;\n }\n }\n if (minidx === i) continue;\n j = minidx;\n moves.push(`${i + 1} ${j + 1}`);\n\n let tmpa = a[i];\n a[i] = a[j];\n a[j] = tmpa;\n\n let tmpb = b[i];\n b[i] = b[j];\n b[j] = tmpb;\n }\n\n for (let l = 0; l < n - 1; l++) {\n let r = l + 1;\n while (r < n && a[l] === a[r]) {\n r++;\n }\n\n for (let i = l; i < r; i++) {\n let minidx = i;\n let j = i + 1\n for (; j < r; j++) {\n if (b[j] < b[minidx]) {\n minidx = j;\n }\n }\n if (minidx === i) continue;\n j = minidx;\n moves.push(`${i + 1} ${j + 1}`);\n\n let tmpb = b[i];\n b[i] = b[j];\n b[j] = tmpb;\n }\n\n }\n\n if (moves.length > 10000) return '-1';\n\n for (let i = 1; i < n; i++) {\n if (b[i] < b[i - 1]) return '-1';\n }\n\n let result = `${moves.length}`;\n if (moves.length > 0) {\n result += '\\n';\n result += moves.join('\\n');\n }\n return result;\n};\n\nfunction main() {\n let T = +readline();\n let out = [];\n for (let t = 1; t <= T; t++){\n out.push(calc(t));\n // process.stdout.write(`${calc(n, a)}\\n`);\n }\n process.stdout.write(out.join('\\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"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nvar T = readline();\r\nfor(var qe=1;qe<=T;qe++) {\r\n var n = parseInt(readline());\r\n var a = readline().split(' ').map((x) => parseInt(x));\r\n var b = readline().split(' ').map((x) => parseInt(x));\r\n var as = [...a]\r\n var bs = [...b]\r\n as.sort(function(x,y) { return x-y })\r\n bs.sort(function(x,y) { return x-y })\r\n // var rev_a = reverse(as);\r\n // var rev_b = reverse(bs);\r\n // function reverse(arr) {\r\n // var v = [];\r\n // for(var j=arr.length-1;j>=0;j--) v.push(arr[j]);\r\n // return v;\r\n // }\r\n //console.log(a, as, rev_a);\r\n var ans = [];\r\n var flag = true;\r\n for(var i=0;i {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n l++\n const sa = lines[l++].trim().split(' ').map(Number)\n const sb = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(sa, sb)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(sa, sb) {\n const moves = []\n const sorted = sa.map((x, i) => ({ x, i }))\n // .sort((a, b) => a.x - b.x)\n sort(sorted, 0, sorted.length - 1, sa, moves)\n// console.log(sorted)\n //\n let p = {}, pi = -1\n sorted.forEach((x, i) => {\n if (x.x === p.x) {\n //\n } else {\n // [pi, i - 1]\n if (pi >= 0) {\n // console.log(pi, i - 1)\n sort(sorted, pi, i - 1, sb, moves)\n }\n p = x\n pi = i\n }\n })\n// console.log(pi, sa.length - 1)\n sort(sorted, pi, sa.length - 1, sb, moves)\n const after = sorted.map(o => sb[o.i])\n// console.log(after)\n for (let i = 1; i < after.length; i++) {\n if (after[i - 1] > after[i]) return -1\n }\n if (!moves.length) return 0\n return moves.length + '\\n' + moves.join('\\n')\n}\nfunction sort(arr, first, last, old, moves) {\n let swap\n for (let i = first; i <= last; i++) {\n swap = 0\n for (let j = first + 1; j <= last; j++) {\n if (old[arr[j - 1].i] > old[arr[j].i]) {\n [arr[j - 1], arr[j]] = [arr[j], arr[j - 1]]\n moves.push([j - 1 + 1, j + 1].join(' '))\n swap = 1\n }\n }\n if (!swap) break\n }\n}\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a, b) {\r\n let nums = new Array(n);\r\n for (let i = 0; i < n; i++) {\r\n nums[i] = [a[i], b[i], i];\r\n }\r\n let flag = true;\r\n nums.sort((a, b) => {\r\n if (a[0] === b[0]) {\r\n return a[1] - b[1];\r\n } else if (a[1] === b[1]) {\r\n return a[0] - b[0];\r\n } else {\r\n const x = a[0] - b[0],\r\n y = a[1] - b[1];\r\n if (x * y < 0) {\r\n flag = false;\r\n }\r\n return a[0] - b[0];\r\n }\r\n });\r\n if (!flag) return -1;\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [];\r\n let idx = 0;\r\n const add = (i, j) => {\r\n e[idx] = j, ne[idx] = h[i], h[i] = idx++;\r\n };\r\n for (let i = 0; i < n; i++) {\r\n if (nums[i][2] !== i) {\r\n add(i, nums[i][2]);\r\n }\r\n }\r\n let res = [],\r\n st = new Array(n);\r\n for (let i = 0; i < n; i++) {\r\n if (st[i]) continue;\r\n if (h[i] !== -1) {\r\n const queue = [i];\r\n for (let u of queue) {\r\n st[u] = 1;\r\n for (let k = h[u]; k !== -1; k = ne[k]) {\r\n const v = e[k];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n }\r\n }\r\n let cur = i;\r\n for (let j = 1; j < queue.length; j++) {\r\n res.push([cur, queue[j]]);\r\n cur = queue[j];\r\n }\r\n }\r\n }\r\n if (res.length === 0) return '0';\r\n return `${res.length}\\n${res.map(arr => arr.map(num => num + 1).join(' ')).join('\\n')}`;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}], "negative_code": [{"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tcloop: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {\r\n results.push(\"-1\");\r\n continue tcloop;\r\n }\r\n }\r\n\r\n ops = [];\r\n // for (let i = 0; i < N; i++) {\r\n // for (let j = i + 1; j < N; j++) {\r\n // if (A[i] > A[j] || B[i] > B[j]) {\r\n // [A[i], A[j]] = [A[j], A[i]];\r\n // [B[i], B[j]] = [B[j], B[i]];\r\n // ops.push([j + 1, i + 1].join(\" \"));\r\n // }\r\n // }\r\n // }\r\n for (let i = 1; i < N; i++) {\r\n for (let j = 1; j < N; j++) {\r\n if (A[j - 1] > A[j] || B[j - 1] > B[j]) {\r\n [A[j - 1], A[j]] = [A[j], A[j - 1]];\r\n [B[j - 1], B[j]] = [B[j], B[j - 1]];\r\n ops.push([j, j + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tcloop: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {\r\n results.push(\"-1\");\r\n continue tcloop;\r\n }\r\n }\r\n\r\n ops = [];\r\n for (let i = 0; i < N; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([j + 1, i + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const { Console } = require(\"console\");\r\n\r\nconst rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tcloop: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {\r\n results.push(\"-1\");\r\n continue tcloop;\r\n }\r\n }\r\n\r\n ops = [];\r\n for (let i = 0; i < N; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([j + 1, i + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n for (let i = 0; i < N; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([j + 1, i + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const { Console } = require(\"console\");\r\n\r\nconst rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tcloop: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {\r\n results.push(\"-1\");\r\n continue tcloop;\r\n }\r\n }\r\n\r\n ops = [];\r\n for (let i = 0; i < N - 1; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([j + 1, i + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const { Console } = require(\"console\");\r\n\r\nconst rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tcloop: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {\r\n results.push(-1);\r\n continue tcloop;\r\n }\r\n }\r\n\r\n ops = [];\r\n for (let i = 0; i < N; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([j + 1, i + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const { Console } = require(\"console\");\r\n\r\nconst rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tcloop: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[1][i - 1] > AB[1][i]) {\r\n results.push(-1);\r\n continue tcloop;\r\n }\r\n }\r\n\r\n ops = [];\r\n for (let i = 0; i < N; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([j + 1, i + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const { Console } = require(\"console\");\r\n\r\nconst rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n tcloop: for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n\r\n const AB = [];\r\n for (let i = 0; i < N; i++) {\r\n AB.push([A[i], B[i]]);\r\n }\r\n AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));\r\n for (let i = 1; i < N; i++) {\r\n if (AB[1][i - 1] > AB[1][i]) {\r\n results.push(-1);\r\n continue tcloop;\r\n }\r\n }\r\n\r\n ops = [];\r\n for (let i = 0; i < N; i++) {\r\n for (let j = i + 1; j < N; j++) {\r\n if (A[i] > A[j] || B[i] > B[j]) {\r\n [A[i], A[j]] = [A[j], A[i]];\r\n [B[i], B[j]] = [B[j], B[i]];\r\n ops.push([i + 1, j + 1].join(\" \"));\r\n }\r\n }\r\n }\r\n\r\n results.push(ops.length);\r\n for (let i = 0; i < ops.length; i++) {\r\n results.push(ops[i]);\r\n }\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const { Console } = require(\"console\");\r\n\r\nconst rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n\r\n const results = [];\r\n for (let t = 0; t < T; t++) {\r\n const N = Number(input.next().value);\r\n const A = input.next().value.split(\" \").map(Number);\r\n const B = input.next().value.split(\" \").map(Number);\r\n const history = [];\r\n for (let i = 0; i < N; i++) {\r\n let minA = A[i];\r\n let minB = B[i];\r\n let idxA = null;\r\n let idxB = null;\r\n for (let j = i + 1; j < N; j++) {\r\n if (minA > A[j]) {\r\n minA = A[j];\r\n idxA = j;\r\n }\r\n if (minB > B[j]) {\r\n minB = B[j];\r\n idxB = j;\r\n }\r\n }\r\n const idx = idxA || idxB;\r\n if (idx !== null) {\r\n let tmp = A[i];\r\n A[i] = A[idx];\r\n A[idx] = tmp;\r\n tmp = B[i];\r\n B[i] = B[idx];\r\n B[idx] = tmp;\r\n history.push([i + 1, idx + 1]);\r\n }\r\n }\r\n if (\r\n JSON.stringify(A.slice().sort()) === JSON.stringify(A) &&\r\n JSON.stringify(B.slice().sort()) === JSON.stringify(B)\r\n ) {\r\n results.push(history.length);\r\n history.forEach((v) => results.push(v.join(\" \")));\r\n } else {\r\n results.push(-1);\r\n }\r\n\r\n // console.log(history);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr1 = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr2 = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let res = [];\r\n const sort = (arr, arr1) => {\r\n for (let i = 0; i < n; i++) {\r\n let min = i;\r\n for (let j = i + 1; j < n; j++) {\r\n if (arr[min] > arr[j]) min = j;\r\n }\r\n if (min === i) continue;\r\n res.push(`${min + 1} ${i + 1}`);\r\n [arr[i], arr[min]] = [arr[min], arr[i]];\r\n [arr1[i], arr1[min]] = [arr1[min], arr1[i]];\r\n }\r\n for (let i = 1; i < n; i++) {\r\n if (arr1[i - 1] > arr1[i]) return false;\r\n }\r\n return true;\r\n };\r\n const print = () => {\r\n console.log(res.length);\r\n if (res.length === 0) return;\r\n for (let i = 0; i < res.length; i++) console.log(res[i]);\r\n };\r\n if (sort(arr1, arr2)) {\r\n print();\r\n continue;\r\n }\r\n res = [];\r\n if (sort(arr2, arr1)) {\r\n print();\r\n continue;\r\n }\r\n console.log(-1);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr1 = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr2 = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let res = [];\r\n const sort = (arr, arr1) => {\r\n for (let i = 0; i < n; i++) {\r\n let min = i;\r\n for (let j = i + 1; j < n; j++) {\r\n if (arr[min] > arr[j]) min = j;\r\n }\r\n if (min === i) continue;\r\n res.push(`${min + 1} ${i + 1}`);\r\n [arr[i], arr[min]] = [arr[min], arr[i]];\r\n [arr1[i], arr1[min]] = [arr1[min], arr1[i]];\r\n }\r\n for (let i = 1; i < n; i++) {\r\n if (arr1[i - 1] > arr1[i]) return false;\r\n }\r\n return true;\r\n };\r\n const print = () => {\r\n console.log(res.length);\r\n if (res.length === 0) return;\r\n for (let i = 0; i < res.length; i++) console.log(res[i]);\r\n };\r\n if (sort([...arr1], [...arr2])) {\r\n print();\r\n continue;\r\n }\r\n res = [];\r\n if (sort([...arr2], [...arr1])) {\r\n print();\r\n continue;\r\n }\r\n console.log(-1);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst calc = (testN)=>{\n // READING:\n let [n] = ra();\n let A = ra();\n let B = ra();\n LT({n, A, B});\n // PROCESSING:\n let P = [];\n for (let i=0; i{\n swaps.push((i+1)+' '+(j+1));\n let tmp = A[i];\n A[i] = A[j];\n A[j] = tmp;\n tmp = B[i];\n B[i] = B[j];\n B[j] = tmp;\n };\n for (let i=0; iB[j+1]){\n swap(j, j+1);\n }\n } else {\n if (A[j]B[j+1])\n print(-1);\n } else {\n if (B[j]1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst calc = (testN)=>{\n // READING:\n let [n] = ra();\n let A = ra();\n let B = ra();\n LT({n, A, B});\n // PROCESSING:\n let P = [];\n for (let i=0; i{\n swaps.push((i+1)+' '+(j+1));\n let tmp = A[i];\n A[i] = A[j];\n A[j] = tmp;\n tmp = B[i];\n B[i] = B[j];\n B[j] = tmp;\n };\n for (let i=0; iB[j+1]){\n swap(j, j+1);\n }\n } else {\n if (A[j]B[j+1])\n return -1;\n } else {\n if (B[j] lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\n/*---------------------------------------------------*/\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst calc = (t)=>{\n /* read */\n let n = +readline();\n let a = ra();\n let b = ra();\n\n let moves = [];\n\n for (let i = 0; i < n; i++) {\n let minidx = i;\n let j = i + 1;\n for (; j < n; j++) {\n if (a[j] < a[minidx]) {\n minidx = j;\n }\n }\n if (minidx === i) continue;\n j = minidx;\n moves.push(`${i} ${j}`);\n\n let tmpa = a[i];\n a[i] = a[j];\n a[j] = tmpa;\n\n let tmpb = b[i];\n b[i] = b[j];\n b[j] = tmpb;\n }\n\n for (let l = 0; l < n - 1; l++) {\n let r = l + 1;\n while (r < n && a[l] === a[r]) {\n r++;\n }\n\n for (let i = l; i < r; i++) {\n let minidx = i;\n let j = i + 1\n for (; j < r; j++) {\n if (b[j] < b[minidx]) {\n minidx = j;\n }\n }\n if (minidx === i) continue;\n j = minidx;\n moves.push(`${i} ${j}`);\n\n let tmpb = b[i];\n b[i] = b[j];\n b[j] = tmpb;\n }\n\n }\n\n if (moves.length > 10000) return '-1';\n\n for (let i = 1; i < n; i++) {\n if (b[i] < b[i - 1]) return '-1';\n }\n\n let result = `${moves.length}`;\n if (moves.length > 0) {\n result += '\\n';\n result += moves.join('\\n');\n }\n return result;\n};\n\nfunction main() {\n let T = +readline();\n let out = [];\n for (let t = 1; t <= T; t++){\n out.push(calc(t));\n // process.stdout.write(`${calc(n, a)}\\n`);\n }\n process.stdout.write(out.join('\\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"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nvar T = readline();\r\nfor(var qe=1;qe<=T;qe++) {\r\n var n = parseInt(readline());\r\n var a = readline().split(' ').map((x) => parseInt(x));\r\n var b = readline().split(' ').map((x) => parseInt(x));\r\n var as = [...a]\r\n var bs = [...b]\r\n as.sort(function(x,y) { return x-y })\r\n bs.sort(function(x,y) { return x-y })\r\n // var rev_a = reverse(as);\r\n // var rev_b = reverse(bs);\r\n // function reverse(arr) {\r\n // var v = [];\r\n // for(var j=arr.length-1;j>=0;j--) v.push(arr[j]);\r\n // return v;\r\n // }\r\n //console.log(a, as, rev_a);\r\n var ans = [];\r\n var flag = true;\r\n for(var i=0;i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction main(){\r\n const testNumbers = readline();\r\n \r\n for(let i = 0; iparseInt(x)));\r\n }\r\n}\r\n\r\n\r\nfunction solve(input){\r\n let max = 0;\r\n let min = 21;\r\n for(let i = 0; i<3; i++){\r\n max = input[i] > max ? input[i] : max;\r\n min = input[i] < min ? input[i] : min;\r\n }\r\n console.log(\r\n input.filter(x=>x != max && x != min)[0]\r\n )\r\n}"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable', function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end', function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n for(let _=1;_<=t;_++)\r\n {\r\n let [a,b,c]=line[_].split(' ').map(x=>{return parseInt(x)});\r\n if(a>b) [a,b]=[b,a];\r\n if(a>c) [a,c]=[c,a];\r\n if(b>c) [b,c]=[c,b];\r\n console.log(b);\r\n }\r\n})"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\nvar T = readline();\r\nvar inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n\tvar n = readline().split(\" \").map(w => parseInt(w));\r\n\tn.sort((x,y) => x-y);\r\n\tconsole.log(n[1])\r\n}"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', function(inputStdin) {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', function() {\r\n inputString = inputString.split('\\n');\r\n \r\n main();\r\n});\r\n \r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n \r\nfunction gcd(a,b )\r\n{\r\n if (!b)\r\n return a\r\n \r\n return gcd( b , a%b )\r\n}\r\n\r\n \r\nfunction main() {\r\n \r\n let t = parseInt(readLine());\r\n \r\n //let mod = 10**9+7\r\n loopwhile:\r\n while(t--)\r\n {\r\n \r\n let a_b_c = readLine().trim().split(\" \").map(x=>parseInt(x));\r\n \r\n //console.log(\"a_b_c \" + a_b_c)\r\n let min = Math.min(...a_b_c);\r\n let max = Math.max(...a_b_c);\r\n \r\n \r\n \r\n /*console.log(\"min \" + min)\r\n console.log(\"max \" + max)*/\r\n \r\n let medium = a_b_c.filter(x=>(x!=min)&&(x!=max))[0]\r\n \r\n //console.log(\"medium \" + medium)\r\n \r\n console.log(medium)\r\n } \r\n}"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\nfunction main() {\r\n const testCases = Number(readline());\r\n for (let i = 0; i < testCases; i++) {\r\n let arr = readline().split(\" \").map(elem => Number(elem));\r\n console.log(findMedium(arr))\r\n }\r\n}\r\n\r\nfunction findMedium(arr) {\r\n arr.sort((a, b) => a - b)\r\n return arr[1]\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(arr) {\n arr.sort((a, b) => a - b)\n return arr[1]\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar list = nextIntArray(3);\r\n\t\tlist.sort(function(a,b){\r\n\t\t\treturn a - b;\r\n\t\t});\r\n\t\tmyout(list[1]);\r\n\t}\r\n}\r\n"}, {"source_code": "t = +readline()\r\n\r\nwhile(t--) {\r\n abc = readline().split(' ').map(value => +value).sort((a, b) => a - b)\r\n print(abc[1])\r\n}"}, {"source_code": "t = +readline()\r\n \r\nwhile(t--) {\r\n abc = readline().split(' ').map(value => +value).sort((a, b) => a - b)\r\n print(abc[1])\r\n}"}, {"source_code": "var t = +readline();\r\n \r\nfor(var i = 0; i< t; i ++) {\r\n \r\n var nums = [];\r\n var arr = readline().split(' ')\r\n\r\n print(ThreeNum(arr[0],arr[1],arr[2]))\r\n \r\n}\r\n \r\nfunction ThreeNum(a,b,c){\r\n a = +a\r\n b = +b\r\n c = +c\r\n \r\n return [a,b,c].sort((a,b) => a-b)[1]\r\n}\r\n"}, {"source_code": "var t = readline();\r\n\r\nfor(tt=0;tt {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction main(){\r\n const testNumbers = readline()\r\n \r\n for(let i = 0; iparseInt(x)))\r\n }\r\n}\r\n\r\n\r\nfunction solve(input){\r\n let max = 0;\r\n let min = 21;\r\n for(let i = 0; i<3; i++){\r\n max = input[1] > max ? input[i] : max;\r\n min = input[i] < min ? input[i] : min;\r\n }\r\n console.log(\r\n input.filter(x=>x != max && x != min)[0]\r\n )\r\n}"}, {"source_code": "t = +readline()\r\n\r\nwhile(t--) {\r\n abc = readline().split(' ').map(value => +value).sort()\r\n print(abc[1])\r\n}"}], "src_uid": "63c2142461c93ae4c962eac1ecb5b192"} {"nl": {"description": "You are given $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ and an integer $$$k$$$. Find the maximum value of $$$i \\cdot j - k \\cdot (a_i | a_j)$$$ over all pairs $$$(i, j)$$$ of integers with $$$1 \\le i < j \\le n$$$. Here, $$$|$$$ is the bitwise OR operator.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$)  — the number of test cases. The first line of each test case contains two integers $$$n$$$ ($$$2 \\le n \\le 10^5$$$) and $$$k$$$ ($$$1 \\le k \\le \\min(n, 100)$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer  — the maximum possible value of $$$i \\cdot j - k \\cdot (a_i | a_j)$$$.", "sample_inputs": ["4\n3 3\n1 1 3\n2 2\n1 2\n4 3\n0 1 2 3\n6 6\n3 2 0 0 5 6"], "sample_outputs": ["-1\n-4\n3\n12"], "notes": "NoteLet $$$f(i, j) = i \\cdot j - k \\cdot (a_i | a_j)$$$.In the first test case, $$$f(1, 2) = 1 \\cdot 2 - k \\cdot (a_1 | a_2) = 2 - 3 \\cdot (1 | 1) = -1$$$. $$$f(1, 3) = 1 \\cdot 3 - k \\cdot (a_1 | a_3) = 3 - 3 \\cdot (1 | 3) = -6$$$. $$$f(2, 3) = 2 \\cdot 3 - k \\cdot (a_2 | a_3) = 6 - 3 \\cdot (1 | 3) = -3$$$. So the maximum is $$$f(1, 2) = -1$$$.In the fourth test case, the maximum is $$$f(3, 4) = 12$$$."}, "positive_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, k] = rna();\r\n\t\tconst a = rna();\r\n\t\ta.unshift(0);\r\n\r\n\t\tlet ans = -INF;\r\n\t\tfor (let i = n; i > Math.max(0, n-2*k); i--) {\r\n\t\t\tfor (let j = i-1; j > Math.max(0, n-2*k); j--) {\r\n\t\t\t\tconst cur = i*j - k*(a[i]|a[j]);\r\n\t\t\t\tans = Math.max(ans, cur);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, k] = rna();\r\n\t\tconst a = rna();\r\n\t\ta.unshift(0);\r\n\r\n\t\tlet ans = -INF;\r\n\t\tfor (let i = n; i >= Math.max(1, n-k-5); i--) {\r\n\t\t\tfor (let j = i-1; j >= Math.max(1, n-k-5); j--) {\r\n\t\t\t\tconst cur = i*j - k*(a[i]|a[j]);\r\n\t\t\t\tans = Math.max(ans, cur);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const args = lines[l++].trim().split(' ').map(Number)\n console.log(solve(n, k, args))\n }\n// })()\n})\n\nfunction solve(n, k, arr) {\n let max = -Infinity\n const limit = 2 * k + 1\n for (let i = 0; i < limit; i++) {\n for (let j = 0; j < limit; j++) {\n if (i === j) continue\n\n const a = n - 1 - i\n const b = n - 1 - j\n if (a < 0 || b < 0) continue\n const v = (a + 1) * (b + 1) - k * (arr[a] | arr[b])\n // console.log(i, j, v)\n max = Math.max(max, v)\n }\n }\n return max\n}\n"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, k] = rna();\r\n\t\tconst a = rna();\r\n\t\ta.unshift(0);\r\n\r\n\t\tlet ans = -INF;\r\n\t\tfor (let i = n; i >= Math.max(1, n-k); i--) {\r\n\t\t\tfor (let j = i-1; j >= Math.max(1, n-k); j--) {\r\n\t\t\t\tconst cur = i*j - k*(a[i]|a[j]);\r\n\t\t\t\tans = Math.max(ans, cur);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, k] = rna();\r\n\t\tconst a = rna();\r\n\t\ta.unshift(0);\r\n\r\n\t\tlet ans = -INF;\r\n\t\tfor (let i = n; i >= Math.max(1, n-k-5); i--) {\r\n\t\t\tfor (let j = i-1; j >- Math.max(1, n-k-5); j--) {\r\n\t\t\t\tconst cur = i*j - k*(a[i]|a[j]);\r\n\t\t\t\tans = Math.max(ans, cur);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, k] = rna();\r\n\t\tconst a = rna();\r\n\t\ta.unshift(0);\r\n\r\n\t\tlet ans = -INF;\r\n\t\tfor (let i = n; i > n-k; i--) {\r\n\t\t\tfor (let j = i-1; j > n-k; j--) {\r\n\t\t\t\tconst cur = i*j - k*(a[i]|a[j]);\r\n\t\t\t\tans = Math.max(ans, cur);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "3a45b6acdcf3800d1cb4ef8ac96ed4cf"} {"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, m (1 ≤ n, m ≤ 100) — the number of streets and avenues in Munhattan. Each of the next n lines contains m integers cij (1 ≤ cij ≤ 109) — 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 — 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": "function cmp(a,b){return a-b;}\n\ns=readline().split(' ')\nn=+s[0]\nm=+s[1]\nres=0\nwhile(n--)\n{\n a=readline().split(' ')\n a.sort(cmp)\n if (+a[0]>res)\n {\n res=+a[0]\n }\n}\nprint(res)"}, {"source_code": "main.apply(0, readNums());\nfunction main(n, m) {\n var max = 0;\n for (var i = 0; i < n; i++) {\n var v = min(readNums());\n if (v > max)\n max = v;\n }\n print(max);\n}\nfunction readNums() {\n return readline().split(' ').map(function(v) {\n return v - 0;\n })\n}\nfunction min(arr) {\n var v = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (v > arr[i])\n v = arr[i];\n }\n return v;\n}\n"}], "negative_code": [], "src_uid": "f2142bc2f44e5d8b77f8561c29038a73"} {"nl": {"description": "Three guys play a game: first, each person writes down $$$n$$$ distinct words of length $$$3$$$. Then, they total up the number of points as follows: if a word was written by one person — that person gets 3 points, if a word was written by two people — each of the two gets 1 point, if a word was written by all — nobody gets any points. In the end, how many points does each player have?", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) — 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 1000$$$) — the number of words written by each person. The following three lines each contain $$$n$$$ distinct strings — the words written by each person. Each string consists of $$$3$$$ lowercase English characters.", "output_spec": "For each test case, output three space-separated integers — the number of points each of the three guys earned. You should output the answers in the same order as the input; the $$$i$$$-th integer should be the number of points earned by the $$$i$$$-th guy.", "sample_inputs": ["3\n\n1\n\nabc\n\ndef\n\nabc\n\n3\n\norz for qaq\n\nqaq orz for\n\ncod for ces\n\n5\n\niat roc hem ica lly\n\nbac ter iol ogi sts\n\nbac roc lly iol iat"], "sample_outputs": ["1 3 1 \n2 2 6 \n9 11 5"], "notes": "NoteIn the first test case: The word $$$\\texttt{abc}$$$ was written by the first and third guys — they each get $$$1$$$ point. The word $$$\\texttt{def}$$$ was written by the second guy only — he gets $$$3$$$ points. "}, "positive_code": [{"source_code": "var t = parseInt(readline());\r\n\r\nvar calc = (ob1, ob2, ob3) => {\r\n var res = 0;\r\n for(var k in ob1){\r\n if(!ob2[k] && !ob3[k]) res += 3;\r\n else if (!ob2[k] || !ob3[k] ) res += 1;\r\n }\r\n \r\n return res;\r\n};\r\n\r\nvar toObj = (r) => {\r\n var obj = {}\r\n for(var i = 0; i < r.length; i++){\r\n obj[r[i]] = true\r\n }\r\n return obj\r\n}\r\n\r\nwhile(t--){\r\n var n = parseInt(readline());\r\n var r1 = readline().split(\" \");\r\n var r2 = readline().split(\" \");\r\n var r3 = readline().split(\" \");\r\n \r\n var ob1 = toObj(r1);\r\n var ob2 = toObj(r2);\r\n var ob3 = toObj(r3);\r\n \r\n \r\n var res1 = calc(ob1, ob2, ob3);\r\n var res2 = calc(ob2, ob1, ob3);\r\n var res3 = calc(ob3, ob2, ob1);\r\n \r\n print(res1 + \" \" + res2 + \" \" + res3);\r\n \r\n \r\n}"}, {"source_code": "(function main(){\r\n \r\n var t = readline();\r\n while(t--){\r\n var num = readline();\r\n var word = [];\r\n var obj = {\r\n\r\n }\r\n for(var i=0;i<3;i++){\r\n word[i] = readline().split(' ');\r\n for(var j=0;j {\r\n var count = 0; \r\n\r\n for (var i = 0; i < n; i++) {\r\n if (map.get(pl[i]) === 1) {\r\n count += 3;\r\n } else if (map.get(pl[i]) === 2) {\r\n count += 1;\r\n }\r\n }\r\n\r\n return count;\r\n }\r\n\r\n ans.push(counter(pl1));\r\n ans.push(counter(pl2));\r\n ans.push(counter(pl3));\r\n\r\n print(ans.join(' '));\r\n}\r\n"}, {"source_code": "var n, a;\r\n\r\n var tests = parseInt(readline());\r\n for (var t=0; t {\r\n i = 0;\r\n return () => {\r\n return lines[i++]\r\n }\r\n}\r\n\r\nrl.on('line', line => lines.push(line))\r\nrl.on('close', () => {\r\n const readLine = createReadLine();\r\n let t = parseInt(readLine())\r\n while (t--) {\r\n let words = {}\r\n let n = readLine()\r\n for (let i = 0; i < 3; i++){\r\n let playerWords = readLine().split(' ')\r\n for (const word of playerWords) {\r\n if (words[word]) {\r\n words[word].push(i)\r\n } else {\r\n words[word] = [i]\r\n }\r\n }\r\n }\r\n\r\n let result = {\r\n 0: 0,\r\n 1: 0,\r\n 2: 0,\r\n };\r\n\r\n for (const word in words) {\r\n if (words.hasOwnProperty(word)) {\r\n if (words[word].length === 1) {\r\n result[words[word][0]] += 3\r\n } else if (words[word].length === 2) {\r\n result[words[word][0]] += 1\r\n result[words[word][1]] += 1\r\n }\r\n }\r\n }\r\n\r\n console.log(result['0'], result['1'], result['2'])\r\n }\r\n})"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n\r\n let a = readline().split(' ');\r\n let b = readline().split(' ');\r\n let c = readline().split(' ');\r\n\r\n let arr = [...a, ...b, ...c];\r\n\r\n let freq = {};\r\n for (let i = 0; i < arr.length; i++) {\r\n if (freq[arr[i]]) {\r\n freq[arr[i]]++;\r\n } else {\r\n freq[arr[i]] = 1;\r\n }\r\n }\r\n\r\n const val = word => {\r\n if (freq[word] === 1) {\r\n return 3;\r\n } else if (freq[word] === 2) {\r\n return 1;\r\n } else if (freq[word] === 3) {\r\n return 0;\r\n }\r\n };\r\n\r\n let sa = a.reduce((acc, curr) => acc + val(curr), 0);\r\n let sb = b.reduce((acc, curr) => acc + val(curr), 0);\r\n let sc = c.reduce((acc, curr) => acc + val(curr), 0);\r\n\r\n output(`${sa} ${sb} ${sc}`);\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const numberOfTest = Number.parseInt(readline());\n for(let i=0; i {\n if(frqncy[word]){\n frqncy[word] = frqncy[word]+1\n } else {\n frqncy[word]= 1;\n }\n });\n s2Words.forEach(word => {\n if(frqncy[word]){\n frqncy[word] = frqncy[word]+1\n } else {\n frqncy[word]= 1;\n }\n });\n s3Words.forEach(word => {\n if(frqncy[word]){\n frqncy[word] = frqncy[word]+1\n } else {\n frqncy[word]= 1;\n }\n });\n const s1Count = s1Words.reduce((acc, curr)=> {\n if(frqncy[curr] == 2){\n acc += 1\n }else if(frqncy[curr] == 1){\n acc += 3\n }\n return acc;\n }, 0);\n const s2Count = s2Words.reduce((acc, curr)=> {\n if(frqncy[curr] == 2){\n acc += 1\n }else if(frqncy[curr] == 1){\n acc += 3\n }\n return acc;\n }, 0);\n\n const s3Count = s3Words.reduce((acc, curr)=> {\n if(frqncy[curr] == 2){\n acc += 1\n }else if(frqncy[curr] == 1){\n acc += 3\n }\n return acc;\n }, 0);\n console.log(`${s1Count} ${s2Count} ${s3Count}`);\n}"}, {"source_code": "let readline = require(\"readline\");\r\nconst { start } = require(\"repl\");\r\n\r\nlet rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n\r\n if (input.length === +input[0] * 4 + 1) {\r\n // call your function here\r\n solve(input);\r\n rl.close();\r\n }\r\n});\r\n\r\nlet solve = (input) => {\r\n //console.log(input[1 + 1].split(\" \"));\r\n\r\n for (let i = 1; i < input.length; i += 4) {\r\n let words1 = input[i + 1].split(\" \");\r\n let words2 = input[i + 2].split(\" \");\r\n let words3 = input[i + 3].split(\" \");\r\n\r\n let words1Map = {};\r\n let words2Map = {};\r\n let words3Map = {};\r\n\r\n for (const word of words1) {\r\n words1Map[word] = true;\r\n }\r\n\r\n for (const word of words2) {\r\n words2Map[word] = true;\r\n }\r\n for (const word of words3) {\r\n words3Map[word] = true;\r\n }\r\n\r\n let score1 = 0;\r\n let score2 = 0;\r\n let score3 = 0;\r\n\r\n for (const word of words1) {\r\n if (words2Map[word] && words3Map[word]) continue;\r\n else if (words2Map[word] || words3Map[word]) score1++;\r\n else score1 += 3;\r\n }\r\n\r\n for (const word of words2) {\r\n if (words1Map[word] && words3Map[word]) continue;\r\n else if (words1Map[word] || words3Map[word]) score2++;\r\n else score2 += 3;\r\n }\r\n\r\n for (const word of words3) {\r\n if (words1Map[word] && words2Map[word]) continue;\r\n else if (words1Map[word] || words2Map[word]) score3++;\r\n else score3 += 3;\r\n }\r\n\r\n console.log(`${score1} ${score2} ${score3}`);\r\n }\r\n};\r\n"}, {"source_code": "let fs = require(\"fs\");\r\nlet sc = {\r\n _buf: new Buffer.alloc(1 << 14),\r\n _bufPos: 0,\r\n _bufLen: 0,\r\n _ensure: function ()\r\n {\r\n if (this._bufPos === this._bufLen)\r\n {\r\n this._bufPos = 0;\r\n this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);\r\n }\r\n },\r\n _isws: function (ch)\r\n {\r\n return ch === 32 || ch === 9 || ch === 10 || ch === 13;\r\n },\r\n _islf: function (ch)\r\n {\r\n return ch === 10 || ch === 13;\r\n },\r\n _peekChar: function ()\r\n {\r\n this._ensure();\r\n return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];\r\n },\r\n _skipWs: function ()\r\n {\r\n while (this._isws(this._peekChar()))\r\n this._bufPos++;\r\n },\r\n _readUntil: function (stop)\r\n {\r\n this._ensure();\r\n if (this._bufPos === this._bufLen)\r\n throw new Error(\"eof\");\r\n let start = this._bufPos;\r\n let before = null;\r\n for (; ;)\r\n {\r\n if (this._bufPos === this._bufLen)\r\n {\r\n let len = this._bufPos - start, preLen = (before ? before.length : 0);\r\n let nbuf = new Buffer(len + preLen);\r\n if (before)\r\n before.copy(nbuf);\r\n before = nbuf;\r\n this._buf.copy(before, preLen, start);\r\n this._ensure();\r\n start = this._bufPos;\r\n }\r\n if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;\r\n this._bufPos++;\r\n }\r\n if (!before)\r\n return this._buf.toString(\"utf8\", start, this._bufPos);\r\n let after = this._buf.slice(start, this._bufPos);\r\n let res = new Buffer(before.length + after.length);\r\n before.copy(res);\r\n after.copy(res, before.length);\r\n return res.toString();\r\n },\r\n\r\n nextToken: function ()\r\n {\r\n this._skipWs();\r\n return this._readUntil(this._isws);\r\n },\r\n L: function ()\r\n {\r\n let line = this._readUntil(this._islf);\r\n if (this._peekChar() === 13) this._bufPos++;\r\n if (this._peekChar() === 10) this._bufPos++;\r\n return line;\r\n },\r\n N: function ()\r\n {\r\n return +this.nextToken();\r\n },\r\n S: function ()\r\n {\r\n return this.nextToken();\r\n }\r\n};\r\n\r\n// DO NOT CHANGE TEMPLATE BEFORE\r\n\r\nconst Def = Number(1e9);\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nconst LowerBound = (arr, val) =>\r\n{\r\n let ng = -1;\r\n let ok = arr.length;\r\n while (ok - ng > 1)\r\n {\r\n let med = (ok + ng) / 2 | 0;\r\n if (arr[med] >= val)\r\n {\r\n ok = med;\r\n }\r\n else\r\n {\r\n ng = med;\r\n }\r\n }\r\n\r\n return ok;\r\n}\r\n\r\nconst ReverseLowerBound = (arr, val) =>\r\n{\r\n let ng = 0;\r\n let ok = arr.length;\r\n while (ok - ng > 1)\r\n {\r\n let med = (ok + ng) / 2 | 0;\r\n if (arr[med] <= val)\r\n {\r\n ng = med;\r\n }\r\n else\r\n {\r\n ok = med;\r\n }\r\n }\r\n // Находит наибольший элемент который меньше или равен val\r\n return ng;\r\n}\r\n\r\n\r\nconst ReverseUpperBound = (arr, val) =>\r\n{\r\n let ng = 0;\r\n let ok = arr.length;\r\n while (ok - ng > 1)\r\n {\r\n let med = (ok + ng) / 2 | 0;\r\n if (arr[med] < val)\r\n {\r\n ng = med;\r\n }\r\n else\r\n {\r\n ok = med;\r\n }\r\n }\r\n // Находит наибольший элемент который меньше val\r\n return ng;\r\n}\r\n\r\nconst UpperBound = (arr, val) =>\r\n{\r\n let ok = arr.length;\r\n let ng = -1;\r\n while (ok - ng > 1)\r\n {\r\n let med = (ok + ng) / 2 | 0;\r\n if (arr[med] > val)\r\n {\r\n ok = med;\r\n }\r\n else\r\n {\r\n ng = med;\r\n }\r\n }\r\n\r\n return ok;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nconst Solve = () =>\r\n{\r\n let map1 = new Map();\r\n let map2 = new Map();\r\n let map3 = new Map();\r\n\r\n let n = +sc.L();\r\n let l1 = sc.L().split(' ');\r\n let l2 = sc.L().split(' ');\r\n let l3 = sc.L().split(' ');\r\n let map = new Map();\r\n\r\n for (let s of l1)\r\n {\r\n map1.set(s, 1);\r\n\r\n if (map.has(s))\r\n {\r\n map.set(s, map.get(s) + 1);\r\n }\r\n else map.set(s, 1);\r\n }\r\n\r\n for (let s of l2)\r\n {\r\n map2.set(s, 2);\r\n\r\n if (map.has(s))\r\n {\r\n map.set(s, map.get(s) + 1);\r\n }\r\n else map.set(s, 1);\r\n }\r\n\r\n for (let s of l3)\r\n {\r\n map3.set(s, 3);\r\n\r\n if (map.has(s))\r\n {\r\n map.set(s, map.get(s) + 1);\r\n }\r\n else map.set(s, 1);\r\n }\r\n\r\n let one = 0, two = 0, three = 0;\r\n for (let [key, value] of map)\r\n {\r\n let c = 0;\r\n\r\n if (map1.has(key))\r\n {\r\n ++c;\r\n }\r\n\r\n if (map2.has(key)) ++c;\r\n\r\n if (map3.has(key)) ++c;\r\n\r\n if (c === 2)\r\n {\r\n if (map1.has(key)) ++one;\r\n if (map2.has(key)) ++two;\r\n if (map3.has(key)) ++three;\r\n }\r\n else if (c === 1)\r\n {\r\n if (map1.has(key)) one += 3;\r\n if (map2.has(key)) two += 3;\r\n if (map3.has(key)) three += 3;\r\n }\r\n }\r\n\r\n console.log(`${one} ${two} ${three}`);\r\n\r\n\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\nconst main = () =>\r\n{\r\n let cases = +sc.L();\r\n while (cases-- > 0) Solve();\r\n\r\n // Solve();\r\n}\r\nmain();\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar map = {};\r\n\t\tvar one = nextStrArray(N);\r\n\t\tvar two = nextStrArray(N);\r\n\t\tvar three = nextStrArray(N);\r\n\t\tvar oneP = 0;\r\n\t\tvar twoP = 0;\r\n\t\tvar threeP = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tif(map[one[i]] == null){\r\n\t\t\t\tmap[one[i]] = 0;\r\n\t\t\t}\r\n\t\t\tmap[one[i]]++;\r\n\t\t\tif(map[two[i]] == null){\r\n\t\t\t\tmap[two[i]] = 0;\r\n\t\t\t}\r\n\t\t\tmap[two[i]]++;\r\n\t\t\tif(map[three[i]] == null){\r\n\t\t\t\tmap[three[i]] = 0;\r\n\t\t\t}\r\n\t\t\tmap[three[i]]++;\r\n\t\t}\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tif(map[one[i]] == 1){\r\n\t\t\t\toneP += 3;\r\n\t\t\t}else if(map[one[i]] == 2){\r\n\t\t\t\toneP++;\r\n\t\t\t}\r\n\t\t\tif(map[two[i]] == 1){\r\n\t\t\t\ttwoP += 3;\r\n\t\t\t}else if(map[two[i]] == 2){\r\n\t\t\t\ttwoP++;\r\n\t\t\t}\r\n\t\t\tif(map[three[i]] == 1){\r\n\t\t\t\tthreeP += 3;\r\n\t\t\t}else if(map[three[i]] == 2){\r\n\t\t\t\tthreeP++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(oneP + \" \" + twoP + \" \" + threeP);\r\n\t}\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines.slice(l, l + 3).map(str => str.trim().split(' '))\n l += 3\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const map = {}\n for (let i = 0; i < arr.length; i++) {\n for (let j = 0; j < arr[i].length; j++) {\n const s = arr[i][j]\n map[s] = (map[s] || 0) + 1\n }\n }\n // return [n, arr]\n // console.log(map)\n return arr.map(x => {\n let p = 0\n for (let i = 0; i < x.length; i++) {\n const s = x[i]\n if (map[s] === 1) {\n p += 3\n } else if (map[s] === 2) {\n p += 1\n }\n }\n return p\n }).join(' ')\n}\n"}], "negative_code": [], "src_uid": "f8a89510fefbbc8e5698efe8a0c30927"} {"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$$$) — 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$$$) — 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$$$) — 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": "var t = readline();\r\n for(var i = 0 ; i < t ; i++){\r\n var n = readline(),\r\n a = readline().split(' ').sort((a,b)=>{return(a - b)}).reverse();\r\n if(n == 1 && a[0] > 1){\r\n print(\"NO\");\r\n }\r\n else if(a[0] - a[1] > 1){\r\n print('NO');\r\n }\r\n else{\r\n print('YES');\r\n }\r\n }\r\n"}, {"source_code": "var tests = parseInt(readline());\r\n for (var t=0; t < tests; t++) {\r\n var n = parseInt(readline());\r\n var a = readline().split(' ').map(x=>parseInt(x));\r\n var ans = 'YES';\r\n if (n == 1) {\r\n if (a[0] != 1) {\r\n ans = 'NO'\r\n }\r\n } else {\r\n var max = Math.max(...a);\r\n a.splice(a.indexOf(max), 1);\r\n var second = Math.max(...a);\r\n if (max - second > 1) {\r\n ans = 'NO'\r\n }\r\n }\r\n print(ans);\r\n }"}, {"source_code": "var t = readline();\r\n\r\nfor (var i = 0; i < t; i++) {\r\n var n = readline();\r\n var c = readline().split(' ').map(Number);\r\n c.sort((a,b) => b - a);\r\n \r\n if (c[0] - c[1] <= 1 || c[0] === 1) print('YES');\r\n else { \r\n print('NO');\r\n }\r\n}\r\n"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n var e = 0;\n for(i = 1; i <= t * 2; i++){\n var k = lines[i].split(' ').map(Number).sort(function(a, b){return b - a});\n if(i % 2 == 1){\n e = k[0]; \n }else{\n console.log(k[0] - k[1] < 2 || e == 1 && k[0] == 1? 'YES' : 'NO');\n }\n }\n});"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n let arr = readline().split(' ').map(Number);\r\n\r\n arr.sort((a, b) => b - a);\r\n \r\n if (arr.length === 1 && arr[0] > 1) {\r\n output('NO');\r\n } else if (arr[0] - 1 > arr[1]) {\r\n output('NO');\r\n } else {\r\n output('YES');\r\n }\r\n }\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var c = readLine();\r\n var res = solveMeFirst(b, c);\r\n // let out = \"\";\r\n // if (res) {\r\n // for (let i = 0; i < res.length; i++) {\r\n // out += res[i] + \" \";\r\n // }\r\n console.log(res);\r\n // }\r\n }\r\n}\r\nfunction solveMeFirst(n, arr) {\r\n arr = arr.split(\" \");\r\n arr[arr.length - 1] = arr[arr.length - 1].replace(\"\\r\", \"\");\r\n arr.sort((a, b) => +a - +b);\r\n if (arr.length > 1) {\r\n if (\r\n +arr[arr.length - 1] - +arr[arr.length - 2] == 1 ||\r\n +arr[arr.length - 1] - +arr[arr.length - 2] == 0\r\n ) {\r\n return \"YES\";\r\n } else {\r\n return \"NO\";\r\n }\r\n } else {\r\n if (+arr[0] == 1) return \"YES\";\r\n else return \"NO\";\r\n }\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tlist.sort(function(a,b){\r\n\t\t\treturn b - a;\r\n\t\t});\r\n\t\tvar max = list[0];\r\n\t\tif(N == 1){\r\n\t\t\tif(max > 1){\r\n\t\t\t\tmyout(\"NO\");\r\n\t\t\t}else{\r\n\t\t\t\tmyout(\"YES\");\r\n\t\t\t}\r\n\t\t}else{\r\n\t\t\tvar nx = list[1];\r\n\t\t\tif(max > nx + 1){\r\n\t\t\t\tmyout(\"NO\");\r\n\t\t\t}else{\r\n\t\t\t\tmyout(\"YES\");\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main(){\n\tlet t = parseInt(readLine());\n\twhile(t--){\n\t\tlet n = parseInt(readLine());\n\t\tlet ans = true;\n\t\tconst arr = readLine().split(' ');\n\t\tif(n == 1){\n\t\t\tif(parseInt(arr[0]) > 1)console.log(\"NO\");\n\t\t\telse console.log(\"YES\");\n\t\t\tcontinue;\n\t\t}\n\t\tarr.sort(function(a, b){return b - a});\n\t\tif(arr[0] - 1 > arr[1])ans = false;\n\t\tconsole.log((ans? \"YES\" : \"NO\"));\n\t}\n\t\t\n}\n\n"}, {"source_code": "process.stdin.resume();process.stdin.setEncoding('utf-8');let inputString = '';let currentLine = 0;process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; }\n\nfunction main() {\n const N = readLine();\n for (let i = 0; i < N; i++) {\n const n = Number(readLine());\n const arr = readLine().split(' ').map(Number);\n arr.sort((x, y) => x - y);\n if (n === 1) {\n console.log(arr[0] === 1 ? 'YES' : 'NO');\n } else {\n console.log(arr[arr.length - 1] - arr[arr.length - 2] >=2 ? 'NO' : 'YES');\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let t = parseInt(readLine());\n\n for (let i = 0; i < t; i++) {\n let n = parseInt(readLine());\n let arr = readLine().split(\" \").map(Number);\n arr.sort((a, b) => a - b);\n\n if (n == 1) {\n if (arr[0] > 1) {\n console.log(\"NO\");\n } else {\n console.log(\"YES\");\n }\n } else {\n if (arr[n - 2] + 1 < arr[n - 1]) {\n console.log(\"NO\");\n } else {\n console.log(\"YES\");\n }\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nlet stepeni = [1, 2]\r\nlet stepen = function (n) {\r\n if (stepeni[n]) return stepeni[n];\r\n let l = stepeni.length - 1;\r\n while (l < n) {\r\n stepeni.push(2 * stepeni[l++]);\r\n }\r\n return stepeni[n];\r\n}\r\n\r\nlet parser = e=>parseInt(e);\r\nlet sorter = (a,b)=>a-b;\r\n\r\nfunction main() {\r\n let k = parseInt(readLine());\r\n for(let i = 0; i0){\r\n let br = niz.pop();\r\n if(preth-br>sme){\r\n flag = false;\r\n break;\r\n }\r\n sme+=br;\r\n preth = br;\r\n }\r\n }\r\n console.log(flag?\"YES\":\"NO\");\r\n }\r\n}"}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\n\r\nconst n = Number(inputs[0])\r\n\r\nmain(n, inputs)\r\n\r\nfunction main(_, lines) {\r\n let res = []\r\n next: for (let i = 0; i < _; i++) {\r\n const n = Number(lines[i * 2 + 1])\r\n const data = lines[i * 2 + 2].trim().split(' ').map(Number)\r\n\r\n data.sort((a, b) => b - a)\r\n if ((data.length === 1 && data[0] > 1) || data[0] > data[1] + 1) {\r\n res.push('NO')\r\n } else {\r\n res.push('YES')\r\n }\r\n }\r\n\r\n console.log(res.join('\\n'))\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr) ? 'YES' : 'NO'\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n if (n === 1) return arr[0] <= 1\n\n arr.sort((a, b) => b - a)\n return arr[0] - arr[1] <= 1\n}\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n console.log(solve());\r\n }\r\n}\r\nfunction solve() {\r\n const t = parseInt(readLine());\r\n const arr = readLine().split(\" \").map(i => parseInt(i)).sort((a, b) => a - b);\r\n let last = arr[arr.length - 1]\r\n if (t == 1 && last > 1) return \"NO\";\r\n if (t == 1 && last == 1) return \"YES\";\r\n if ((last - arr[arr.length - 2]) > 1) return \"NO\"\r\n return \"YES\";\r\n}\r\n"}, {"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nmodule.exports = E;\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\n\nconst EPS = 1e-6;\n\nconst calc = (arr, n)=>{\n arr.sort((a, b)=>b-a);\n if (n==1)\n return arr[0]==1;\n return arr[0]-arr[1]<2;\n for (let i=0; iarr[i+1]+1)\n return false;\n arr[i+1] = 0;\n }\n return true;\n};\n \nfunction main() {\n let T = +readline();\n while (T--){\n let n = +readline();\n let a = ra();\n print(calc(a, n) ? 'yes' : 'no')\n }\n}\n\nE.calc = calc;"}], "negative_code": [{"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n var e = 0;\n for(i = 1; i <= t * 2; i++){\n var k = lines[i].split(' ').map(Number).sort(function(a, b){return b - a});\n if(i % 2 == 1){\n e = k[0]; \n }else{\n console.log(k[0] - k[1] < 2 || e == k[0] ? 'YES' : 'NO');\n }\n }\n});"}], "src_uid": "8b926a19f380a56018308668c17c6928"} {"nl": {"description": "Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.Initially, on day $$$1$$$, there is one bacterium with mass $$$1$$$.Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $$$m$$$ splits, it becomes two bacteria of mass $$$\\frac{m}{2}$$$ each. For example, a bacterium of mass $$$3$$$ can split into two bacteria of mass $$$1.5$$$.Also, every night, the mass of every bacteria will increase by one.Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $$$n$$$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \\le n \\le 10^9$$$) — the sum of bacteria masses that Phoenix is interested in. ", "output_spec": "For each test case, if there is no way for the bacteria to exactly achieve total mass $$$n$$$, print -1. Otherwise, print two lines. The first line should contain an integer $$$d$$$  — the minimum number of nights needed. The next line should contain $$$d$$$ integers, with the $$$i$$$-th integer representing the number of bacteria that should split on the $$$i$$$-th day. If there are multiple solutions, print any.", "sample_inputs": ["3\n9\n11\n2"], "sample_outputs": ["3\n1 0 2 \n3\n1 1 2\n1\n0"], "notes": "NoteIn the first test case, the following process results in bacteria with total mass $$$9$$$: Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$ each. Night $$$1$$$: All bacteria's mass increases by one. There are now two bacteria with mass $$$1.5$$$. Day $$$2$$$: None split. Night $$$2$$$: There are now two bacteria with mass $$$2.5$$$. Day $$$3$$$: Both bacteria split. There are now four bacteria with mass $$$1.25$$$. Night $$$3$$$: There are now four bacteria with mass $$$2.25$$$. The total mass is $$$2.25+2.25+2.25+2.25=9$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 9 in 3 nights.$$$ $$$In the second test case, the following process results in bacteria with total mass $$$11$$$: Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$. Night $$$1$$$: There are now two bacteria with mass $$$1.5$$$. Day $$$2$$$: One bacterium splits. There are now three bacteria with masses $$$0.75$$$, $$$0.75$$$, and $$$1.5$$$. Night $$$2$$$: There are now three bacteria with masses $$$1.75$$$, $$$1.75$$$, and $$$2.5$$$. Day $$$3$$$: The bacteria with mass $$$1.75$$$ and the bacteria with mass $$$2.5$$$ split. There are now five bacteria with masses $$$0.875$$$, $$$0.875$$$, $$$1.25$$$, $$$1.25$$$, and $$$1.75$$$. Night $$$3$$$: There are now five bacteria with masses $$$1.875$$$, $$$1.875$$$, $$$2.25$$$, $$$2.25$$$, and $$$2.75$$$. The total mass is $$$1.875+1.875+2.25+2.25+2.75=11$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 11 in 3 nights.$$$ $$$In the third test case, the bacterium does not split on day $$$1$$$, and then grows to mass $$$2$$$ during night $$$1$$$."}, "positive_code": [{"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 3\n 9\n 11\n 2\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r 0) {\n b.push(total);\n b.sort((x,y) => x-y);\n }\n \n\n for(let i=1;i= r || rx <= l) return 0;\n if (lx >= l && rx <= r) return tree[x];\n var m = (lx + rx) / 2;\n var left = query(l, r, 2 * x + 1, lx, m),\n right = query(l, r, 2 * x + 2, m, rx);\n return Math.max(left, right);\n}\n\nvar l = readline().split(\" \");\nvar m = parseInt(l[0]);\nvar n = parseInt(l[1]);\n\nvar arr = readline().split(\" \");\nfor (var i = 0; i < n; i++) {\n arr[i] = parseInt(arr[i]);\n}\n\nvar N = 1;\nwhile (N < arr.length) N *= 2;\ntree = new Array(N * 2);\nfor (var i = 0; i < arr.length; i++) {\n tree[N - 1 + i] = arr[i];\n}\nfor (var i = N - 2; i >= 0; i--) {\n var left = tree[2 * i + 1],\n right = tree[2 * i + 2];\n tree[i] = Math.max(left, right);\n}\n\nvar q = parseInt(readline(), 10);\nwhile (q--) {\n l = readline().split(\" \");\n for (var i = 0; i < l.length; i++) l[i] = parseInt(l[i]);\n var xs = --l[0],\n ys = --l[1],\n xf = --l[2],\n yf = --l[3],\n k = l[4];\n xs = m - xs - 1;\n xf = m - xf - 1;\n if (ys > yf) {\n var temp = ys;\n ys = yf;\n yf = temp;\n temp = xs;\n xs = xf;\n xf = temp;\n }\n if ((xf - xs) % k !== 0 || (yf - ys) % k !== 0) {\n print(\"NO\");\n } else {\n var x = xs % k;\n if (x < m - query(ys, yf, 0, 0, N)) {\n print(\"YES\");\n } else {\n print(\"NO\");\n }\n }\n}\n"}, {"source_code": "function query(l, r, x, lx, rx) {\n if (lx >= r || rx <= l) return 0;\n if (lx >= l && rx <= r) return tree[x];\n var m = (lx + rx) / 2;\n var left = query(l, r, 2 * x + 1, lx, m),\n right = query(l, r, 2 * x + 2, m, rx);\n return Math.max(left, right);\n}\n\nvar l = readline().split(\" \");\nvar m = parseInt(l[0]);\nvar n = parseInt(l[1]);\n\nvar arr = readline().split(\" \");\nfor (var i = 0; i < n; i++) {\n arr[i] = parseInt(arr[i]);\n}\n\nvar N = 1;\nwhile (N < arr.length) N *= 2;\ntree = new Array(N * 2);\nfor (var i = 0; i < arr.length; i++) {\n tree[N - 1 + i] = arr[i];\n}\nfor (var i = N - 2; i >= 0; i--) {\n var left = tree[2 * i + 1],\n right = tree[2 * i + 2];\n tree[i] = Math.max(left, right);\n}\n\nvar q = parseInt(readline(), 10);\nwhile (q--) {\n l = readline().split(\" \");\n for (var i = 0; i < l.length; i++) l[i] = parseInt(l[i]);\n var xs = --l[0],\n ys = --l[1],\n xf = --l[2],\n yf = --l[3],\n k = l[4];\n xs = m - xs - 1;\n xf = m - xf - 1;\n if (ys > yf) {\n var temp = ys;\n ys = yf;\n yf = temp;\n temp = xs;\n xs = xf;\n xf = temp;\n }\n if ((xf - xs) % k !== 0 || (yf - ys) % k !== 0) {\n print(\"NO\\n\");\n } else {\n var x = xs % k;\n if (x < m - query(ys, yf, 0, 0, N)) {\n print(\"YES\\n\");\n } else {\n print(\"NO\\n\");\n }\n }\n}\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, q, a, b) {\r\n const segTree = new SegTree(m);\r\n for (let i = 0; i < m; i++) {\r\n segTree.update(i, a[i]);\r\n }\r\n let res = new Array(q);\r\n for (let i = 0; i < q; i++) {\r\n let [x1, y1, x2, y2, k] = b[i];\r\n if (Math.abs(x2 - x1) % k !== 0 || Math.abs(y2 - y1) % k !== 0) {\r\n res[i] = 'NO';\r\n } else if (y1 === y2) {\r\n res[i] = 'YES';\r\n } else {\r\n let max = 0;\r\n if (y1 > y2) {\r\n max = segTree.query(y2, y1 - 2);\r\n } else {\r\n max = segTree.query(y1, y2 - 2);\r\n }\r\n const cur = Math.floor((n - x1) / k) * k + x1;\r\n if (cur > max) {\r\n res[i] = 'YES';\r\n } else {\r\n res[i] = 'NO';\r\n }\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nclass SegTree {\r\n constructor(n) {\r\n this.n = n;\r\n this.root = this._newNode();\r\n this.update = (x, z) => {\r\n x = Math.max(x, 0);\r\n x = Math.min(x, n);\r\n this._update(this.root, 0, n, x, z);\r\n };\r\n this.query = (x, y) => {\r\n x = Math.max(x, 0);\r\n y = Math.min(y, n);\r\n return this._query(this.root, 0, n, x, y);\r\n };\r\n }\r\n _newNode(left = null, right = null) {\r\n return {\r\n max: 0,\r\n left,\r\n right\r\n };\r\n }\r\n _up(node) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n node.max = Math.max(left.max, right.max);\r\n }\r\n _update(node, l, r, x, z) {\r\n if (!node) return;\r\n if (l === r) {\r\n node.max = z;\r\n return;\r\n }\r\n const mid = Math.floor((l + r) / 2);\r\n if (!node.left) {\r\n node.left = this._newNode();\r\n node.right = this._newNode();\r\n }\r\n if (x <= mid) this._update(node.left, l, mid, x, z);else this._update(node.right, mid + 1, r, x, z);\r\n this._up(node);\r\n }\r\n _query(node, l, r, x, y) {\r\n if (y < x) return 0;\r\n if (!node) return 0;\r\n if (l === x && r === y) return node.max;\r\n let res = 0,\r\n mid = Math.floor((l + r) / 2);\r\n if (!node.left) {\r\n node.left = this._newNode();\r\n node.right = this._newNode();\r\n }\r\n if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else res = Math.max(this._query(node.left, l, mid, x, mid), this._query(node.right, mid + 1, r, mid + 1, y));\r\n return res;\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n const k = Number(await read());\r\n let tmp = k;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(n, m, k, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "negative_code": [], "src_uid": "19f12c275f2b389ed5a1af66808d1bbd"} {"nl": {"description": "The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one.Soon the Hedgehog came up with a brilliant idea: instead of buying ready-made puzzles, one can take his own large piece of paper with some picture and cut it into many small rectangular pieces, then mix them and solve the resulting puzzle, trying to piece together the picture. The resulting task is even more challenging than the classic puzzle: now all the fragments have the same rectangular shape, and one can assemble the puzzle only relying on the picture drawn on the pieces.All puzzle pieces turn out to be of the same size X × Y, because the picture is cut first by horizontal cuts with the pitch of X, then with vertical cuts with the pitch of Y. If we denote the initial size of the picture as A × B, then A must be divisible by X and B must be divisible by Y (X and Y are integer numbers). However, not every such cutting of the picture will result in a good puzzle. The Hedgehog finds a puzzle good if no two pieces in it are the same (It is allowed to rotate the pieces when comparing them, but it is forbidden to turn them over). Your task is to count for a given picture the number of good puzzles that you can make from it, and also to find the puzzle with the minimal piece size.", "input_spec": "The first line contains two numbers A and B which are the sizes of the picture. They are positive integers not exceeding 20. Then follow A lines containing B symbols each, describing the actual picture. The lines only contain uppercase English letters.", "output_spec": "In the first line print the number of possible good puzzles (in other words, the number of pairs (X, Y) such that the puzzle with the corresponding element sizes will be good). This number should always be positive, because the whole picture is a good puzzle itself. In the second line print two numbers — the sizes X and Y of the smallest possible element among all good puzzles. The comparison is made firstly by the area XY of one element and secondly — by the length X.", "sample_inputs": ["2 4\nABDC\nABDC", "2 6\nABCCBA\nABCCBA"], "sample_outputs": ["3\n2 1", "1\n2 6"], "notes": "NoteThe picture in the first sample test has the following good puzzles: (2, 1), (2, 2), (2, 4)."}, "positive_code": [{"source_code": "'use strict'\n\nlet lll\nlll = readline().split(' ').map(v => parseInt(v))\nlet A = lll[1]\nlet B = lll[0]\n\nlet f = []\nwhile (lll = readline()) {\n f.push(lll.split(''))\n}\n\nlet sa = []\nlet sb = []\nfor (let i = 1; i <= 20; i++) {\n if (!(A % i)) sa.push(i)\n if (!(B % i)) sb.push(i)\n}\n\nlet best = {x: Infinity, y: Infinity}\nlet all = 0\nfor (let i = 0; i < sa.length; i++) {\n n: for (let j = 0; j < sb.length; j++) {\n let ps = split(sa[i], sb[j])\n let phs = new Set\n for (let pi = 0; pi < ps.length; pi++) {\n let hs = rotatesHashes(ps[pi])\n if (sa[i] == 6 && sb[j] == 2) {\n for (let hi = 0; hi < 4; hi++) {\n let h = hs[hi]\n if (phs.has(h)) {\n let sss = []\n phs.forEach(v => sss.push(v))\n }\n }\n }\n for (let hi = 0; hi < 4; hi++) {\n let h = hs[hi]\n if (phs.has(h)) continue n\n }\n for (let hi = 0; hi < 4; hi++) {\n phs.add(hs[hi])\n }\n }\n all++\n if (best.x * best.y > sa[i] * sb[j] || best.x * best.y == sa[i] * sb[j] && best.x > sb[j]) {\n best.x = sb[j]\n best.y = sa[i]\n }\n }\n}\n\nprint(all)\nprint(best.x + ' ' + best.y)\n\nfunction split (x, y) {\n let ps = []\n for (let i = 0; i < A; i += x) {\n for (let j = 0; j < B; j += y) {\n let p = []\n for (let r = 0; r < y; r++) {\n p.push(f[j + r].slice(i, i + x))\n }\n ps.push(p)\n }\n }\n return ps\n}\n\nfunction rotatesHashes (p) {\n let hs = [hash(p)]\n for (let i = 0; i < 3; i++) {\n p = rotate(p)\n hs.push(hash(p))\n }\n return hs\n}\n\nfunction rotate (p) {\n let n = []\n for (let i = 0; i < p[0].length; i++) {\n n.push([])\n }\n for (let i = 0; i < p.length; i++) {\n for (let j = 0; j < p[0].length; j++) {\n n[j][p.length - i - 1] = p[i][j]\n }\n }\n return n\n}\n\nfunction hash (p) {\n let h = ''\n for (let i = 0; i < p.length; i++) {\n for (let j = 0; j < p[0].length; j++) {\n h += p[i][j]\n }\n h += '*'\n }\n return h\n}\n\nfunction test (a, b) {\n for (let i = 0; i < a.length; i++) {\n if (a[i] == b[i]) return false\n }\n return true\n}"}], "negative_code": [{"source_code": "'use strict'\n\nlet lll\nlll = readline().split(' ').map(v => parseInt(v))\nlet A = lll[1]\nlet B = lll[0]\n\nlet f = []\nwhile (lll = readline()) {\n f.push(lll.split(''))\n}\n\nlet sa = []\nlet sb = []\nfor (let i = 1; i <= 20; i++) {\n if (!(A % i)) sa.push(i)\n if (!(B % i)) sb.push(i)\n}\n\nlet best = {x: Infinity, y: Infinity}\nlet all = 0\nfor (let i = 0; i < sa.length; i++) {\n n: for (let j = 0; j < sb.length; j++) {\n let ps = split(sa[i], sb[j])\n let phs = new Set\n for (let pi = 0; pi < ps.length; pi++) {\n let hs = rotatesHashes(ps[pi])\n for (let hi = 0; hi < 4; hi++) {\n let h = hs[hi]\n if (phs.has(h)) continue n\n }\n for (let hi = 0; hi < 4; hi++) {\n phs.add(hs[hi])\n }\n }\n all++\n if (best.x * best.y > sa[i] * sb[j] || best.x * best.y == sa[i] * sb[j] && best.x > sb[j]) {\n best.x = sb[j]\n best.y = sa[i]\n }\n }\n}\n\nprint(all)\nprint(best.x + ' ' + best.y)\n\nfunction split (x, y) {\n let ps = []\n for (let i = 0; i < A; i += x) {\n for (let j = 0; j < B; j += y) {\n let p = []\n for (let r = 0; r < y; r++) {\n p.push(f[j + r].slice(i, i + x))\n }\n ps.push(p)\n }\n }\n return ps\n}\n\nfunction rotatesHashes (p) {\n let hs = [hash(p)]\n for (let i = 0; i < 3; i++) {\n p = rotate(p)\n hs.push(hash(p))\n }\n return hs\n}\n\nfunction rotate (p) {\n let n = []\n for (let i = 0; i < p[0].length; i++) {\n n.push([])\n }\n for (let i = 0; i < p.length; i++) {\n for (let j = 0; j < p[0].length; j++) {\n n[j][p.length - i - 1] = p[i][j]\n }\n }\n return n\n}\n\nfunction hash (p) {\n let h = ''\n for (let i = 0; i < p.length; i++) {\n for (let j = 0; j < p[0].length; j++) {\n h += p[i][j]\n }\n }\n return h\n}\n\nfunction test (a, b) {\n for (let i = 0; i < a.length; i++) {\n if (a[i] == b[i]) return false\n }\n return true\n}"}], "src_uid": "4de8b72f9ce12554cae8b6a83b3f023e"} {"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$$$) — 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$$$) — 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": "var bigInt = (function (undefined) {\n \"use strict\";\n\n var BASE = 1e7,\n LOG_BASE = 7,\n MAX_INT = 9007199254740992,\n MAX_INT_ARR = smallToArray(MAX_INT),\n LOG_MAX_INT = Math.log(MAX_INT);\n\n function Integer(v, radix) {\n if (typeof v === \"undefined\") return Integer[0];\n if (typeof radix !== \"undefined\") return +radix === 10 ? parseValue(v) : parseBase(v, radix);\n return parseValue(v);\n }\n\n function BigInteger(value, sign) {\n this.value = value;\n this.sign = sign;\n this.isSmall = false;\n }\n BigInteger.prototype = Object.create(Integer.prototype);\n\n function SmallInteger(value) {\n this.value = value;\n this.sign = value < 0;\n this.isSmall = true;\n }\n SmallInteger.prototype = Object.create(Integer.prototype);\n\n function isPrecise(n) {\n return -MAX_INT < n && n < MAX_INT;\n }\n\n function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes\n if (n < 1e7)\n return [n];\n if (n < 1e14)\n return [n % 1e7, Math.floor(n / 1e7)];\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\n }\n\n function arrayToSmall(arr) { // If BASE changes this function may need to change\n trim(arr);\n var length = arr.length;\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\n switch (length) {\n case 0: return 0;\n case 1: return arr[0];\n case 2: return arr[0] + arr[1] * BASE;\n default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\n }\n }\n return arr;\n }\n\n function trim(v) {\n var i = v.length;\n while (v[--i] === 0);\n v.length = i + 1;\n }\n\n function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\n var x = new Array(length);\n var i = -1;\n while (++i < length) {\n x[i] = 0;\n }\n return x;\n }\n\n function truncate(n) {\n if (n > 0) return Math.floor(n);\n return Math.ceil(n);\n }\n\n function add(a, b) { // assumes a and b are arrays with a.length >= b.length\n var l_a = a.length,\n l_b = b.length,\n r = new Array(l_a),\n carry = 0,\n base = BASE,\n sum, i;\n for (i = 0; i < l_b; i++) {\n sum = a[i] + b[i] + carry;\n carry = sum >= base ? 1 : 0;\n r[i] = sum - carry * base;\n }\n while (i < l_a) {\n sum = a[i] + carry;\n carry = sum === base ? 1 : 0;\n r[i++] = sum - carry * base;\n }\n if (carry > 0) r.push(carry);\n return r;\n }\n\n function addAny(a, b) {\n if (a.length >= b.length) return add(a, b);\n return add(b, a);\n }\n\n function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT\n var l = a.length,\n r = new Array(l),\n base = BASE,\n sum, i;\n for (i = 0; i < l; i++) {\n sum = a[i] - base + carry;\n carry = Math.floor(sum / base);\n r[i] = sum - carry * base;\n carry += 1;\n }\n while (carry > 0) {\n r[i++] = carry % base;\n carry = Math.floor(carry / base);\n }\n return r;\n }\n\n BigInteger.prototype.add = function (v) {\n var n = parseValue(v);\n if (this.sign !== n.sign) {\n return this.subtract(n.negate());\n }\n var a = this.value, b = n.value;\n if (n.isSmall) {\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\n }\n return new BigInteger(addAny(a, b), this.sign);\n };\n BigInteger.prototype.plus = BigInteger.prototype.add;\n\n SmallInteger.prototype.add = function (v) {\n var n = parseValue(v);\n var a = this.value;\n if (a < 0 !== n.sign) {\n return this.subtract(n.negate());\n }\n var b = n.value;\n if (n.isSmall) {\n if (isPrecise(a + b)) return new SmallInteger(a + b);\n b = smallToArray(Math.abs(b));\n }\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\n };\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\n\n function subtract(a, b) { // assumes a and b are arrays with a >= b\n var a_l = a.length,\n b_l = b.length,\n r = new Array(a_l),\n borrow = 0,\n base = BASE,\n i, difference;\n for (i = 0; i < b_l; i++) {\n difference = a[i] - borrow - b[i];\n if (difference < 0) {\n difference += base;\n borrow = 1;\n } else borrow = 0;\n r[i] = difference;\n }\n for (i = b_l; i < a_l; i++) {\n difference = a[i] - borrow;\n if (difference < 0) difference += base;\n else {\n r[i++] = difference;\n break;\n }\n r[i] = difference;\n }\n for (; i < a_l; i++) {\n r[i] = a[i];\n }\n trim(r);\n return r;\n }\n\n function subtractAny(a, b, sign) {\n var value;\n if (compareAbs(a, b) >= 0) {\n value = subtract(a, b);\n } else {\n value = subtract(b, a);\n sign = !sign;\n }\n value = arrayToSmall(value);\n if (typeof value === \"number\") {\n if (sign) value = -value;\n return new SmallInteger(value);\n }\n return new BigInteger(value, sign);\n }\n\n function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT\n var l = a.length,\n r = new Array(l),\n carry = -b,\n base = BASE,\n i, difference;\n for (i = 0; i < l; i++) {\n difference = a[i] + carry;\n carry = Math.floor(difference / base);\n difference %= base;\n r[i] = difference < 0 ? difference + base : difference;\n }\n r = arrayToSmall(r);\n if (typeof r === \"number\") {\n if (sign) r = -r;\n return new SmallInteger(r);\n } return new BigInteger(r, sign);\n }\n\n BigInteger.prototype.subtract = function (v) {\n var n = parseValue(v);\n if (this.sign !== n.sign) {\n return this.add(n.negate());\n }\n var a = this.value, b = n.value;\n if (n.isSmall)\n return subtractSmall(a, Math.abs(b), this.sign);\n return subtractAny(a, b, this.sign);\n };\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\n\n SmallInteger.prototype.subtract = function (v) {\n var n = parseValue(v);\n var a = this.value;\n if (a < 0 !== n.sign) {\n return this.add(n.negate());\n }\n var b = n.value;\n if (n.isSmall) {\n return new SmallInteger(a - b);\n }\n return subtractSmall(b, Math.abs(a), a >= 0);\n };\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\n\n BigInteger.prototype.negate = function () {\n return new BigInteger(this.value, !this.sign);\n };\n SmallInteger.prototype.negate = function () {\n var sign = this.sign;\n var small = new SmallInteger(-this.value);\n small.sign = !sign;\n return small;\n };\n\n BigInteger.prototype.abs = function () {\n return new BigInteger(this.value, false);\n };\n SmallInteger.prototype.abs = function () {\n return new SmallInteger(Math.abs(this.value));\n };\n\n function multiplyLong(a, b) {\n var a_l = a.length,\n b_l = b.length,\n l = a_l + b_l,\n r = createArray(l),\n base = BASE,\n product, carry, i, a_i, b_j;\n for (i = 0; i < a_l; ++i) {\n a_i = a[i];\n for (var j = 0; j < b_l; ++j) {\n b_j = b[j];\n product = a_i * b_j + r[i + j];\n carry = Math.floor(product / base);\n r[i + j] = product - carry * base;\n r[i + j + 1] += carry;\n }\n }\n trim(r);\n return r;\n }\n\n function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE\n var l = a.length,\n r = new Array(l),\n base = BASE,\n carry = 0,\n product, i;\n for (i = 0; i < l; i++) {\n product = a[i] * b + carry;\n carry = Math.floor(product / base);\n r[i] = product - carry * base;\n }\n while (carry > 0) {\n r[i++] = carry % base;\n carry = Math.floor(carry / base);\n }\n return r;\n }\n\n function shiftLeft(x, n) {\n var r = [];\n while (n-- > 0) r.push(0);\n return r.concat(x);\n }\n\n function multiplyKaratsuba(x, y) {\n var n = Math.max(x.length, y.length);\n\n if (n <= 30) return multiplyLong(x, y);\n n = Math.ceil(n / 2);\n\n var b = x.slice(n),\n a = x.slice(0, n),\n d = y.slice(n),\n c = y.slice(0, n);\n\n var ac = multiplyKaratsuba(a, c),\n bd = multiplyKaratsuba(b, d),\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\n\n var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));\n trim(product);\n return product;\n }\n\n // The following function is derived from a surface fit of a graph plotting the performance difference\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\n function useKaratsuba(l1, l2) {\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\n }\n\n BigInteger.prototype.multiply = function (v) {\n var n = parseValue(v),\n a = this.value, b = n.value,\n sign = this.sign !== n.sign,\n abs;\n if (n.isSmall) {\n if (b === 0) return Integer[0];\n if (b === 1) return this;\n if (b === -1) return this.negate();\n abs = Math.abs(b);\n if (abs < BASE) {\n return new BigInteger(multiplySmall(a, abs), sign);\n }\n b = smallToArray(abs);\n }\n if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes\n return new BigInteger(multiplyKaratsuba(a, b), sign);\n return new BigInteger(multiplyLong(a, b), sign);\n };\n\n BigInteger.prototype.times = BigInteger.prototype.multiply;\n\n function multiplySmallAndArray(a, b, sign) { // a >= 0\n if (a < BASE) {\n return new BigInteger(multiplySmall(b, a), sign);\n }\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\n }\n SmallInteger.prototype._multiplyBySmall = function (a) {\n if (isPrecise(a.value * this.value)) {\n return new SmallInteger(a.value * this.value);\n }\n return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);\n };\n BigInteger.prototype._multiplyBySmall = function (a) {\n if (a.value === 0) return Integer[0];\n if (a.value === 1) return this;\n if (a.value === -1) return this.negate();\n return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);\n };\n SmallInteger.prototype.multiply = function (v) {\n return parseValue(v)._multiplyBySmall(this);\n };\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\n\n function square(a) {\n //console.assert(2 * BASE * BASE < MAX_INT);\n var l = a.length,\n r = createArray(l + l),\n base = BASE,\n product, carry, i, a_i, a_j;\n for (i = 0; i < l; i++) {\n a_i = a[i];\n carry = 0 - a_i * a_i;\n for (var j = i; j < l; j++) {\n a_j = a[j];\n product = 2 * (a_i * a_j) + r[i + j] + carry;\n carry = Math.floor(product / base);\n r[i + j] = product - carry * base;\n }\n r[i + l] = carry;\n }\n trim(r);\n return r;\n }\n\n BigInteger.prototype.square = function () {\n return new BigInteger(square(this.value), false);\n };\n\n SmallInteger.prototype.square = function () {\n var value = this.value * this.value;\n if (isPrecise(value)) return new SmallInteger(value);\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\n };\n\n function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\n var a_l = a.length,\n b_l = b.length,\n base = BASE,\n result = createArray(b.length),\n divisorMostSignificantDigit = b[b_l - 1],\n // normalization\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\n remainder = multiplySmall(a, lambda),\n divisor = multiplySmall(b, lambda),\n quotientDigit, shift, carry, borrow, i, l, q;\n if (remainder.length <= a_l) remainder.push(0);\n divisor.push(0);\n divisorMostSignificantDigit = divisor[b_l - 1];\n for (shift = a_l - b_l; shift >= 0; shift--) {\n quotientDigit = base - 1;\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\n quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);\n }\n // quotientDigit <= base - 1\n carry = 0;\n borrow = 0;\n l = divisor.length;\n for (i = 0; i < l; i++) {\n carry += quotientDigit * divisor[i];\n q = Math.floor(carry / base);\n borrow += remainder[shift + i] - (carry - q * base);\n carry = q;\n if (borrow < 0) {\n remainder[shift + i] = borrow + base;\n borrow = -1;\n } else {\n remainder[shift + i] = borrow;\n borrow = 0;\n }\n }\n while (borrow !== 0) {\n quotientDigit -= 1;\n carry = 0;\n for (i = 0; i < l; i++) {\n carry += remainder[shift + i] - base + divisor[i];\n if (carry < 0) {\n remainder[shift + i] = carry + base;\n carry = 0;\n } else {\n remainder[shift + i] = carry;\n carry = 1;\n }\n }\n borrow += carry;\n }\n result[shift] = quotientDigit;\n }\n // denormalization\n remainder = divModSmall(remainder, lambda)[0];\n return [arrayToSmall(result), arrayToSmall(remainder)];\n }\n\n function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\n // Performs faster than divMod1 on larger input sizes.\n var a_l = a.length,\n b_l = b.length,\n result = [],\n part = [],\n base = BASE,\n guess, xlen, highx, highy, check;\n while (a_l) {\n part.unshift(a[--a_l]);\n trim(part);\n if (compareAbs(part, b) < 0) {\n result.push(0);\n continue;\n }\n xlen = part.length;\n highx = part[xlen - 1] * base + part[xlen - 2];\n highy = b[b_l - 1] * base + b[b_l - 2];\n if (xlen > b_l) {\n highx = (highx + 1) * base;\n }\n guess = Math.ceil(highx / highy);\n do {\n check = multiplySmall(b, guess);\n if (compareAbs(check, part) <= 0) break;\n guess--;\n } while (guess);\n result.push(guess);\n part = subtract(part, check);\n }\n result.reverse();\n return [arrayToSmall(result), arrayToSmall(part)];\n }\n\n function divModSmall(value, lambda) {\n var length = value.length,\n quotient = createArray(length),\n base = BASE,\n i, q, remainder, divisor;\n remainder = 0;\n for (i = length - 1; i >= 0; --i) {\n divisor = remainder * base + value[i];\n q = truncate(divisor / lambda);\n remainder = divisor - q * lambda;\n quotient[i] = q | 0;\n }\n return [quotient, remainder | 0];\n }\n\n function divModAny(self, v) {\n var value, n = parseValue(v);\n var a = self.value, b = n.value;\n var quotient;\n if (b === 0) throw new Error(\"Cannot divide by zero\");\n if (self.isSmall) {\n if (n.isSmall) {\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\n }\n return [Integer[0], self];\n }\n if (n.isSmall) {\n if (b === 1) return [self, Integer[0]];\n if (b == -1) return [self.negate(), Integer[0]];\n var abs = Math.abs(b);\n if (abs < BASE) {\n value = divModSmall(a, abs);\n quotient = arrayToSmall(value[0]);\n var remainder = value[1];\n if (self.sign) remainder = -remainder;\n if (typeof quotient === \"number\") {\n if (self.sign !== n.sign) quotient = -quotient;\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\n }\n return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];\n }\n b = smallToArray(abs);\n }\n var comparison = compareAbs(a, b);\n if (comparison === -1) return [Integer[0], self];\n if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\n\n // divMod1 is faster on smaller input sizes\n if (a.length + b.length <= 200)\n value = divMod1(a, b);\n else value = divMod2(a, b);\n\n quotient = value[0];\n var qSign = self.sign !== n.sign,\n mod = value[1],\n mSign = self.sign;\n if (typeof quotient === \"number\") {\n if (qSign) quotient = -quotient;\n quotient = new SmallInteger(quotient);\n } else quotient = new BigInteger(quotient, qSign);\n if (typeof mod === \"number\") {\n if (mSign) mod = -mod;\n mod = new SmallInteger(mod);\n } else mod = new BigInteger(mod, mSign);\n return [quotient, mod];\n }\n\n BigInteger.prototype.divmod = function (v) {\n var result = divModAny(this, v);\n return {\n quotient: result[0],\n remainder: result[1]\n };\n };\n SmallInteger.prototype.divmod = BigInteger.prototype.divmod;\n\n BigInteger.prototype.divide = function (v) {\n return divModAny(this, v)[0];\n };\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;\n\n BigInteger.prototype.mod = function (v) {\n return divModAny(this, v)[1];\n };\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;\n\n BigInteger.prototype.pow = function (v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value,\n value, x, y;\n if (b === 0) return Integer[1];\n if (a === 0) return Integer[0];\n if (a === 1) return Integer[1];\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\n if (n.sign) {\n return Integer[0];\n }\n if (!n.isSmall) throw new Error(\"The exponent \" + n.toString() + \" is too large.\");\n if (this.isSmall) {\n if (isPrecise(value = Math.pow(a, b)))\n return new SmallInteger(truncate(value));\n }\n x = this;\n y = Integer[1];\n while (true) {\n if (b & 1 === 1) {\n y = y.times(x);\n --b;\n }\n if (b === 0) break;\n b /= 2;\n x = x.square();\n }\n return y;\n };\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\n\n BigInteger.prototype.modPow = function (exp, mod) {\n exp = parseValue(exp);\n mod = parseValue(mod);\n if (mod.isZero()) throw new Error(\"Cannot take modPow with modulus 0\");\n var r = Integer[1],\n base = this.mod(mod);\n while (exp.isPositive()) {\n if (base.isZero()) return Integer[0];\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\n exp = exp.divide(2);\n base = base.square().mod(mod);\n }\n return r;\n };\n SmallInteger.prototype.modPow = BigInteger.prototype.modPow;\n\n function compareAbs(a, b) {\n if (a.length !== b.length) {\n return a.length > b.length ? 1 : -1;\n }\n for (var i = a.length - 1; i >= 0; i--) {\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\n }\n return 0;\n }\n\n BigInteger.prototype.compareAbs = function (v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (n.isSmall) return 1;\n return compareAbs(a, b);\n };\n SmallInteger.prototype.compareAbs = function (v) {\n var n = parseValue(v),\n a = Math.abs(this.value),\n b = n.value;\n if (n.isSmall) {\n b = Math.abs(b);\n return a === b ? 0 : a > b ? 1 : -1;\n }\n return -1;\n };\n\n BigInteger.prototype.compare = function (v) {\n // See discussion about comparison with Infinity:\n // https://github.com/peterolson/BigInteger.js/issues/61\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (this.sign !== n.sign) {\n return n.sign ? 1 : -1;\n }\n if (n.isSmall) {\n return this.sign ? -1 : 1;\n }\n return compareAbs(a, b) * (this.sign ? -1 : 1);\n };\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\n\n SmallInteger.prototype.compare = function (v) {\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (n.isSmall) {\n return a == b ? 0 : a > b ? 1 : -1;\n }\n if (a < 0 !== n.sign) {\n return a < 0 ? -1 : 1;\n }\n return a < 0 ? 1 : -1;\n };\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\n\n BigInteger.prototype.equals = function (v) {\n return this.compare(v) === 0;\n };\n SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;\n\n BigInteger.prototype.notEquals = function (v) {\n return this.compare(v) !== 0;\n };\n SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;\n\n BigInteger.prototype.greater = function (v) {\n return this.compare(v) > 0;\n };\n SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;\n\n BigInteger.prototype.lesser = function (v) {\n return this.compare(v) < 0;\n };\n SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;\n\n BigInteger.prototype.greaterOrEquals = function (v) {\n return this.compare(v) >= 0;\n };\n SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;\n\n BigInteger.prototype.lesserOrEquals = function (v) {\n return this.compare(v) <= 0;\n };\n SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;\n\n BigInteger.prototype.isEven = function () {\n return (this.value[0] & 1) === 0;\n };\n SmallInteger.prototype.isEven = function () {\n return (this.value & 1) === 0;\n };\n\n BigInteger.prototype.isOdd = function () {\n return (this.value[0] & 1) === 1;\n };\n SmallInteger.prototype.isOdd = function () {\n return (this.value & 1) === 1;\n };\n\n BigInteger.prototype.isPositive = function () {\n return !this.sign;\n };\n SmallInteger.prototype.isPositive = function () {\n return this.value > 0;\n };\n\n BigInteger.prototype.isNegative = function () {\n return this.sign;\n };\n SmallInteger.prototype.isNegative = function () {\n return this.value < 0;\n };\n\n BigInteger.prototype.isUnit = function () {\n return false;\n };\n SmallInteger.prototype.isUnit = function () {\n return Math.abs(this.value) === 1;\n };\n\n BigInteger.prototype.isZero = function () {\n return false;\n };\n SmallInteger.prototype.isZero = function () {\n return this.value === 0;\n };\n BigInteger.prototype.isDivisibleBy = function (v) {\n var n = parseValue(v);\n var value = n.value;\n if (value === 0) return false;\n if (value === 1) return true;\n if (value === 2) return this.isEven();\n return this.mod(n).equals(Integer[0]);\n };\n SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;\n\n function isBasicPrime(v) {\n var n = v.abs();\n if (n.isUnit()) return false;\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\n if (n.lesser(49)) return true;\n // we don't know if it's prime: let the other functions figure it out\n }\n\n function millerRabinTest(n, a) {\n var nPrev = n.prev(),\n b = nPrev,\n r = 0,\n d, t, i, x;\n while (b.isEven()) b = b.divide(2), r++;\n next : for (i = 0; i < a.length; i++) {\n if (n.lesser(a[i])) continue;\n x = bigInt(a[i]).modPow(b, n);\n if (x.equals(Integer[1]) || x.equals(nPrev)) continue;\n for (d = r - 1; d != 0; d--) {\n x = x.square().mod(n);\n if (x.isUnit()) return false;\n if (x.equals(nPrev)) continue next;\n }\n return false;\n }\n return true;\n }\n\n// Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\n BigInteger.prototype.isPrime = function (strict) {\n var isPrime = isBasicPrime(this);\n if (isPrime !== undefined) return isPrime;\n var n = this.abs();\n var bits = n.bitLength();\n if(bits <= 64)\n return millerRabinTest(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]);\n var logN = Math.log(2) * bits;\n var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);\n for (var a = [], i = 0; i < t; i++) {\n a.push(bigInt(i + 2));\n }\n return millerRabinTest(n, a);\n };\n SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;\n\n BigInteger.prototype.isProbablePrime = function (iterations) {\n var isPrime = isBasicPrime(this);\n if (isPrime !== undefined) return isPrime;\n var n = this.abs();\n var t = iterations === undefined ? 5 : iterations;\n for (var a = [], i = 0; i < t; i++) {\n a.push(bigInt.randBetween(2, n.minus(2)));\n }\n return millerRabinTest(n, a);\n };\n SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;\n\n BigInteger.prototype.modInv = function (n) {\n var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;\n while (!newR.equals(bigInt.zero)) {\n q = r.divide(newR);\n lastT = t;\n lastR = r;\n t = newT;\n r = newR;\n newT = lastT.subtract(q.multiply(newT));\n newR = lastR.subtract(q.multiply(newR));\n }\n if (!r.equals(1)) throw new Error(this.toString() + \" and \" + n.toString() + \" are not co-prime\");\n if (t.compare(0) === -1) {\n t = t.add(n);\n }\n if (this.isNegative()) {\n return t.negate();\n }\n return t;\n };\n\n SmallInteger.prototype.modInv = BigInteger.prototype.modInv;\n\n BigInteger.prototype.next = function () {\n var value = this.value;\n if (this.sign) {\n return subtractSmall(value, 1, this.sign);\n }\n return new BigInteger(addSmall(value, 1), this.sign);\n };\n SmallInteger.prototype.next = function () {\n var value = this.value;\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\n return new BigInteger(MAX_INT_ARR, false);\n };\n\n BigInteger.prototype.prev = function () {\n var value = this.value;\n if (this.sign) {\n return new BigInteger(addSmall(value, 1), true);\n }\n return subtractSmall(value, 1, this.sign);\n };\n SmallInteger.prototype.prev = function () {\n var value = this.value;\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\n return new BigInteger(MAX_INT_ARR, true);\n };\n\n var powersOfTwo = [1];\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\n var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];\n\n function shift_isSmall(n) {\n return ((typeof n === \"number\" || typeof n === \"string\") && +Math.abs(n) <= BASE) ||\n (n instanceof BigInteger && n.value.length <= 1);\n }\n\n BigInteger.prototype.shiftLeft = function (n) {\n if (!shift_isSmall(n)) {\n throw new Error(String(n) + \" is too large for shifting.\");\n }\n n = +n;\n if (n < 0) return this.shiftRight(-n);\n var result = this;\n if (result.isZero()) return result;\n while (n >= powers2Length) {\n result = result.multiply(highestPower2);\n n -= powers2Length - 1;\n }\n return result.multiply(powersOfTwo[n]);\n };\n SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;\n\n BigInteger.prototype.shiftRight = function (n) {\n var remQuo;\n if (!shift_isSmall(n)) {\n throw new Error(String(n) + \" is too large for shifting.\");\n }\n n = +n;\n if (n < 0) return this.shiftLeft(-n);\n var result = this;\n while (n >= powers2Length) {\n if (result.isZero() || (result.isNegative() && result.isUnit())) return result;\n remQuo = divModAny(result, highestPower2);\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\n n -= powers2Length - 1;\n }\n remQuo = divModAny(result, powersOfTwo[n]);\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\n };\n SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;\n\n function bitwise(x, y, fn) {\n y = parseValue(y);\n var xSign = x.isNegative(), ySign = y.isNegative();\n var xRem = xSign ? x.not() : x,\n yRem = ySign ? y.not() : y;\n var xDigit = 0, yDigit = 0;\n var xDivMod = null, yDivMod = null;\n var result = [];\n while (!xRem.isZero() || !yRem.isZero()) {\n xDivMod = divModAny(xRem, highestPower2);\n xDigit = xDivMod[1].toJSNumber();\n if (xSign) {\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\n }\n\n yDivMod = divModAny(yRem, highestPower2);\n yDigit = yDivMod[1].toJSNumber();\n if (ySign) {\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\n }\n\n xRem = xDivMod[0];\n yRem = yDivMod[0];\n result.push(fn(xDigit, yDigit));\n }\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\n for (var i = result.length - 1; i >= 0; i -= 1) {\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\n }\n return sum;\n }\n\n BigInteger.prototype.not = function () {\n return this.negate().prev();\n };\n SmallInteger.prototype.not = BigInteger.prototype.not;\n\n BigInteger.prototype.and = function (n) {\n return bitwise(this, n, function (a, b) { return a & b; });\n };\n SmallInteger.prototype.and = BigInteger.prototype.and;\n\n BigInteger.prototype.or = function (n) {\n return bitwise(this, n, function (a, b) { return a | b; });\n };\n SmallInteger.prototype.or = BigInteger.prototype.or;\n\n BigInteger.prototype.xor = function (n) {\n return bitwise(this, n, function (a, b) { return a ^ b; });\n };\n SmallInteger.prototype.xor = BigInteger.prototype.xor;\n\n var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;\n function roughLOB(n) { // get lowestOneBit (rough)\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\n var v = n.value, x = typeof v === \"number\" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI;\n return x & -x;\n }\n\n function integerLogarithm(value, base) {\n if (base.compareTo(value) <= 0) {\n var tmp = integerLogarithm(value, base.square(base));\n var p = tmp.p;\n var e = tmp.e;\n var t = p.multiply(base);\n return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };\n }\n return { p: bigInt(1), e: 0 };\n }\n\n BigInteger.prototype.bitLength = function () {\n var n = this;\n if (n.compareTo(bigInt(0)) < 0) {\n n = n.negate().subtract(bigInt(1));\n }\n if (n.compareTo(bigInt(0)) === 0) {\n return bigInt(0);\n }\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\n }\n SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;\n\n function max(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n return a.greater(b) ? a : b;\n }\n function min(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n return a.lesser(b) ? a : b;\n }\n function gcd(a, b) {\n a = parseValue(a).abs();\n b = parseValue(b).abs();\n if (a.equals(b)) return a;\n if (a.isZero()) return b;\n if (b.isZero()) return a;\n var c = Integer[1], d, t;\n while (a.isEven() && b.isEven()) {\n d = Math.min(roughLOB(a), roughLOB(b));\n a = a.divide(d);\n b = b.divide(d);\n c = c.multiply(d);\n }\n while (a.isEven()) {\n a = a.divide(roughLOB(a));\n }\n do {\n while (b.isEven()) {\n b = b.divide(roughLOB(b));\n }\n if (a.greater(b)) {\n t = b; b = a; a = t;\n }\n b = b.subtract(a);\n } while (!b.isZero());\n return c.isUnit() ? a : a.multiply(c);\n }\n function lcm(a, b) {\n a = parseValue(a).abs();\n b = parseValue(b).abs();\n return a.divide(gcd(a, b)).multiply(b);\n }\n function randBetween(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n var low = min(a, b), high = max(a, b);\n var range = high.subtract(low).add(1);\n if (range.isSmall) return low.add(Math.floor(Math.random() * range));\n var length = range.value.length - 1;\n var result = [], restricted = true;\n for (var i = length; i >= 0; i--) {\n var top = restricted ? range.value[i] : BASE;\n var digit = truncate(Math.random() * top);\n result.unshift(digit);\n if (digit < top) restricted = false;\n }\n result = arrayToSmall(result);\n return low.add(typeof result === \"number\" ? new SmallInteger(result) : new BigInteger(result, false));\n }\n var parseBase = function (text, base) {\n var length = text.length;\n var i;\n var absBase = Math.abs(base);\n for (var i = 0; i < length; i++) {\n var c = text[i].toLowerCase();\n if (c === \"-\") continue;\n if (/[a-z0-9]/.test(c)) {\n if (/[0-9]/.test(c) && +c >= absBase) {\n if (c === \"1\" && absBase === 1) continue;\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\n } else if (c.charCodeAt(0) - 87 >= absBase) {\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\n }\n }\n }\n if (2 <= base && base <= 36) {\n if (length <= LOG_MAX_INT / Math.log(base)) {\n var result = parseInt(text, base);\n if (isNaN(result)) {\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\n }\n return new SmallInteger(parseInt(text, base));\n }\n }\n base = parseValue(base);\n var digits = [];\n var isNegative = text[0] === \"-\";\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\n var c = text[i].toLowerCase(),\n charCode = c.charCodeAt(0);\n if (48 <= charCode && charCode <= 57) digits.push(parseValue(c));\n else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87));\n else if (c === \"<\") {\n var start = i;\n do { i++; } while (text[i] !== \">\");\n digits.push(parseValue(text.slice(start + 1, i)));\n }\n else throw new Error(c + \" is not a valid character\");\n }\n return parseBaseFromArray(digits, base, isNegative);\n };\n\n function parseBaseFromArray(digits, base, isNegative) {\n var val = Integer[0], pow = Integer[1], i;\n for (i = digits.length - 1; i >= 0; i--) {\n val = val.add(digits[i].times(pow));\n pow = pow.times(base);\n }\n return isNegative ? val.negate() : val;\n }\n\n function stringify(digit) {\n if (digit <= 35) {\n return \"0123456789abcdefghijklmnopqrstuvwxyz\".charAt(digit);\n }\n return \"<\" + digit + \">\";\n }\n\n function toBase(n, base) {\n base = bigInt(base);\n if (base.isZero()) {\n if (n.isZero()) return { value: [0], isNegative: false };\n throw new Error(\"Cannot convert nonzero numbers to base 0.\");\n }\n if (base.equals(-1)) {\n if (n.isZero()) return { value: [0], isNegative: false };\n if (n.isNegative())\n return {\n value: [].concat.apply([], Array.apply(null, Array(-n))\n .map(Array.prototype.valueOf, [1, 0])\n ),\n isNegative: false\n };\n\n var arr = Array.apply(null, Array(+n - 1))\n .map(Array.prototype.valueOf, [0, 1]);\n arr.unshift([1]);\n return {\n value: [].concat.apply([], arr),\n isNegative: false\n };\n }\n\n var neg = false;\n if (n.isNegative() && base.isPositive()) {\n neg = true;\n n = n.abs();\n }\n if (base.equals(1)) {\n if (n.isZero()) return { value: [0], isNegative: false };\n\n return {\n value: Array.apply(null, Array(+n))\n .map(Number.prototype.valueOf, 1),\n isNegative: neg\n };\n }\n var out = [];\n var left = n, divmod;\n while (left.isNegative() || left.compareAbs(base) >= 0) {\n divmod = left.divmod(base);\n left = divmod.quotient;\n var digit = divmod.remainder;\n if (digit.isNegative()) {\n digit = base.minus(digit).abs();\n left = left.next();\n }\n out.push(digit.toJSNumber());\n }\n out.push(left.toJSNumber());\n return { value: out.reverse(), isNegative: neg };\n }\n\n function toBaseString(n, base) {\n var arr = toBase(n, base);\n return (arr.isNegative ? \"-\" : \"\") + arr.value.map(stringify).join('');\n }\n\n BigInteger.prototype.toArray = function (radix) {\n return toBase(this, radix);\n };\n\n SmallInteger.prototype.toArray = function (radix) {\n return toBase(this, radix);\n };\n\n BigInteger.prototype.toString = function (radix) {\n if (radix === undefined) radix = 10;\n if (radix !== 10) return toBaseString(this, radix);\n var v = this.value, l = v.length, str = String(v[--l]), zeros = \"0000000\", digit;\n while (--l >= 0) {\n digit = String(v[l]);\n str += zeros.slice(digit.length) + digit;\n }\n var sign = this.sign ? \"-\" : \"\";\n return sign + str;\n };\n\n SmallInteger.prototype.toString = function (radix) {\n if (radix === undefined) radix = 10;\n if (radix != 10) return toBaseString(this, radix);\n return String(this.value);\n };\n BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }\n\n BigInteger.prototype.valueOf = function () {\n return parseInt(this.toString(), 10);\n };\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\n\n SmallInteger.prototype.valueOf = function () {\n return this.value;\n };\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\n\n function parseStringValue(v) {\n if (isPrecise(+v)) {\n var x = +v;\n if (x === truncate(x))\n return new SmallInteger(x);\n throw new Error(\"Invalid integer: \" + v);\n }\n var sign = v[0] === \"-\";\n if (sign) v = v.slice(1);\n var split = v.split(/e/i);\n if (split.length > 2) throw new Error(\"Invalid integer: \" + split.join(\"e\"));\n if (split.length === 2) {\n var exp = split[1];\n if (exp[0] === \"+\") exp = exp.slice(1);\n exp = +exp;\n if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error(\"Invalid integer: \" + exp + \" is not a valid exponent.\");\n var text = split[0];\n var decimalPlace = text.indexOf(\".\");\n if (decimalPlace >= 0) {\n exp -= text.length - decimalPlace - 1;\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\n }\n if (exp < 0) throw new Error(\"Cannot include negative exponent part for integers\");\n text += (new Array(exp + 1)).join(\"0\");\n v = text;\n }\n var isValid = /^([0-9][0-9]*)$/.test(v);\n if (!isValid) throw new Error(\"Invalid integer: \" + v);\n var r = [], max = v.length, l = LOG_BASE, min = max - l;\n while (max > 0) {\n r.push(+v.slice(min, max));\n min -= l;\n if (min < 0) min = 0;\n max -= l;\n }\n trim(r);\n return new BigInteger(r, sign);\n }\n\n function parseNumberValue(v) {\n if (isPrecise(v)) {\n if (v !== truncate(v)) throw new Error(v + \" is not an integer.\");\n return new SmallInteger(v);\n }\n return parseStringValue(v.toString());\n }\n\n function parseValue(v) {\n if (typeof v === \"number\") {\n return parseNumberValue(v);\n }\n if (typeof v === \"string\") {\n return parseStringValue(v);\n }\n return v;\n }\n // Pre-define numbers in range [-999,999]\n for (var i = 0; i < 1000; i++) {\n Integer[i] = new SmallInteger(i);\n if (i > 0) Integer[-i] = new SmallInteger(-i);\n }\n // Backwards compatibility\n Integer.one = Integer[1];\n Integer.zero = Integer[0];\n Integer.minusOne = Integer[-1];\n Integer.max = max;\n Integer.min = min;\n Integer.gcd = gcd;\n Integer.lcm = lcm;\n Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; };\n Integer.randBetween = randBetween;\n\n Integer.fromArray = function (digits, base, isNegative) {\n return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);\n };\n\n return Integer;\n})();\n\nif (typeof module !== \"undefined\" && module.hasOwnProperty(\"exports\")) {\n module.exports = bigInt;\n}\nif (typeof define === \"function\" && define.amd) {\n define(\"big-integer\", [], function () {\n return bigInt;\n });\n}\n\nvar cnt = +readline();\nfor(var i = 0; i < cnt; i++) {\n var line = readline().split(' ').map(v=>+v);\n var diff = line[0] - line[1];\n var answer = bigInt(diff).multiply(Math.ceil(line[2] / 2));\n if(line[2] % 2) answer = answer.plus(line[1]);\n print(answer.toString());\n}"}, {"source_code": "solve();\n\nfunction solve() {\n var t = Number(readline()), line, p1, p2, s1, res, d, o, z, bs, zs, sign;\n for (;t--;) {\n line = readline().split(' ').map(Number);\n z = '';\n p1 = (line[0] - line[1]);\n if (p1 < 0) {\n z = '-';\n p1 = -p1;\n }\n p2 = (line[2] >> 1);\n s1 = ((line[2] & 1) * line[0]);\n if (!p1 || line[2] === 1) {\n print(s1);\n continue;\n }\n zs = '';\n if (s1 < 0) {\n zs = '-';\n s1 = -s1;\n }\n res = [];\n while (p1) {\n o = p1 % 10;\n res.push(o);\n p1 = (p1 - o) / 10;\n }\n bs = [];\n if (s1) {\n while (s1) {\n o = s1 % 10;\n bs.push(o);\n s1 = (s1 - o) / 10;\n }\n } else {\n bs = [0];\n }\n d = 0;\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] * p2 + d;\n o = res[i] % 10;\n d = (res[i] - o) / 10;\n res[i] = o;\n }\n while (d) {\n o = d % 10;\n res.push(o);\n d = (d - o) / 10;\n }\n if (z === zs) {\n while (res.length < bs.length) {\n res.push(0);\n }\n while (bs.length < res.length) {\n bs.push(0);\n }\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] + bs[i] + d;\n o = res[i] % 10;\n d = (res[i] - o) / 10;\n res[i] = o;\n }\n while (d) {\n o = d % 10;\n res.push(o);\n d = (d - o) / 10;\n }\n } else {\n sign = 0;\n if (res.length < bs.length) {\n sign = -1;\n } else if (res.length > bs.length) {\n sign = 1;\n } else {\n for (i = res.length - 1; i >= 0; --i) {\n if (res[i] < bs[i]) {\n sign = -1;\n break;\n } else if (res[i] > bs[i]) {\n sign = 1;\n break;\n }\n }\n }\n if (!sign) {\n print(0);\n continue\n }\n if (sign === -1) {\n z = zs;\n p1 = res;\n res = bs;\n bs = p1;\n }\n while (bs.length < res.length) {\n bs.push(0);\n }\n for (i = 0; i < res.length; ++i) {\n if (res[i] + d < bs[i]) {\n res[i] = res[i] + d + 10 - bs[i];\n d = -1;\n } else {\n res[i] = res[i] + d - bs[i];\n d = 0;\n }\n }\n while (res[res.length - 1] === 0) {\n res.pop();\n }\n }\n print(z + res.reverse().join(''));\n /*a = line[0];\n b = line[1];\n k = line[2];\n print ('' + a + b + k);\n print((a - b) * (k >> 1) + (k & 1) * a);*/\n }\n}"}, {"source_code": "//solve();\n\nfunction solve() {\n var t = Number(readline()), line, p1, p2, s1, res, d, o, z, bs, zs, sign;\n for (;t--;) {\n line = readline().split(' ').map(Number);\n z = '';\n p1 = (line[0] - line[1]);\n if (p1 < 0) {\n z = '-';\n p1 = -p1;\n }\n p2 = (line[2] >> 1);\n s1 = ((line[2] & 1) * line[0]);\n if (!p1 || line[2] === 1) {\n print(s1);\n continue;\n }\n zs = '';\n if (s1 < 0) {\n zs = '-';\n s1 = -s1;\n }\n res = [];\n while (p1) {\n o = p1 % 10;\n res.push(o);\n p1 = (p1 - o) / 10;\n }\n bs = [];\n if (s1) {\n while (s1) {\n o = s1 % 10;\n bs.push(o);\n s1 = (s1 - o) / 10;\n }\n } else {\n bs = [0];\n }\n d = 0;\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] * p2 + d;\n o = res[i] % 10;\n d = (res[i] - o) / 10;\n res[i] = o;\n }\n while (d) {\n o = d % 10;\n res.push(o);\n d = (d - o) / 10;\n }\n if (z === zs) {\n while (res.length < bs.length) {\n res.push(0);\n }\n while (bs.length < res.length) {\n bs.push(0);\n }\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] + bs[i] + d;\n o = res[i] % 10;\n d = (res[i] - o) / 10;\n res[i] = o;\n }\n while (d) {\n o = d % 10;\n res.push(o);\n d = (d - o) / 10;\n }\n } else {\n sign = 0;\n if (res.length < bs.length) {\n sign = -1;\n } else if (res.length > bs.length) {\n sign = 1;\n } else {\n for (i = res.length - 1; i >= 0; --i) {\n if (res[i] < bs[i]) {\n sign = -1;\n break;\n } else if (res[i] > bs[i]) {\n sign = 1;\n break;\n }\n }\n }\n if (!sign) {\n print(0);\n continue\n }\n if (sign === -1) {\n z = zs;\n p1 = res;\n res = bs;\n bs = p1;\n }\n while (bs.length < res.length) {\n bs.push(0);\n }\n for (i = 0; i < res.length; ++i) {\n if (res[i] + d < bs[i]) {\n res[i] = res[i] + d + 10 - bs[i];\n d = -1;\n } else {\n res[i] = res[i] + d - bs[i];\n d = 0;\n }\n }\n while (res[res.length - 1] === 0) {\n res.pop();\n }\n }\n print(z + res.reverse().join(''));\n /*a = line[0];\n b = line[1];\n k = line[2];\n print ('' + a + b + k);\n print((a - b) * (k >> 1) + (k & 1) * a);*/\n }\n}\n\nlet MEMORY = [],\n i = 0;\nfunction print() {\n console.log.apply(null, arguments);\n}\nfunction readline() {\n return MEMORY[i++];\n}\n\nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n\nRL.on('line', (line) => {\n MEMORY.push(line);\n});\n\nRL.on('close', solve);\n"}], "negative_code": [{"source_code": "var BigNum = {\n\n plus: function plus(number1, number2, minus1, minus2) {\n\n if (typeof number1 === 'number' && Math.abs(number1) < BigNum.limit2 &&\n typeof number2 === 'number' && Math.abs(number2) < BigNum.limit2)\n\n return number1 + number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n if (minus1 === undefined) minus1 = ranks1.minus;\n if (minus2 === undefined) minus2 = ranks2.minus;\n\n\n if (!minus1) {\n if (minus2) {\n return BigNum.minus(ranks1, ranks2, false, false);\n }\n } else if (!minus2) {\n return BigNum.minus(ranks2, ranks1, false, false);\n } else {\n result.minus = true;\n }\n\n var maxRank = Math.max(ranks1.length, ranks2.length);\n for (var i = 0; i < maxRank; i++) {\n result[i] = (result[i] || 0)\n + (ranks1[i] || 0)\n + (ranks2[i] || 0);\n\n if (result[i] >= BigNum.limit) {\n result[i + 1] = 1;\n result[i] -= BigNum.limit;\n }\n }\n\n return result;\n },\n\n minus: function minus(number1, number2, minus1, minus2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit2 &&\n typeof number2 === 'number' && number2 < BigNum.limit2)\n\n return number1 - number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n if (minus1 === undefined) minus1 = ranks1.minus;\n if (minus2 === undefined) minus2 = ranks2.minus;\n\n\n if (!minus1) {\n if (minus2) {\n return BigNum.plus(ranks1, ranks2, false, false);\n }\n } else if (!minus2) {\n result = BigNum.plus(ranks1, ranks2, false, false);\n result.minus = true;\n return result;\n } else {\n return BigNum.minus(ranks2, ranks1, false, false);\n }\n\n var maxRank = Math.max(ranks1.length - 1, ranks2.length - 1);\n for (var i = maxRank; i >= 0; i--) {\n\n result[i] = (ranks1[i] || 0)\n - (ranks2[i] || 0);\n\n if (result[i] < 0) {\n if (result.minus === undefined) {\n result.minus = true;\n result[i] = -result[i];\n\n var swap = ranks1;\n ranks1 = ranks2;\n ranks2 = swap;\n } else {\n var j = i;\n do {\n result[j + 1] -= 1;\n result[j] += BigNum.limit;\n } while (result[++j] < 0);\n }\n } else if (result.minus === undefined && result[i] > 0) {\n result.minus = false;\n }\n }\n\n while(result[result.length - 1] === 0) {\n result.pop();\n }\n if (result.length < 3) {\n return BigNum.toInt(result);\n }\n\n return result;\n },\n\n multiply: function multiply(number1, number2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit &&\n typeof number2 === 'number' && number2 < BigNum.limit)\n\n return number1 * number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n for (var i = 0; i < ranks1.length; i++) {\n for (var j = 0; j < ranks2.length; j++) {\n var rank = i + j;\n var prod = ranks1[i] * ranks2[j];\n if (prod > BigNum.limit) {\n result[rank] = (result[rank] || 0)\n + prod % BigNum.limit;\n result[rank + 1] = (result[rank + 1] || 0)\n + Math.floor(prod / BigNum.limit);\n } else {\n result[rank] = (result[rank] || 0)\n + prod;\n }\n }\n }\n\n for (i = 0; i < result.length; i++) {\n if (result[i] > BigNum.limit) {\n result[i] -= BigNum.limit;\n result[i + 1] = (result[i + 1] || 0) + 1;\n }\n }\n\n result.minus = (ranks1.minus != ranks2.minus);\n return result;\n },\n\n divide: function divide(number1, number2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit2 &&\n typeof number2 === 'number' && number2 < BigNum.limit2)\n\n return number1 / number2;\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n var result = BigNum.toStr(ranks1) / BigNum.toStr(ranks2);\n return result;\n },\n\n ////////////////////////////////////////////////\n // comparision\n more: function more(number1, number2) {\n return BigNum.compare(number1, number2) > 0;\n },\n\n less: function less(number1, number2) {\n return BigNum.compare(number1, number2) < 0;\n },\n\n equal: function equal(number1, number2) {\n return BigNum.compare(number1, number2) === 0;\n },\n\n max: function max(number1, number2) {\n if(number2 !== undefined) {\n return BigNum.more(number1, number2) ? number1 : number2;\n }\n\n var numberArr = number1;\n var max = numberArr[0];\n\n for(var i = 1; i < numberArr.length; i++) {\n if(BigNum.more(numberArr[i], max)) {\n max = numberArr[i];\n }\n }\n\n return max;\n },\n\n min: function max(number1, number2) {\n if(number2 !== undefined) {\n return BigNum.compare(number1, number2) < 0 ? number1 : number2;\n }\n\n var numberArr = number1;\n var min = numberArr[0];\n\n for(var i = 1; i < numberArr.length; i++) {\n if(BigNum.compare(numberArr[i], min) < 0) {\n min = numberArr[i]\n }\n }\n\n return min;\n },\n\n compare: function compareNumbers(number1, number2) {\n var numberTypes = [typeof number1, typeof number2];\n\n if(numberTypes[0] === numberTypes[1]) {\n if(numberTypes[0] === 'number') {\n return number1 - number2;\n }\n } else {\n if (numberTypes[1] === 'number') {\n if (number1[2]) {\n return 1;\n }\n } else if (numberTypes[0] === 'number') {\n if(number2[2]) {\n return -1;\n }\n }\n }\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n var diff;\n\n if(ranks1.minus !== ranks2.minus) {\n return !ranks1.minus > !ranks2.minus ? 1 : -1\n } else if(diff = ranks1.length - ranks2.length) {\n return diff;\n }\n\n for (var i = ranks1.length - 1; i >= 0; i--) {\n if(diff = ranks1[i] - ranks2[i]) {\n return diff;\n }\n }\n\n return 0;\n },\n\n toInt: function (number) {\n if (typeof number === 'object') {\n if(!number.length) return 0;\n else return +BigNum.toStr(number);\n }\n else return +number;\n },\n\n toStr: function (number) {\n\n if (typeof number === 'string') return number;\n else if(typeof number === 'number') return '' + number;\n\n var str = '';\n for (var i = 0; i < number.length - 1; i++) {\n str = ('000000' + number[i]).substr(-7) + str;\n }\n str = number[i] + str;\n return (number.minus ? '-' : '') + str;\n },\n\n getBig: function (number) {\n if (typeof number === 'string') {\n if (number.length < 16) return +number;\n }\n\n return BigNum._getRanks(number);\n },\n\n _getRanks: function (number) {\n\n if (typeof number === 'object') {\n return number;\n } else if (typeof number === 'number') {\n number = '' + number;\n }\n\n var ranks = [];\n if (number[0] === '-') {\n ranks.minus = true;\n number = number.substr(1);\n }\n\n if (number.length > 7) {\n\n number = '' + number;\n for (var i = 7; i <= number.length; i += 7) {\n ranks.push(+number.substr(-i, 7));\n }\n\n var rest = number.length % 7;\n if (rest) {\n ranks.push(+number.substr(0, rest));\n }\n\n } else {\n ranks.push(+number);\n }\n\n if (ranks[ranks.length - 1] < 0) {\n ranks[ranks.length - 1] = -ranks[ranks.length - 1];\n ranks.minus = true;\n }\n\n return ranks;\n },\n\n rand: function getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n },\n\n /*runTests: function tests(count = 10) {\n var correct = 0;\n var values = [];\n for(var i = 0; i < count; i++) {\n var val1 = BigNum.rand(-999999999999999, 999999999999999);\n var val2 = BigNum.rand(-999999999999999, 999999999999999);\n\n var resBn = BigNum.plus(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = val1 + val2;\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' + ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.minus(val1, val2);\n resBnInt = BigNum.toInt(resBn);\n res = val1 - val2;\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' - ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.divide(val1, val2);\n resBnInt = Math.round(resBn, 4);\n res = Math.round(val1 / val2, 4);\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' / ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.more(val1, val2);\n res = val1 > val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' > ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.less(val1, val2);\n res = val1 < val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' < ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.equal(val1, val2);\n res = val1 === val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' === ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.equal(val1, val1);\n res = val1 === val1;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' === ' + val1);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.max(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.max(val1, val2);\n\n if(resBnInt !== res) {\n console.log('!!! max ' + val1 + ', ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.min(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.min(val1, val2);\n\n if(resBnInt !== res) {in\n console.log('!!! min ' + val1 + ', ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var val3 = BigNum.rand(-999999999999999, 999999999999999);\n var resBn = BigNum.max([val1, val2, val3]);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.max(val1, val2, val3);\n\n if(resBnInt !== res) {\n console.log('!!! max ' + val1 + ', ' + val2 + ', ' + val3);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.min([val1, val2, val3]);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.min(val1, val2, val3);\n\n if(resBnInt !== res) {\n console.log('!!! min ' + val1 + ', ' + val2 + ', ' + val3);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n val1 = BigNum.rand(-99999999, 99999999);\n val2 = BigNum.rand(-9999999, 9999999);\n\n resBn = BigNum.multiply(val1, val2);\n resBnInt = BigNum.toInt(resBn);\n res = Math.round(val1 * val2, 4);\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' * ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n }\n console.log('correct:' + correct);\n\n\n },*/\n /*runTimeTests: function timeTests(count = 10000, ranks = 15) {\n\n var max = Math.pow(10, ranks);\n\n var values = [];\n for(var i = 0; i < count; i++) {\n var val1 = BigNum.rand(-max, max);\n var val2 = BigNum.rand(-max, max);\n\n values.push([val1, val2]);\n }\n\n var testF = function (funcs, operation) {\n var results = [];\n for(var f = 0; f < 2; f++) {\n var func = funcs[f];\n var t = performance.now();\n for(var i = 0; i < count; i++) {\n res = func(values[i][0], values[i][1]);\n }\n results[f] = Math.floor(performance.now() - t);\n }\n\n console.log('test ' + operation + ': diff ' + (results[1] - results[0]));\n }\n\n var testsFuncs = {\n plus: [\n (val1, val2) => val1 + val2,\n (val1, val2) => BigNum.plus(val1, val2),\n ],\n\n minus: [\n (val1, val2) => val1 - val2,\n (val1, val2) => BigNum.minus(val1, val2),\n ],\n\n divide: [\n (val1, val2) => val1 / val2,\n (val1, val2) => BigNum.divide(val1, val2),\n ],\n\n miltiply: [\n (val1, val2) => val1 * val2,\n (val1, val2) => BigNum.multiply(val1, val2),\n ],\n };\n\n for(k in testsFuncs) {\n testF(testsFuncs[k], k);\n }\n },*/\n\n limit: 10000000,\n limit2: 100000000000000,\n}\n\n\n\nvar cnt = +readline();\nfor(var i = 0; i < cnt; i++) {\n var line = readline().split(' ').map(v=>+v);\n var diff = line[0] - line[1];\n var answer = BigNum.multiply(diff, Math.ceil(line[2] / 2));\n if(line[2] % 2) answer = BigNum.plus(answer, line[1]);\n print(BigNum.toInt(answer));\n}"}, {"source_code": "var BigNum = {\n\n plus: function plus(number1, number2, minus1, minus2) {\n\n if (typeof number1 === 'number' && Math.abs(number1) < BigNum.limit2 &&\n typeof number2 === 'number' && Math.abs(number2) < BigNum.limit2)\n\n return number1 + number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n if (minus1 === undefined) minus1 = ranks1.minus;\n if (minus2 === undefined) minus2 = ranks2.minus;\n\n\n if (!minus1) {\n if (minus2) {\n return BigNum.minus(ranks1, ranks2, false, false);\n }\n } else if (!minus2) {\n return BigNum.minus(ranks2, ranks1, false, false);\n } else {\n result.minus = true;\n }\n\n var maxRank = Math.max(ranks1.length, ranks2.length);\n for (var i = 0; i < maxRank; i++) {\n result[i] = (result[i] || 0)\n + (ranks1[i] || 0)\n + (ranks2[i] || 0);\n\n if (result[i] >= BigNum.limit) {\n result[i + 1] = 1;\n result[i] -= BigNum.limit;\n }\n }\n\n return result;\n },\n\n minus: function minus(number1, number2, minus1, minus2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit2 &&\n typeof number2 === 'number' && number2 < BigNum.limit2)\n\n return number1 - number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n if (minus1 === undefined) minus1 = ranks1.minus;\n if (minus2 === undefined) minus2 = ranks2.minus;\n\n\n if (!minus1) {\n if (minus2) {\n return BigNum.plus(ranks1, ranks2, false, false);\n }\n } else if (!minus2) {\n result = BigNum.plus(ranks1, ranks2, false, false);\n result.minus = true;\n return result;\n } else {\n return BigNum.minus(ranks2, ranks1, false, false);\n }\n\n var maxRank = Math.max(ranks1.length - 1, ranks2.length - 1);\n for (var i = maxRank; i >= 0; i--) {\n\n result[i] = (ranks1[i] || 0)\n - (ranks2[i] || 0);\n\n if (result[i] < 0) {\n if (result.minus === undefined) {\n result.minus = true;\n result[i] = -result[i];\n\n var swap = ranks1;\n ranks1 = ranks2;\n ranks2 = swap;\n } else {\n var j = i;\n do {\n result[j + 1] -= 1;\n result[j] += BigNum.limit;\n } while (result[++j] < 0);\n }\n } else if (result.minus === undefined && result[i] > 0) {\n result.minus = false;\n }\n }\n\n while(result[result.length - 1] === 0) {\n result.pop();\n }\n if (result.length < 3) {\n return BigNum.toInt(result);\n }\n\n return result;\n },\n\n multiply: function multiply(number1, number2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit &&\n typeof number2 === 'number' && number2 < BigNum.limit)\n\n return number1 * number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n for (var i = 0; i < ranks1.length; i++) {\n for (var j = 0; j < ranks2.length; j++) {\n var rank = i + j;\n var prod = ranks1[i] * ranks2[j];\n if (prod > BigNum.limit) {\n result[rank] = (result[rank] || 0)\n + prod % BigNum.limit;\n result[rank + 1] = (result[rank + 1] || 0)\n + Math.floor(prod / BigNum.limit);\n } else {\n result[rank] = (result[rank] || 0)\n + prod;\n }\n }\n }\n\n for (i = 0; i < result.length; i++) {\n if (result[i] > BigNum.limit) {\n result[i] -= BigNum.limit;\n result[i + 1] = (result[i + 1] || 0) + 1;\n }\n }\n\n result.minus = (ranks1.minus != ranks2.minus);\n return result;\n },\n\n divide: function divide(number1, number2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit2 &&\n typeof number2 === 'number' && number2 < BigNum.limit2)\n\n return number1 / number2;\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n var result = BigNum.toStr(ranks1) / BigNum.toStr(ranks2);\n return result;\n },\n\n ////////////////////////////////////////////////\n // comparision\n more: function more(number1, number2) {\n return BigNum.compare(number1, number2) > 0;\n },\n\n less: function less(number1, number2) {\n return BigNum.compare(number1, number2) < 0;\n },\n\n equal: function equal(number1, number2) {\n return BigNum.compare(number1, number2) === 0;\n },\n\n max: function max(number1, number2) {\n if(number2 !== undefined) {\n return BigNum.more(number1, number2) ? number1 : number2;\n }\n\n var numberArr = number1;\n var max = numberArr[0];\n\n for(var i = 1; i < numberArr.length; i++) {\n if(BigNum.more(numberArr[i], max)) {\n max = numberArr[i];\n }\n }\n\n return max;\n },\n\n min: function max(number1, number2) {\n if(number2 !== undefined) {\n return BigNum.compare(number1, number2) < 0 ? number1 : number2;\n }\n\n var numberArr = number1;\n var min = numberArr[0];\n\n for(var i = 1; i < numberArr.length; i++) {\n if(BigNum.compare(numberArr[i], min) < 0) {\n min = numberArr[i]\n }\n }\n\n return min;\n },\n\n compare: function compareNumbers(number1, number2) {\n var numberTypes = [typeof number1, typeof number2];\n\n if(numberTypes[0] === numberTypes[1]) {\n if(numberTypes[0] === 'number') {\n return number1 - number2;\n }\n } else {\n if (numberTypes[1] === 'number') {\n if (number1[2]) {\n return 1;\n }\n } else if (numberTypes[0] === 'number') {\n if(number2[2]) {\n return -1;\n }\n }\n }\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n var diff;\n\n if(ranks1.minus !== ranks2.minus) {\n return !ranks1.minus > !ranks2.minus ? 1 : -1\n } else if(diff = ranks1.length - ranks2.length) {\n return diff;\n }\n\n for (var i = ranks1.length - 1; i >= 0; i--) {\n if(diff = ranks1[i] - ranks2[i]) {\n return diff;\n }\n }\n\n return 0;\n },\n\n toInt: function (number) {\n if (typeof number === 'object') {\n if(!number.length) return 0;\n else return +BigNum.toStr(number);\n }\n else return +number;\n },\n\n toStr: function (number) {\n\n if (typeof number === 'string') return number;\n else if(typeof number === 'number') return '' + number;\n\n var str = '';\n for (var i = 0; i < number.length - 1; i++) {\n str = ('000000' + number[i]).substr(-7) + str;\n }\n str = number[i] + str;\n return (number.minus ? '-' : '') + str;\n },\n\n getBig: function (number) {\n if (typeof number === 'string') {\n if (number.length < 16) return +number;\n }\n\n return BigNum._getRanks(number);\n },\n\n _getRanks: function (number) {\n\n if (typeof number === 'object') {\n return number;\n } else if (typeof number === 'number') {\n number = '' + number;\n }\n\n var ranks = [];\n if (number[0] === '-') {\n ranks.minus = true;\n number = number.substr(1);\n }\n\n if (number.length > 7) {\n\n number = '' + number;\n for (var i = 7; i <= number.length; i += 7) {\n ranks.push(+number.substr(-i, 7));\n }\n\n var rest = number.length % 7;\n if (rest) {\n ranks.push(+number.substr(0, rest));\n }\n\n } else {\n ranks.push(+number);\n }\n\n if (ranks[ranks.length - 1] < 0) {\n ranks[ranks.length - 1] = -ranks[ranks.length - 1];\n ranks.minus = true;\n }\n\n return ranks;\n },\n\n rand: function getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n },\n\n /*runTests: function tests(count = 10) {\n var correct = 0;\n var values = [];\n for(var i = 0; i < count; i++) {\n var val1 = BigNum.rand(-999999999999999, 999999999999999);\n var val2 = BigNum.rand(-999999999999999, 999999999999999);\n\n var resBn = BigNum.plus(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = val1 + val2;\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' + ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.minus(val1, val2);\n resBnInt = BigNum.toInt(resBn);\n res = val1 - val2;\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' - ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.divide(val1, val2);\n resBnInt = Math.round(resBn, 4);\n res = Math.round(val1 / val2, 4);\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' / ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.more(val1, val2);\n res = val1 > val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' > ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.less(val1, val2);\n res = val1 < val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' < ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.equal(val1, val2);\n res = val1 === val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' === ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.equal(val1, val1);\n res = val1 === val1;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' === ' + val1);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.max(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.max(val1, val2);\n\n if(resBnInt !== res) {\n console.log('!!! max ' + val1 + ', ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.min(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.min(val1, val2);\n\n if(resBnInt !== res) {in\n console.log('!!! min ' + val1 + ', ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var val3 = BigNum.rand(-999999999999999, 999999999999999);\n var resBn = BigNum.max([val1, val2, val3]);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.max(val1, val2, val3);\n\n if(resBnInt !== res) {\n console.log('!!! max ' + val1 + ', ' + val2 + ', ' + val3);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.min([val1, val2, val3]);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.min(val1, val2, val3);\n\n if(resBnInt !== res) {\n console.log('!!! min ' + val1 + ', ' + val2 + ', ' + val3);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n val1 = BigNum.rand(-99999999, 99999999);\n val2 = BigNum.rand(-9999999, 9999999);\n\n resBn = BigNum.multiply(val1, val2);\n resBnInt = BigNum.toInt(resBn);\n res = Math.round(val1 * val2, 4);\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' * ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n }\n console.log('correct:' + correct);\n\n\n },*/\n /*runTimeTests: function timeTests(count = 10000, ranks = 15) {\n\n var max = Math.pow(10, ranks);\n\n var values = [];\n for(var i = 0; i < count; i++) {\n var val1 = BigNum.rand(-max, max);\n var val2 = BigNum.rand(-max, max);\n\n values.push([val1, val2]);\n }\n\n var testF = function (funcs, operation) {\n var results = [];\n for(var f = 0; f < 2; f++) {\n var func = funcs[f];\n var t = performance.now();\n for(var i = 0; i < count; i++) {\n res = func(values[i][0], values[i][1]);\n }\n results[f] = Math.floor(performance.now() - t);\n }\n\n console.log('test ' + operation + ': diff ' + (results[1] - results[0]));\n }\n\n var testsFuncs = {\n plus: [\n (val1, val2) => val1 + val2,\n (val1, val2) => BigNum.plus(val1, val2),\n ],\n\n minus: [\n (val1, val2) => val1 - val2,\n (val1, val2) => BigNum.minus(val1, val2),\n ],\n\n divide: [\n (val1, val2) => val1 / val2,\n (val1, val2) => BigNum.divide(val1, val2),\n ],\n\n miltiply: [\n (val1, val2) => val1 * val2,\n (val1, val2) => BigNum.multiply(val1, val2),\n ],\n };\n\n for(k in testsFuncs) {\n testF(testsFuncs[k], k);\n }\n },*/\n\n limit: 10000000,\n limit2: 100000000000000,\n}\n\nvar cnt = +readline();\nfor(var i = 0; i < cnt; i++) {\n var line = readline().split(' ').map(v=>+v);\n var diff = line[0] - line[1];\n var answer = BigNum.multiply(diff, Math.ceil(line[2] / 2));\n if(line[2] % 2) answer = BigNum.plus(answer, line[1]);\n print(BigNum.toInt(answer));\n}"}, {"source_code": "var cnt = +readline();\nfor(var i = 0; i < cnt; i++) {\n var line = readline().split(' ').map(v=>+v);\n var diff = line[0] - line[1];\n var answer = diff * Math.round(line[2] / 2);\n if(line[2] % 2) answer = answer + line[1];\n print(answer);\n}"}, {"source_code": "var BigNum = {\n\n plus: function plus(number1, number2, minus1, minus2) {\n\n if (typeof number1 === 'number' && Math.abs(number1) < BigNum.limit2 &&\n typeof number2 === 'number' && Math.abs(number2) < BigNum.limit2)\n\n return number1 + number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n if (minus1 === undefined) minus1 = ranks1.minus;\n if (minus2 === undefined) minus2 = ranks2.minus;\n\n\n if (!minus1) {\n if (minus2) {\n return BigNum.minus(ranks1, ranks2, false, false);\n }\n } else if (!minus2) {\n return BigNum.minus(ranks2, ranks1, false, false);\n } else {\n result.minus = true;\n }\n\n var maxRank = Math.max(ranks1.length, ranks2.length);\n for (var i = 0; i < maxRank; i++) {\n result[i] = (result[i] || 0)\n + (ranks1[i] || 0)\n + (ranks2[i] || 0);\n\n if (result[i] >= BigNum.limit) {\n result[i + 1] = 1;\n result[i] -= BigNum.limit;\n }\n }\n\n return result;\n },\n\n minus: function minus(number1, number2, minus1, minus2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit2 &&\n typeof number2 === 'number' && number2 < BigNum.limit2)\n\n return number1 - number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n if (minus1 === undefined) minus1 = ranks1.minus;\n if (minus2 === undefined) minus2 = ranks2.minus;\n\n\n if (!minus1) {\n if (minus2) {\n return BigNum.plus(ranks1, ranks2, false, false);\n }\n } else if (!minus2) {\n result = BigNum.plus(ranks1, ranks2, false, false);\n result.minus = true;\n return result;\n } else {\n return BigNum.minus(ranks2, ranks1, false, false);\n }\n\n var maxRank = Math.max(ranks1.length - 1, ranks2.length - 1);\n for (var i = maxRank; i >= 0; i--) {\n\n result[i] = (ranks1[i] || 0)\n - (ranks2[i] || 0);\n\n if (result[i] < 0) {\n if (result.minus === undefined) {\n result.minus = true;\n result[i] = -result[i];\n\n var swap = ranks1;\n ranks1 = ranks2;\n ranks2 = swap;\n } else {\n var j = i;\n do {\n result[j + 1] -= 1;\n result[j] += BigNum.limit;\n } while (result[++j] < 0);\n }\n } else if (result.minus === undefined && result[i] > 0) {\n result.minus = false;\n }\n }\n\n while(result[result.length - 1] === 0) {\n result.pop();\n }\n if (result.length < 3) {\n return BigNum.toInt(result);\n }\n\n return result;\n },\n\n multiply: function multiply(number1, number2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit &&\n typeof number2 === 'number' && number2 < BigNum.limit)\n\n return number1 * number2;\n\n var result = [];\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n for (var i = 0; i < ranks1.length; i++) {\n for (var j = 0; j < ranks2.length; j++) {\n var rank = i + j;\n var prod = ranks1[i] * ranks2[j];\n if (prod > BigNum.limit) {\n result[rank] = (result[rank] || 0)\n + prod % BigNum.limit;\n result[rank + 1] = (result[rank + 1] || 0)\n + Math.floor(prod / BigNum.limit);\n } else {\n result[rank] = (result[rank] || 0)\n + prod;\n }\n }\n }\n\n for (i = 0; i < result.length; i++) {\n if (result[i] > BigNum.limit) {\n result[i] -= BigNum.limit;\n result[i + 1] = (result[i + 1] || 0) + 1;\n }\n }\n\n result.minus = (ranks1.minus != ranks2.minus);\n return result;\n },\n\n divide: function divide(number1, number2) {\n\n if (typeof number1 === 'number' && number1 < BigNum.limit2 &&\n typeof number2 === 'number' && number2 < BigNum.limit2)\n\n return number1 / number2;\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n var result = BigNum.toStr(ranks1) / BigNum.toStr(ranks2);\n return result;\n },\n\n ////////////////////////////////////////////////\n // comparision\n more: function more(number1, number2) {\n return BigNum.compare(number1, number2) > 0;\n },\n\n less: function less(number1, number2) {\n return BigNum.compare(number1, number2) < 0;\n },\n\n equal: function equal(number1, number2) {\n return BigNum.compare(number1, number2) === 0;\n },\n\n max: function max(number1, number2) {\n if(number2 !== undefined) {\n return BigNum.more(number1, number2) ? number1 : number2;\n }\n\n var numberArr = number1;\n var max = numberArr[0];\n\n for(var i = 1; i < numberArr.length; i++) {\n if(BigNum.more(numberArr[i], max)) {\n max = numberArr[i];\n }\n }\n\n return max;\n },\n\n min: function max(number1, number2) {\n if(number2 !== undefined) {\n return BigNum.compare(number1, number2) < 0 ? number1 : number2;\n }\n\n var numberArr = number1;\n var min = numberArr[0];\n\n for(var i = 1; i < numberArr.length; i++) {\n if(BigNum.compare(numberArr[i], min) < 0) {\n min = numberArr[i]\n }\n }\n\n return min;\n },\n\n compare: function compareNumbers(number1, number2) {\n var numberTypes = [typeof number1, typeof number2];\n\n if(numberTypes[0] === numberTypes[1]) {\n if(numberTypes[0] === 'number') {\n return number1 - number2;\n }\n } else {\n if (numberTypes[1] === 'number') {\n if (number1[2]) {\n return 1;\n }\n } else if (numberTypes[0] === 'number') {\n if(number2[2]) {\n return -1;\n }\n }\n }\n\n var ranks1 = BigNum._getRanks(number1);\n var ranks2 = BigNum._getRanks(number2);\n\n var diff;\n\n if(ranks1.minus !== ranks2.minus) {\n return !ranks1.minus > !ranks2.minus ? 1 : -1\n } else if(diff = ranks1.length - ranks2.length) {\n return diff;\n }\n\n for (var i = ranks1.length - 1; i >= 0; i--) {\n if(diff = ranks1[i] - ranks2[i]) {\n return diff;\n }\n }\n\n return 0;\n },\n\n toInt: function (number) {\n if (typeof number === 'object') {\n if(!number.length) return 0;\n else return +BigNum.toStr(number);\n }\n else return +number;\n },\n\n toStr: function (number) {\n\n if (typeof number === 'string') return number;\n else if(typeof number === 'number') return '' + number;\n\n var str = '';\n while(number.length && !number[number.length - 1]) number.pop();\n\n if(!number.length) return '0';\n\n for (var i = 0; i < number.length - 1; i++) {\n str = ('000000' + number[i]).substr(-7) + str;\n }\n str = number[i] + str;\n return (number.minus ? '-' : '') + str;\n },\n\n getBig: function (number) {\n if (typeof number === 'string') {\n if (number.length < 16) return +number;\n }\n\n return BigNum._getRanks(number);\n },\n\n _getRanks: function (number) {\n\n if (typeof number === 'object') {\n return number;\n } else if (typeof number === 'number') {\n number = '' + number;\n }\n\n var ranks = [];\n if (number[0] === '-') {\n ranks.minus = true;\n number = number.substr(1);\n }\n\n if (number.length > 7) {\n\n number = '' + number;\n for (var i = 7; i <= number.length; i += 7) {\n ranks.push(+number.substr(-i, 7));\n }\n\n var rest = number.length % 7;\n if (rest) {\n ranks.push(+number.substr(0, rest));\n }\n\n } else {\n ranks.push(+number);\n }\n\n if (ranks[ranks.length - 1] < 0) {\n ranks[ranks.length - 1] = -ranks[ranks.length - 1];\n ranks.minus = true;\n }\n\n return ranks;\n },\n\n rand: function getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n },\n\n /*runTests: function tests(count = 10) {\n var correct = 0;\n var values = [];\n for(var i = 0; i < count; i++) {\n var val1 = BigNum.rand(-999999999999999, 999999999999999);\n var val2 = BigNum.rand(-999999999999999, 999999999999999);\n\n var resBn = BigNum.plus(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = val1 + val2;\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' + ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.minus(val1, val2);\n resBnInt = BigNum.toInt(resBn);\n res = val1 - val2;\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' - ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.divide(val1, val2);\n resBnInt = Math.round(resBn, 4);\n res = Math.round(val1 / val2, 4);\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' / ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.more(val1, val2);\n res = val1 > val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' > ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.less(val1, val2);\n res = val1 < val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' < ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.equal(val1, val2);\n res = val1 === val2;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' === ' + val2);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n resBn = BigNum.equal(val1, val1);\n res = val1 === val1;\n\n if(resBn !== res) {\n console.log('!!! ' + val1 + ' === ' + val1);\n console.log(' Bn: ' + resBn);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.max(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.max(val1, val2);\n\n if(resBnInt !== res) {\n console.log('!!! max ' + val1 + ', ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.min(val1, val2);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.min(val1, val2);\n\n if(resBnInt !== res) {in\n console.log('!!! min ' + val1 + ', ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var val3 = BigNum.rand(-999999999999999, 999999999999999);\n var resBn = BigNum.max([val1, val2, val3]);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.max(val1, val2, val3);\n\n if(resBnInt !== res) {\n console.log('!!! max ' + val1 + ', ' + val2 + ', ' + val3);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n var resBn = BigNum.min([val1, val2, val3]);\n var resBnInt = BigNum.toInt(resBn);\n var res = Math.min(val1, val2, val3);\n\n if(resBnInt !== res) {\n console.log('!!! min ' + val1 + ', ' + val2 + ', ' + val3);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n val1 = BigNum.rand(-99999999, 99999999);\n val2 = BigNum.rand(-9999999, 9999999);\n\n resBn = BigNum.multiply(val1, val2);\n resBnInt = BigNum.toInt(resBn);\n res = Math.round(val1 * val2, 4);\n\n if(resBnInt !== res) {\n console.log('!!! ' + val1 + ' * ' + val2);\n console.log(' Bn: ' + resBnInt);\n console.log(' Nm: ' + res);\n } else {\n correct++;\n }\n\n }\n console.log('correct:' + correct);\n\n\n },*/\n /*runTimeTests: function timeTests(count = 10000, ranks = 15) {\n\n var max = Math.pow(10, ranks);\n\n var values = [];\n for(var i = 0; i < count; i++) {\n var val1 = BigNum.rand(-max, max);\n var val2 = BigNum.rand(-max, max);\n\n values.push([val1, val2]);\n }\n\n var testF = function (funcs, operation) {\n var results = [];\n for(var f = 0; f < 2; f++) {\n var func = funcs[f];\n var t = performance.now();\n for(var i = 0; i < count; i++) {\n res = func(values[i][0], values[i][1]);\n }\n results[f] = Math.floor(performance.now() - t);\n }\n\n console.log('test ' + operation + ': diff ' + (results[1] - results[0]));\n }\n\n var testsFuncs = {\n plus: [\n (val1, val2) => val1 + val2,\n (val1, val2) => BigNum.plus(val1, val2),\n ],\n\n minus: [\n (val1, val2) => val1 - val2,\n (val1, val2) => BigNum.minus(val1, val2),\n ],\n\n divide: [\n (val1, val2) => val1 / val2,\n (val1, val2) => BigNum.divide(val1, val2),\n ],\n\n miltiply: [\n (val1, val2) => val1 * val2,\n (val1, val2) => BigNum.multiply(val1, val2),\n ],\n };\n\n for(k in testsFuncs) {\n testF(testsFuncs[k], k);\n }\n },*/\n\n limit: 10000000,\n limit2: 100000000000000,\n}\n\nvar cnt = +readline();\nfor(var i = 0; i < cnt; i++) {\n var line = readline().split(' ').map(v=>+v);\n var diff = line[0] - line[1];\n var answer = BigNum.multiply(diff, Math.ceil(line[2] / 2));\n if(line[2] % 2) answer = BigNum.plus(answer, line[1]);\n print(BigNum.toStr(answer));\n}"}, {"source_code": "solve();\n\nfunction solve() {\n var t = Number(readline()), line, p1, p2, s1, res, d, o, z;\n for (;t--;) {\n line = readline().split(' ').map(Number);\n z = '';\n p1 = (line[0] - line[1]);\n if (p1 < 0) {\n z = '-';\n p1 = -p1;\n }\n p2 = (line[2] >> 1);\n s1 = ((line[2] & 1) * line[0]);\n if (!p1 || line[2] === 1) {\n print(s1);\n continue;\n }\n if (z) {\n s1 = -s1;\n }\n res = [];\n while (p1) {\n o = p1 % 1000;\n res.push(o);\n p1 = (p1 - o) / 1000;\n }\n d = 0;\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] * p2 + d;\n o = res[i] % 1000;\n d = (res[i] - o) / 1000;\n res[i] = o;\n }\n while (d) {\n o = d % 1000;\n res.push(o);\n d = (d - o) / 1000;\n }\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] + s1 + d;\n o = res[i] % 1000;\n d = (res[i] - o) / 1000;\n res[i] = o;\n }\n while (d) {\n o = d % 1000;\n res.push(o);\n d = (d - o) / 1000;\n }\n print(z + res.reverse().join(''));\n /*a = line[0];\n b = line[1];\n k = line[2];\n print ('' + a + b + k);\n print((a - b) * (k >> 1) + (k & 1) * a);*/\n }\n}"}, {"source_code": "solve();\n\nvar D = 10000, DL = 4;\n\nfunction LongNumber(n) {\n this.zero = [''];\n for (var i = 1; i < DL; ++i) {\n this.zero[i] = this.zero[i - 1] + '0';\n }\n this.value = [];\n if (!n) {\n this.value.push(0);\n }\n while (n) {\n this.value.push(n % D);\n n = Math.floor(n / D);\n }\n \n this.toString = function() {\n var value = this.value, i, result = '', sc;\n for (i = value.length - 1; i && !value[i]; --i);\n result += value[i--];\n for(; ~i; --i) {\n sc = String(value[i]);\n result += this.zero[DL - sc.length] + sc;\n }\n return result;\n };\n this.plus = function(n) {\n if (typeof n === 'number') {\n n = new LongNumber(n).value;\n }\n var value = this.value, d = 0, i;\n while(value.length < n.length) {\n value.push(0);\n }\n var l = Math.min(value.length, n.length),\n L = Math.max(value.length, n.length);\n for(i = 0; i < l; ++i) {\n value[i] += n[i] + d;\n d = Math.floor(value[i] / D);\n value[i] %= D;\n }\n for(; i < L && d; ++i) {\n value[i] += d;\n d = Math.floor(value[i] / D);\n value[i] %= D;\n }\n while (d) {\n value.push(d % D);\n d = Math.floor(d / D);\n }\n return this;\n };\n \n return this;\n}\n\nfunction solve() {\n var ln = new LongNumber();\n for (var i = 0; i < 10000; ++i) {\n ln.plus(1000000000);\n }\n print(ln.toString());\n}"}, {"source_code": "solve();\n\nfunction solve() {\n var t = Number(readline()), line, a, b, k;\n for (;t--;) {\n line = readline().split(' ').map(Number);\n a = line[0];\n b = line[1];\n k = line[2];\n print((a - b) * (k >> 1) + (k & 1) * a);\n }\n}"}, {"source_code": "solve();\n\nvar D = 10000, DL = 4;\n\nfunction LongNumber(n) {\n this.zero = [''];\n for (var i = 1; i < DL; ++i) {\n this.zero[i] = this.zero[i - 1] + '0';\n }\n this.value = [];\n if (!n) {\n this.value.push(0);\n }\n while (n) {\n this.value.push(n % D);\n n = Math.floor(n / D);\n }\n \n this.toString = function() {\n var value = this.value, i, result = '', sc;\n for (i = value.length - 1; i && !value[i]; --i);\n result += value[i--];\n for(; ~i; --i) {\n sc = String(value[i]);\n result += this.zero[DL - sc.length] + sc;\n }\n return result;\n };\n this.plus = function(n) {\n if (typeof n === 'number') {\n n = new LongNumber(n).value;\n }\n var value = this.value, d = 0, i;\n while(value.length < n.length) {\n value.push(0);\n }\n var l = Math.min(value.length, n.length),\n L = Math.max(value.length, n.length);\n for(i = 0; i < l; ++i) {\n value[i] += n[i] + d;\n d = Math.floor(value[i] / D);\n value[i] %= D;\n }\n for(; i < L && d; ++i) {\n value[i] += d;\n d = Math.floor(value[i] / D);\n value[i] %= D;\n }\n while (d) {\n value.push(d % D);\n d = Math.floor(d / D);\n }\n return this;\n };\n \n return this;\n}\n\nfunction solve() {\n var ln = new LongNumber();\n for (var i = 0; i < 100; ++i) {\n ln.plus(100000000);\n }\n print(ln.toString());\n}"}, {"source_code": "solve();\n\nfunction solve() {\n var t = Number(readline()), line, p1, p2, s1, res, d, o, z, bs, zs, sign;\n for (;t--;) {\n line = readline().split(' ').map(Number);\n z = '';\n p1 = (line[0] - line[1]);\n if (p1 < 0) {\n z = '-';\n p1 = -p1;\n }\n p2 = (line[2] >> 1);\n s1 = ((line[2] & 1) * line[0]);\n if (!p1 || line[2] === 1) {\n print(s1);\n continue;\n }\n zs = '';\n if (s1 < 0) {\n zs = '-';\n s1 = -s1;\n }\n res = [];\n while (p1) {\n o = p1 % 1000;\n res.push(o);\n p1 = (p1 - o) / 1000;\n }\n bs = [];\n while (s1) {\n o = s1 % 1000;\n bs.push(o);\n s1 = (s1 - o) / 1000;\n }\n d = 0;\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] * p2 + d;\n o = res[i] % 1000;\n d = (res[i] - o) / 1000;\n res[i] = o;\n }\n while (d) {\n o = d % 1000;\n res.push(o);\n d = (d - o) / 1000;\n }\n if (z === zs) {\n while (res.length < bs.length) {\n res.push(0);\n }\n while (bs.length < res.length) {\n bs.push(0);\n }\n for (var i = 0; i < res.length; ++i) {\n res[i] = res[i] + bs[i] + d;\n o = res[i] % 1000;\n d = (res[i] - o) / 1000;\n res[i] = o;\n }\n while (d) {\n o = d % 1000;\n res.push(o);\n d = (d - o) / 1000;\n }\n } else {\n sign = 0;\n if (res.length < bs.length) {\n sign = -1;\n } else if (res.length > bs.length) {\n sign = 1;\n } else {\n for (i = res.length - 1; i >= 0; --i) {\n if (res[i] < bs[i]) {\n sign = -1;\n break;\n } else if (res[i] > bs[i]) {\n sign = 1;\n break;\n }\n }\n }\n if (!sign) {\n print(0);\n continue\n }\n if (sign === -1) {\n z = zs;\n p1 = res;\n res = bs;\n bs = p1;\n }\n for (i = 0; i < res.length; ++i) {\n if (res[i] + d < bs[i]) {\n res[i] = res[i] + d + 1000 - bs[i];\n d = -1;\n } else {\n res[i] = res[i] + d - bs[i];\n d = 0;\n }\n }\n while (res[res.length - 1] === 0) {\n res.pop();\n }\n }\n print(z + res.reverse().join(''));\n /*a = line[0];\n b = line[1];\n k = line[2];\n print ('' + a + b + k);\n print((a - b) * (k >> 1) + (k & 1) * a);*/\n }\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 ≤ k ≤ 106). 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 — 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 С++. 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": "print(function(k, s) {\n\n\tvar i, c = 0,\n\t\tans = 0,\n\t\tl = s.length,\n\t\tdp = [1];\n\n\tfor (i = 1; i <= l; i++)\n\t\tdp.push(0);\n\n\n\tfor (i = 0; i < l; i++) {\n\t\tif (s[i] === '1') c++;\n\t\tif (c >= k) ans += dp[c - k];\n\t\tdp[c]++;\n\t}\n\n\n\treturn ans;\n\n}(+readline(), readline()));"}, {"source_code": "\n\nvar k = +readline();\nvar s = readline();\nvar aa =[];\naa[0] = 0;\nfor(var i=1; i<=1e6; i++){\n\taa[i]=aa[i-1]+i;\n}\n\nif(k===0){\n\tprint( s.split(/1+/g).map(function(v){\n\t\treturn aa[v.length];\n\t}).reduce(function(a, b){ return a+b;}) );\n\tquit();\n}\n\nvar low = 0;\nvar high = 0;\nvar c = 0;\nvar ans = 0;\n// while(true){\n\tfor(; high= k) ans += dp[c - k];\n\t\tdp[c]++;\n\t}\n\n\treturn ans;\n}(+readline(), readline()));"}, {"source_code": "\nprint(function(k, s) {\n\tif (k === 0) {\n\t\tvar a = [0];\n\t\tfor (var i = 1; i <= 1e6; i++) {\n\t\t\ta.push( a[i - 1] + i );\n\t\t}\n\t\treturn s.split(/1+/g).map(function(v) {\n\t\t\treturn a[v.length];\n\t\t}).reduce(function(a, b) {\n\t\t\treturn a + b;\n\t\t});\n\t}\n\n\tvar low = 0;\n\tvar high = 0;\n\tvar c = 0;\n\tvar ans = 0;\n\n\twhile (high < s.length) {\n\n\t\tif (s[high] === '1')\n\t\t\tc++;\n\n\t\tif (c === k) {\n\t\t\tvar x1 = 1;\n\t\t\twhile (s[low] === '0') {\n\t\t\t\tx1++;\n\t\t\t\tlow++;\n\t\t\t}\n\t\t\tlow++;\n\t\t\tc--;\n\n\t\t\tvar x2 = 1;\n\t\t\twhile (s[high + 1] === '0') {\n\t\t\t\tx2++;\n\t\t\t\thigh++;\n\t\t\t}\n\n\t\t\tans += x1 * x2;\n\t\t}\n\t\thigh++;\n\t}\n\n\treturn ans;\n\n}(+readline(), readline()));"}, {"source_code": "print(function(k, s) {\n\n\tvar i, c = 0,\n\t\tans = 0,\n\t\tl = s.length,\n\t\tdp = [1];\n\n\tfor (i = 1; i <= l; i++)\n\t\tdp.push(0);\n\n\n\tfor (i = 0; i < l; i++) {\n\t\tif (s[i] === '1') c++;\n\t\tif (c >= k) ans += dp[c - k];\n\t\tdp[c]++;\n\t}\n\n\n\treturn ans;\n\n}(+readline(), readline()));\n"}, {"source_code": "var k = +readline();\nvar s = readline();\nvar aa =[];\naa[0] = 0;\nfor(var i=1; i<=1e6; i++){\n\taa[i]=aa[i-1]+i;\n}\n\nif(k===0){\n\tprint( s.split(/1+/g).map(function(v){\n\t\treturn aa[v.length];\n\t}).reduce(function(a, b){ return a+b;}) );\n\tquit();\n}\n\nvar low = 0;\nvar high = 0;\nvar c = 0;\nvar ans = 0;\n// while(true){\n\tfor(; high= k) ans += dp[c - k];\n\t\tdp[c]++;\n\t}\n\n\n\treturn ans;\n\n}(+readline(), readline()));\n"}], "negative_code": [{"source_code": "var k = +readline();\nvar s = readline();\n\nvar low = 0;\nvar high = 0;\nvar c = 0;\nvar ans = 0;\n// while(true){\n\tfor(; high= k) ans += dp[c - k];\n\t\tdp[c]++;\n\t}\n\n\n\treturn ans;\n\n}(+readline(), readline()));"}, {"source_code": "var k = +readline();\nvar s = readline();\nvar aa =[];\naa[0] = 0;\nfor(var i=1; i<1e6; i++){\n\taa[i]=aa[i-1]+i;\n}\n\nif(k===0){\n\tprint( s.split(/1+/g).map(function(v){\n\t\treturn aa[v.length];\n\t}).reduce(function(a, b){ return a+b;}) );\n\tquit();\n}\n\nvar low = 0;\nvar high = 0;\nvar c = 0;\nvar ans = 0;\n// while(true){\n\tfor(; high1){\n\t\t\ta*=v;\n\t\t\tv--;\n\t\t}\n\t\treturn a;\n\t}).reduce(function(a, b){ return a+b;}) );\n\tquit();\n}\n\nvar low = 0;\nvar high = 0;\nvar c = 0;\nvar ans = 0;\n// while(true){\n\tfor(; high 0) {\n\t used[a[i]] -= 1;\n\t continue;\n\t }\n\t r.push(a[i]);\n\t for (var j = 0; j < r.length; j++) {\n\t var x = Prelude_1.gcd(r[j], a[i]);\n\t used[x] = used[x] || 0;\n\t used[x] += (j < r.length) ? 2 : 1;\n\t }\n\t}\n\tprint(r.join(\" \"));\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction min(a, b) {\n\t return a < b ? a : b;\n\t}\n\texports.min = min;\n\tfunction max(a, b) {\n\t return a < b ? b : a;\n\t}\n\texports.max = max;\n\tfunction curry(f) {\n\t return function (x) { return function (y) { return f(x, y); }; };\n\t}\n\texports.curry = curry;\n\tfunction uncurry(f) {\n\t return function (x, y) { return f(x)(y); };\n\t}\n\texports.uncurry = uncurry;\n\tfunction id(x) {\n\t return x;\n\t}\n\texports.id = id;\n\tfunction constant(x) {\n\t return function (_) { return x; };\n\t}\n\texports.constant = constant;\n\tfunction flip(f) {\n\t return function (y) { return function (x) { return f(x)(y); }; };\n\t}\n\texports.flip = flip;\n\tfunction flip2(f) {\n\t return function (y, x) { return f(x, y); };\n\t}\n\texports.flip2 = flip2;\n\tfunction compose(g, f) {\n\t return function (x) { return g(f(x)); };\n\t}\n\texports.compose = compose;\n\tfunction gcd(a, b) {\n\t var r = a % b;\n\t while (r !== 0) {\n\t a = b;\n\t b = r;\n\t r = a % b;\n\t }\n\t return b;\n\t}\n\texports.gcd = gcd;\n\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(1);\n\tfunction add(xs, ys) {\n\t return xs.concat(ys);\n\t}\n\texports.add = add;\n\tfunction head(xs) {\n\t return xs[0];\n\t}\n\texports.head = head;\n\tfunction last(xs) {\n\t return xs[xs.length - 1];\n\t}\n\texports.last = last;\n\tfunction tail(xs) {\n\t return xs.slice(1);\n\t}\n\texports.tail = tail;\n\tfunction init(xs) {\n\t return xs.slice(0, xs.length - 1);\n\t}\n\texports.init = init;\n\tfunction map(f, xs) {\n\t var result = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t result[i] = f(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.map = map;\n\tfunction reverse(xs) {\n\t return xs.slice().reverse();\n\t}\n\texports.reverse = reverse;\n\tfunction intersperse(x, xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = new Array(xs.length + xs.length - 1);\n\t for (var i = 0; i + 1 < xs.length; i++) {\n\t result[i + i] = xs[i];\n\t result[i + i + 1] = x;\n\t }\n\t result[result.length - 1] = xs[xs.length - 1];\n\t return result;\n\t}\n\texports.intersperse = intersperse;\n\tfunction intercalate(xs, xss) {\n\t return concat(intersperse(xs, xss));\n\t}\n\texports.intercalate = intercalate;\n\tfunction foldl(f, initial, xs) {\n\t var result = initial;\n\t for (var i = 0; i < xs.length; i++) {\n\t result = f(result, xs[i]);\n\t }\n\t return result;\n\t}\n\texports.foldl = foldl;\n\tfunction foldr(f, initial, xs) {\n\t var result = initial;\n\t for (var i = xs.length - 1; i >= 0; i--) {\n\t result = f(xs[i], result);\n\t }\n\t return result;\n\t}\n\texports.foldr = foldr;\n\tfunction concat(xss) {\n\t var total = sum(map(function (xs) { return xs.length; }, xss));\n\t var result = new Array(total);\n\t var m = 0;\n\t for (var i = 0; i < xss.length; i++) {\n\t var xs = xss[i];\n\t for (var j = 0; j < xs.length; j++) {\n\t result[m++] = xs[j];\n\t }\n\t }\n\t return result;\n\t}\n\texports.concat = concat;\n\tfunction sum(xs) {\n\t var result = 0;\n\t for (var i = 0; i < xs.length; i++) {\n\t result += xs[i];\n\t }\n\t return result;\n\t}\n\texports.sum = sum;\n\tfunction product(xs) {\n\t var result = 1;\n\t for (var i = 0; i < xs.length; i++) {\n\t result *= xs[i];\n\t }\n\t return result;\n\t}\n\texports.product = product;\n\tfunction maximum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result < xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.maximum = maximum;\n\tfunction minimum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result > xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.minimum = minimum;\n\tfunction replicate(n, x) {\n\t var result = new Array(n);\n\t for (var i = 0; i < result.length; i++) {\n\t result[i] = x;\n\t }\n\t return result;\n\t}\n\texports.replicate = replicate;\n\tfunction take(n, xs) {\n\t return xs.slice(0, n);\n\t}\n\texports.take = take;\n\tfunction drop(n, xs) {\n\t return xs.slice(n);\n\t}\n\texports.drop = drop;\n\tfunction splitAt(n, xs) {\n\t return [take(n, xs), drop(n, xs)];\n\t}\n\texports.splitAt = splitAt;\n\tfunction takeWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(0, i);\n\t }\n\t }\n\t return xs.slice();\n\t}\n\texports.takeWhile = takeWhile;\n\tfunction dropWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(i);\n\t }\n\t }\n\t return [];\n\t}\n\texports.dropWhile = dropWhile;\n\tfunction group(xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = [];\n\t var last = [xs[0]];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (last[0] === xs[i]) {\n\t last.push(xs[i]);\n\t }\n\t else {\n\t result.push(last);\n\t last = [xs[i]];\n\t }\n\t }\n\t result.push(last);\n\t return result;\n\t}\n\texports.group = group;\n\tfunction filter(f, xs) {\n\t var result = [];\n\t for (var i = 0; i < xs.length; i++) {\n\t if (f(xs[i]))\n\t result.push(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.filter = filter;\n\tfunction zip(xs, ys) {\n\t var n = Prelude_1.min(xs.length, ys.length);\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = [xs[i], ys[i]];\n\t }\n\t return result;\n\t}\n\texports.zip = zip;\n\tfunction unzip(xs) {\n\t var r1 = new Array(xs.length);\n\t var r2 = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t r1[i] = xs[i][0];\n\t r2[i] = xs[i][1];\n\t }\n\t return [r1, r2];\n\t}\n\texports.unzip = unzip;\n\tfunction range(from, to) {\n\t var result = Array(to - from + 1);\n\t for (var i = from; i <= to; i++) {\n\t result[i - from] = i;\n\t }\n\t return result;\n\t}\n\texports.range = range;\n\tfunction copy(xs) {\n\t return xs.slice(0);\n\t}\n\texports.copy = copy;\n\tfunction apply_permutation(p, xs) {\n\t var n = xs.length;\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = xs[p[i]];\n\t }\n\t return result;\n\t}\n\texports.apply_permutation = apply_permutation;\n\tfunction next_permutation(p) {\n\t var n = p.length;\n\t if (n < 2)\n\t return null;\n\t var r = copy(p);\n\t var k = n - 2;\n\t for (; k >= 0 && r[k] >= r[k + 1]; k--)\n\t ;\n\t if (k < 0)\n\t return null;\n\t for (var i = k + 1, j = n - 1; i < j; i++, j--) {\n\t var t_1 = r[i];\n\t r[i] = r[j];\n\t r[j] = t_1;\n\t }\n\t var next = k + 1;\n\t for (; r[next] <= r[k]; next++)\n\t ;\n\t var t = r[k];\n\t r[k] = r[next];\n\t r[next] = t;\n\t return r;\n\t}\n\texports.next_permutation = next_permutation;\n\n\n/***/ }\n/******/ ]);"}], "negative_code": [{"source_code": "/******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n\n\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(1);\n\tvar List = __webpack_require__(2);\n\treadline();\n\tvar a = List.map(parseInt, readline().split(' '));\n\ta.sort(function (a, b) { return b - a; });\n\tvar used = {};\n\tvar r = [];\n\tfor (var i = 0; i < a.length && r.length * r.length < a.length; i++) {\n\t var k = used[a[i]];\n\t if (k > 0) {\n\t used[a[i]] -= 1;\n\t continue;\n\t }\n\t r.push(a[i]);\n\t for (var j = 0; j < r.length; j++) {\n\t var x = Prelude_1.gcd(r[j], a[i]);\n\t used[x] = used[x] || 0;\n\t used[x] += 1;\n\t }\n\t}\n\tprint(r.join(\" \"));\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction min(a, b) {\n\t return a < b ? a : b;\n\t}\n\texports.min = min;\n\tfunction max(a, b) {\n\t return a < b ? b : a;\n\t}\n\texports.max = max;\n\tfunction curry(f) {\n\t return function (x) { return function (y) { return f(x, y); }; };\n\t}\n\texports.curry = curry;\n\tfunction uncurry(f) {\n\t return function (x, y) { return f(x)(y); };\n\t}\n\texports.uncurry = uncurry;\n\tfunction id(x) {\n\t return x;\n\t}\n\texports.id = id;\n\tfunction constant(x) {\n\t return function (_) { return x; };\n\t}\n\texports.constant = constant;\n\tfunction flip(f) {\n\t return function (y) { return function (x) { return f(x)(y); }; };\n\t}\n\texports.flip = flip;\n\tfunction flip2(f) {\n\t return function (y, x) { return f(x, y); };\n\t}\n\texports.flip2 = flip2;\n\tfunction compose(g, f) {\n\t return function (x) { return g(f(x)); };\n\t}\n\texports.compose = compose;\n\tfunction gcd(a, b) {\n\t var r = a % b;\n\t while (r !== 0) {\n\t a = b;\n\t b = r;\n\t r = a % b;\n\t }\n\t return b;\n\t}\n\texports.gcd = gcd;\n\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(1);\n\tfunction add(xs, ys) {\n\t return xs.concat(ys);\n\t}\n\texports.add = add;\n\tfunction head(xs) {\n\t return xs[0];\n\t}\n\texports.head = head;\n\tfunction last(xs) {\n\t return xs[xs.length - 1];\n\t}\n\texports.last = last;\n\tfunction tail(xs) {\n\t return xs.slice(1);\n\t}\n\texports.tail = tail;\n\tfunction init(xs) {\n\t return xs.slice(0, xs.length - 1);\n\t}\n\texports.init = init;\n\tfunction map(f, xs) {\n\t var result = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t result[i] = f(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.map = map;\n\tfunction reverse(xs) {\n\t return xs.slice().reverse();\n\t}\n\texports.reverse = reverse;\n\tfunction intersperse(x, xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = new Array(xs.length + xs.length - 1);\n\t for (var i = 0; i + 1 < xs.length; i++) {\n\t result[i + i] = xs[i];\n\t result[i + i + 1] = x;\n\t }\n\t result[result.length - 1] = xs[xs.length - 1];\n\t return result;\n\t}\n\texports.intersperse = intersperse;\n\tfunction intercalate(xs, xss) {\n\t return concat(intersperse(xs, xss));\n\t}\n\texports.intercalate = intercalate;\n\tfunction foldl(f, initial, xs) {\n\t var result = initial;\n\t for (var i = 0; i < xs.length; i++) {\n\t result = f(result, xs[i]);\n\t }\n\t return result;\n\t}\n\texports.foldl = foldl;\n\tfunction foldr(f, initial, xs) {\n\t var result = initial;\n\t for (var i = xs.length - 1; i >= 0; i--) {\n\t result = f(xs[i], result);\n\t }\n\t return result;\n\t}\n\texports.foldr = foldr;\n\tfunction concat(xss) {\n\t var total = sum(map(function (xs) { return xs.length; }, xss));\n\t var result = new Array(total);\n\t var m = 0;\n\t for (var i = 0; i < xss.length; i++) {\n\t var xs = xss[i];\n\t for (var j = 0; j < xs.length; j++) {\n\t result[m++] = xs[j];\n\t }\n\t }\n\t return result;\n\t}\n\texports.concat = concat;\n\tfunction sum(xs) {\n\t var result = 0;\n\t for (var i = 0; i < xs.length; i++) {\n\t result += xs[i];\n\t }\n\t return result;\n\t}\n\texports.sum = sum;\n\tfunction product(xs) {\n\t var result = 1;\n\t for (var i = 0; i < xs.length; i++) {\n\t result *= xs[i];\n\t }\n\t return result;\n\t}\n\texports.product = product;\n\tfunction maximum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result < xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.maximum = maximum;\n\tfunction minimum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result > xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.minimum = minimum;\n\tfunction replicate(n, x) {\n\t var result = new Array(n);\n\t for (var i = 0; i < result.length; i++) {\n\t result[i] = x;\n\t }\n\t return result;\n\t}\n\texports.replicate = replicate;\n\tfunction take(n, xs) {\n\t return xs.slice(0, n);\n\t}\n\texports.take = take;\n\tfunction drop(n, xs) {\n\t return xs.slice(n);\n\t}\n\texports.drop = drop;\n\tfunction splitAt(n, xs) {\n\t return [take(n, xs), drop(n, xs)];\n\t}\n\texports.splitAt = splitAt;\n\tfunction takeWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(0, i);\n\t }\n\t }\n\t return xs.slice();\n\t}\n\texports.takeWhile = takeWhile;\n\tfunction dropWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(i);\n\t }\n\t }\n\t return [];\n\t}\n\texports.dropWhile = dropWhile;\n\tfunction group(xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = [];\n\t var last = [xs[0]];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (last[0] === xs[i]) {\n\t last.push(xs[i]);\n\t }\n\t else {\n\t result.push(last);\n\t last = [xs[i]];\n\t }\n\t }\n\t result.push(last);\n\t return result;\n\t}\n\texports.group = group;\n\tfunction filter(f, xs) {\n\t var result = [];\n\t for (var i = 0; i < xs.length; i++) {\n\t if (f(xs[i]))\n\t result.push(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.filter = filter;\n\tfunction zip(xs, ys) {\n\t var n = Prelude_1.min(xs.length, ys.length);\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = [xs[i], ys[i]];\n\t }\n\t return result;\n\t}\n\texports.zip = zip;\n\tfunction unzip(xs) {\n\t var r1 = new Array(xs.length);\n\t var r2 = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t r1[i] = xs[i][0];\n\t r2[i] = xs[i][1];\n\t }\n\t return [r1, r2];\n\t}\n\texports.unzip = unzip;\n\tfunction range(from, to) {\n\t var result = Array(to - from + 1);\n\t for (var i = from; i <= to; i++) {\n\t result[i - from] = i;\n\t }\n\t return result;\n\t}\n\texports.range = range;\n\tfunction copy(xs) {\n\t return xs.slice(0);\n\t}\n\texports.copy = copy;\n\tfunction apply_permutation(p, xs) {\n\t var n = xs.length;\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = xs[p[i]];\n\t }\n\t return result;\n\t}\n\texports.apply_permutation = apply_permutation;\n\tfunction next_permutation(p) {\n\t var n = p.length;\n\t if (n < 2)\n\t return null;\n\t var r = copy(p);\n\t var k = n - 2;\n\t for (; k >= 0 && r[k] >= r[k + 1]; k--)\n\t ;\n\t if (k < 0)\n\t return null;\n\t for (var i = k + 1, j = n - 1; i < j; i++, j--) {\n\t var t_1 = r[i];\n\t r[i] = r[j];\n\t r[j] = t_1;\n\t }\n\t var next = k + 1;\n\t for (; r[next] <= r[k]; next++)\n\t ;\n\t var t = r[k];\n\t r[k] = r[next];\n\t r[next] = t;\n\t return r;\n\t}\n\texports.next_permutation = next_permutation;\n\n\n/***/ }\n/******/ ]);"}], "src_uid": "71dc07f0ea8962f23457af1d6509aeee"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that $$$a_1 < a_2 < \\dots < a_n$$$ holds.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\leq a_i \\leq 10^9$$$) — the elements of the array.", "output_spec": "For each test case, output \"YES\" (without quotes) if the array satisfies the condition, and \"NO\" (without quotes) 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": ["3\n\n4\n\n1 1 1 1\n\n5\n\n8 7 1 3 4\n\n1\n\n5"], "sample_outputs": ["NO\nYES\nYES"], "notes": "NoteIn the first test case any rearrangement will keep the array $$$[1,1,1,1]$$$, which is not strictly increasing.In the second test case, you can make the array $$$[1,3,4,7,8]$$$."}, "positive_code": [{"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", function (inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", function () {\n inputString = inputString.split(\"\\n\");\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction possibleIncrease(cases) {\n for (let i = 0; i < cases.length; i++) {\n const [...elements] = cases[i];\n let dict = {};\n for (let j = 0; j < elements.length; j++) {\n dict = {\n ...dict,\n [elements[j]]: isNaN(dict[[elements[j]]])\n ? 1\n : Number(dict[[elements[j]]]) + 1,\n };\n }\n\n const res = Object.keys(dict).some((element) => {\n if (dict[element] > 1) {\n return true;\n }\n });\n\n const sortElements = cases[i];\n sortElements.sort((a, b) => a - b);\n\n let isSorted = true;\n for (let j = 0; j < elements.length && isSorted; j++) {\n if (elements[j] !== sortElements[j]) {\n isSorted = false;\n }\n }\n console.log(res ? \"NO\" : \"YES\");\n }\n}\n\nfunction main() {\n const t = parseInt(readLine().trim());\n const cases = [];\n for (let i = 0; i < t * 2; i++) {\n const numbers = readLine().trim().split(\" \");\n if (i % 2 === 1) cases.push(numbers);\n }\n\n possibleIncrease(cases);\n}\n"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nconst data = [];\r\nconst input = [];\r\nrl.on('line', line => {\r\n input.push(line);\r\n}).on('close', () => {\r\n const dSize = parseInt(input[0], 10);\r\n for (let i = 1; i < input.length; i += 2) {\r\n const size = parseInt(input[i], 10);\r\n if (\r\n new Set(input[i + 1].split(' ').map(x => parseInt(x, 10))).size === size\r\n ) {\r\n data.push('YES');\r\n } else {\r\n data.push('NO');\r\n }\r\n }\r\n if (data.length === dSize) {\r\n console.log(data.join('\\n'));\r\n process.exit(0);\r\n }\r\n});\r\n"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nconst data = [];\r\nconst input = [];\r\nrl.on('line', line => {\r\n input.push(line);\r\n}).on('close', () => {\r\n const dSize = parseInt(input[0], 10);\r\n for (let i = 1; i < input.length; i += 2) {\r\n const size = parseInt(input[i], 10);\r\n new Set(input[i + 1].split(' ').map(x => parseInt(x, 10))).size === size\r\n ? data.push('YES')\r\n : data.push('NO');\r\n }\r\n if (data.length === dSize) {\r\n console.log(data.join('\\n'));\r\n process.exit(0);\r\n }\r\n});\r\n"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nconst data = [];\r\nconst input = [];\r\n\r\nrl.on('line', line => {\r\n input.push(line);\r\n}).on('close', () => {\r\n const dSize = parseInt(input[0], 10);\r\n for (let i = 1; i < input.length; i += 2) {\r\n new Set(input[i + 1].split(' ').map(x => parseInt(x, 10))).size ===\r\n parseInt(input[i], 10)\r\n ? data.push('YES')\r\n : data.push('NO');\r\n }\r\n if (data.length === dSize) {\r\n console.log(data.join('\\n'));\r\n process.exit(0);\r\n }\r\n});\r\n"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nconst data = [];\r\nconst input = [];\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nrl.on('line', line => {\r\n input.push(line);\r\n}).on('close', () => {\r\n const dSize = parseInt(input[0], 10);\r\n for (let i = 1; i < input.length; i += 2) {\r\n const size = parseInt(input[i], 10);\r\n const arr = input[i + 1].split(' ').map(x => parseInt(x, 10));\r\n new Set(arr).size === size ? data.push('YES') : data.push('NO');\r\n }\r\n if (data.length === dSize) {\r\n console.log(data.join('\\n'));\r\n rl.close();\r\n process.exit(0);\r\n }\r\n});\r\n"}, {"source_code": "// cls; cat .\\input.txt | node .\\script.js\r\n// codium --diff file1.js file2.js\r\n'use strict';\r\nasync function main(read) {\r\n let amount = Number(await read());\r\n let output = \"\"\r\n while (amount > 0) {\r\n let length = Number(await read())\r\n let array = await read().split(' ').map(Number).sort((a, b) => a - b)\r\n let answer = array.every((e, i) => array.lastIndexOf(e) == i)\r\n output += (answer ? \"YES\" : \"NO\") + '\\n'\r\n amount--\r\n }\r\n return output\r\n}\r\n\r\nlet inputs, str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});"}, {"source_code": "// var gcd = function(a, b) {\n// if (!b) {\n// return a;\n// }\n\n// return gcd(b, a % b);\n// }\nlet ryan = '';//.map(Number).sort(function(a, b){return a - b})\nprocess.stdin.on('data', c => ryan += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = ryan.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n var e = lines[j], a = new Map(), f= false\n }else{\n k = lines[j].split(' ').map(Number)\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n f = true\n break;\n }else{\n a.set(k[l])\n }\n }\n console.log(f === true ? 'NO' : 'YES')\n }\n \n }\n});"}, {"source_code": " const fs = require('fs');\r\n const input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\n \r\n let currentline = 0;\r\n function readline(){\r\n return input[currentline++];\r\n }\r\n \r\n let T = readline();\r\n for(let i = 1; i <= T; i++){\r\n let N = readline().split(' ');\r\n let arr = readline().split(' ').map(Number);\r\n console.log(solve(arr, N));\r\n }\r\n \r\n \r\n function solve(arr, N){\r\n let itms = new Set();\r\n for(let i=0;i stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i], a = new Map(), flag = false;\n }else{\n k = lines[i].split(' ').map(Number);\n for(j = 0; j < n; j++){\n if(a.has(k[j])){\n flag = true;\n break;\n }else{\n a.set(k[j]);\n }\n }\n console.log(flag === true ? 'NO' : 'YES');\n }\n }\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => {\r\n return string.trim();\r\n });\r\n solve();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve() {\r\n var t = readline();\r\n for (var k = 0; k < t; k++) {\r\n var n = readline();\r\n var a = readline().split(' ');\r\n var repeated = a.filter(function (e, i, a) {\r\n return a.indexOf(e) !== i;\r\n })\r\n if (repeated.length == 0) {\r\n process.stdout.write('YES\\n');\r\n } else {\r\n process.stdout.write('NO\\n');\r\n }\r\n }\r\n}\r\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL} = require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n // console.log(EOL);\r\n for(let z=1;z<=t;z++)\r\n {\r\n let n=parseInt(line[2*z-1]);\r\n let arr=line[2*z].split(' ').map(x=>{return parseInt(x)});\r\n // console.log(arr);\r\n const st=new Set();\r\n for(let i=0;i {\r\n if (currentLineIndex > 0 && currentLineIndex % 2 === 0) {\r\n lines.push(line);\r\n }\r\n currentLineIndex++;\r\n});\r\n\r\nreadlineInterface.on(\"close\", () => {\r\n const tests = lines.map((line) => line.split(\" \").map((e) => +e));\r\n\r\n tests\r\n .map((numbers) => {\r\n return new Set(numbers).size === numbers.length ? \"YES\" : \"NO\";\r\n })\r\n .forEach((e) => console.log(e));\r\n});\r\n"}, {"source_code": "/**\r\n * 10/13/22 morning\r\n * https://codeforces.com/contest/1742/problem/B\r\n */\r\n\r\nconst pr = console.log;\r\n\r\nconst solve = (n, a) => {\r\n a.sort((x, y) => x - y);\r\n for (let i = 1; i < n; i++) {\r\n if (a[i] == a[i - 1]) return pr(\"NO\");\r\n }\r\n pr(\"YES\");\r\n};\r\n\r\nconst main = () => {\r\n const readLine = () => input[currentLine++];\r\n const ni = () => readLine() - '0';\r\n const nas = () => readLine().split(\" \");\r\n const nai = () => nas().map(Number);\r\n const nal = () => nas().map(BigInt);\r\n let input = '', currentLine = 0;\r\n process.stdin.on('data', (stdin) => input += stdin)\r\n process.stdin.on('end', () => {\r\n input = input.split('\\n');\r\n let t = ni();\r\n while (t--) {\r\n let n = ni(), a = nai();\r\n solve(n, a);\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "const readline = require(\"readline\");\r\n\r\nvar tcn = 0\r\nvar isnTurn = true\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nrl.on('line', line => {\r\n if (!tcn) return tcn = Number(line)\r\n\r\n if (isnTurn) {\r\n isnTurn = false\r\n }\r\n else {\r\n isnTurn = true\r\n run(line)\r\n if (!--tcn) rl.close()\r\n }\r\n\r\n})\r\n\r\nfunction run(line) {\r\n var vals = line.split(' ').map(val => Number(val)).sort((a, b) => a - b)\r\n for (let index = 0; index < vals.length - 1; index++) {\r\n if (vals[index] == vals[index + 1]) {\r\n console.log('NO')\r\n return\r\n } \r\n }\r\n console.log('YES') \r\n}\r\n"}, {"source_code": "/*\r\n** Template\r\n*/\r\n\r\n// Common Template Starts //\r\n//*\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n let t = parseInt(readline())\r\n while (t--) {\r\n let n = parseInt(readline())\r\n let arr = readline().split(' ').map(Number)\r\n console.log(solve(arr))\r\n }\r\n}\r\n// Driver Function Ends //\r\n\r\n// MAIN LOGIC\r\nconst solve = (arr) => {\r\n let arr2 = uniqueArray( arr )\r\n \r\n if( arr.length === arr2.length ) return 'YES'\r\n\r\n return 'NO'\r\n}\r\n\r\n\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)\r\n\r\n\r\n// cmd: cat input.txt | node main.js"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet processIn = '';\r\nlet processCurr = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n processIn += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n processIn = processIn.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n JS();\r\n});\r\n\r\nfunction readLine() {\r\n return processIn[processCurr++];\r\n}\r\nfunction mergeSort(a) {\r\n let r = a.length;\r\n let l = 0;\r\n let m = Math.round((r - l) / 2);\r\n if (r === 1) {\r\n return; // returns recursively\r\n }\r\n let L = []; // left half of current a\r\n let R = []; // right half of current a\r\n for (let i = l; i < m; i++) {\r\n L.push(a[i]);\r\n }\r\n for (let j = m; j < r; j++) {\r\n R.push(a[j]);\r\n }\r\n mergeSort(L);\r\n mergeSort(R);\r\n let i = 0, j = 0, k = 0;\r\n // Merging part\r\n while (i < L.length && j < R.length) {\r\n if (L[i] < R[j]) {\r\n a[k] = L[i];\r\n i++;\r\n } else {\r\n a[k] = R[j];\r\n j++;\r\n }\r\n k++;\r\n }\r\n while (i < L.length) {\r\n a[k] = L[i];\r\n i++;\r\n k++;\r\n }\r\n while (j < R.length) {\r\n a[k] = R[j];\r\n j++;\r\n k++;\r\n }\r\n}\r\n\r\nfunction JS() {\r\n /*\r\n\r\n */\r\n let tt = parseInt(readLine());\r\n // let tt = 1;\r\n for(let t=0;t { return parseInt(string.trim()); });\r\n mergeSort(l);\r\n let flag = 1;\r\n for(let i=0;i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let t = readline();\r\n for (let i = 0; i < t; i++) {\r\n let n = readline();\r\n let arr = readline().split(\" \").map(Number);\r\n const set = new Set();\r\n for (let i = 0; i < arr.length; i++) {\r\n if (!set.has(arr[i])) {\r\n set.add(arr[i]);\r\n }\r\n }\r\n if (set.size === arr.length) {\r\n console.log(\"YES\");\r\n } else {\r\n console.log(\"NO\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n);\r\n a.sort((a, b) => a - b);\r\n for (let i = 0; i < n - 1; i++) {\r\n if (a[i] >= a[i + 1]) return 'NO';\r\n }\r\n return 'YES';\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const m = {}\n for (let x of arr) {\n if (m[x]) return 'NO'\n m[x] = 1\n }\n return 'YES'\n}\n"}, {"source_code": "// run on javascript V8 4.8.0\r\n// https://codeforces.com/contest/1742/problem/A\r\n// You are given an array a of n positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that a1 a[i]) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n var isEqual = function (a) {\r\n for (var i = 1; i < a.length; i++) {\r\n if (a[i-1] == a[i]) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n \r\n if (isDecreasing(a)) {\r\n print('NO');\r\n }\r\n else if (isEqual(a)) {\r\n print('NO');\r\n }\r\n else {\r\n print('YES');\r\n }\r\n}\r\n\r\n\r\nmain();\r\n"}, {"source_code": "const tc = readline();\r\nfor (var t =0 ; tNumber(i));\r\n input = input.sort();\r\n var b = true;\r\n for(var i=1;i a - b);\r\n for(var i = 1; i < nums.length; i++) {\r\n if(nums[i] == nums[i-1]) {\r\n print(\"NO\");\r\n return;\r\n }\r\n }\r\n print(\"YES\");\r\n}\r\n\r\nvar caseNum = parseInt(readline(), 10);\r\nfor (var i = 0; i < caseNum; i++) {\r\n var n = parseInt(readline(), 10);\r\n var x = readline()\r\n .trim()\r\n .split(' ')\r\n .map((y) => parseInt(y, 10));\r\n begin(x);\r\n}"}, {"source_code": "var tests = +readline();\r\n\r\nfor(var i=0; i {\n if (dict[element] > 1) {\n return true;\n }\n });\n\n // const sortElements = cases[i];\n // sortElements.sort((a, b) => a - b);\n\n // let isSorted = true;\n // for (let j = 0; j < elements.length && isSorted; j++) {\n // if (elements[j] !== sortElements[j]) {\n // isSorted = false;\n // }\n // }\n console.log(res ? \"NO\" : \"YES\");\n }\n}\n\nfunction main() {\n const t = parseInt(readLine().trim());\n const cases = [];\n for (let i = 0; i < t * 2; i++) {\n const numbers = readLine().split(\" \");\n if (i % 2 === 1) cases.push(numbers);\n }\n\n possibleIncrease(cases);\n}\n"}, {"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", function (inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", function () {\n inputString = inputString.split(\"\\n\");\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction possibleIncrease(cases) {\n for (let i = 0; i < cases.length; i++) {\n const [...elements] = cases[i];\n let dict = {};\n for (let j = 0; j < elements.length; j++) {\n dict = {\n ...dict,\n [elements[j]]: isNaN(dict[[elements[j]]])\n ? 1\n : Number(dict[[elements[j]]]) + 1,\n };\n }\n\n const res = Object.keys(dict).some((element) => {\n if (dict[element] > 1) {\n return true;\n }\n });\n\n console.log(\"ress nya:\", res);\n\n const sortElements = cases[i];\n sortElements.sort((a, b) => a - b);\n\n let isSorted = true;\n for (let j = 0; j < elements.length && isSorted; j++) {\n if (elements[j] !== sortElements[j]) {\n isSorted = false;\n }\n }\n console.log(res ? \"NO\" : \"YES\");\n }\n}\n\nfunction main() {\n const t = parseInt(readLine().trim());\n const cases = [];\n for (let i = 0; i < t * 2; i++) {\n const numbers = readLine().split(\" \");\n if (i % 2 === 1) cases.push(numbers);\n }\n\n possibleIncrease(cases);\n}\n"}, {"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", function (inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", function () {\n inputString = inputString.split(\"\\n\");\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction possibleIncrease(cases) {\n for (let i = 0; i < cases.length; i++) {\n const [...elements] = cases[i];\n let dict = {};\n for (let j = 0; j < elements.length; j++) {\n dict = {\n ...dict,\n [elements[j]]: isNaN(dict[[elements[j]]])\n ? 1\n : Number(dict[[elements[j]]]) + 1,\n };\n }\n\n const res = Object.keys(dict).some((element) => {\n if (dict[element] > 1) {\n return true;\n }\n });\n\n const sortElements = cases[i];\n sortElements.sort((a, b) => a - b);\n\n let isSorted = true;\n for (let j = 0; j < elements.length && isSorted; j++) {\n if (elements[j] !== sortElements[j]) {\n isSorted = false;\n }\n }\n console.log(res ? \"NO\" : \"YES\");\n }\n}\n\nfunction main() {\n const t = parseInt(readLine().trim());\n const cases = [];\n for (let i = 0; i < t * 2; i++) {\n const numbers = readLine().split(\" \");\n if (i % 2 === 1) cases.push(numbers);\n }\n\n possibleIncrease(cases);\n}\n"}, {"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", function (inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", function () {\n inputString = inputString.split(\"\\n\");\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction possibleIncrease(cases) {\n for (let i = 0; i < cases.length; i++) {\n const [...elements] = cases[i];\n let dict = {};\n for (let j = 0; j < elements.length; j++) {\n dict = {\n ...dict,\n [elements[j]]: isNaN(dict[[elements[j]]])\n ? 1\n : Number(dict[[elements[j]]]) + 1,\n };\n }\n\n const res = Object.keys(dict).some((element) => {\n if (dict[element] > 1) {\n return true;\n }\n });\n\n const sortElements = cases[i];\n sortElements.sort((a, b) => a - b);\n\n let isSorted = true;\n for (let j = 0; j < elements.length && isSorted; j++) {\n if (elements[j] !== sortElements[j]) {\n isSorted = false;\n }\n }\n console.log(res || (isSorted && elements.length > 1) ? \"NO\" : \"YES\");\n }\n}\n\nfunction main() {\n const t = parseInt(readLine().trim());\n const cases = [];\n for (let i = 0; i < t * 2; i++) {\n const numbers = readLine().split(\" \");\n if (i % 2 === 1) cases.push(numbers);\n }\n\n possibleIncrease(cases);\n}\n"}, {"source_code": "const readline = require('readline');\r\nconst util = require('util');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nconst question = util.promisify(rl.question).bind(rl);\r\nconst data = [];\r\n\r\nrl.question('', async testCaseSize => {\r\n const dSize = parseInt(testCaseSize, 10);\r\n for (let i = 0; i < dSize; i++) {\r\n const size = parseInt(await question(''), 10);\r\n const arr = (await question('')).split(' ').map(x => parseInt(x, 10));\r\n new Set(arr).size === size ? data.push('YES') : data.push('NO');\r\n if (data.length === dSize) {\r\n console.log(data.join('\\n'));\r\n rl.close();\r\n }\r\n }\r\n});\r\n\r\nrl.on('close', function () {\r\n process.exit(0);\r\n});\r\n"}, {"source_code": "// cls; cat .\\input.txt | node .\\script.js\r\n// codium --diff file1.js file2.js\r\n'use strict';\r\nasync function main(read) {\r\n let amount = Number(await read());\r\n let output = \"\"\r\n while (amount > 0) {\r\n try {\r\n let length = Number(await read())\r\n let array = await read().split(' ').map(Number).sort((a, b) => a - b)\r\n while (array.length > 1) {\r\n let c = array.shift()\r\n let n = array.shift()\r\n if (c < n) continue\r\n break\r\n }\r\n output += (array.length == 0 ? \"YES\" : \"NO\") + '\\n'\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n amount--\r\n }\r\n return output\r\n}\r\n\r\nlet inputs, str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});"}, {"source_code": "// cls; cat .\\input.txt | node .\\script.js\r\n// codium --diff file1.js file2.js\r\n'use strict';\r\nasync function main(read) {\r\n let amount = Number(await read());\r\n let output = \"\"\r\n while (amount > 0) {\r\n try {\r\n let length = Number(await read())\r\n let array = await read().split(' ').map(Number).sort((a, b) => a - b)\r\n while (array.length > 0) {\r\n let c = array.shift()\r\n let n = array.shift()\r\n if (c >= n) break\r\n }\r\n output += (array.length == 0 ? \"YES\" : \"NO\") + '\\n'\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n amount--\r\n }\r\n return output\r\n}\r\n \r\nlet inputs, str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});"}, {"source_code": "// cls; cat .\\input.txt | node .\\script.js\r\n// codium --diff file1.js file2.js\r\n'use strict';\r\nasync function main(read) {\r\n let amount = Number(await read());\r\n let output = \"\"\r\n while (amount > 0) {\r\n try {\r\n let length = Number(await read())\r\n let array = await read().split(' ').sort((a, b) => a - b)\r\n while (array.length > 0) {\r\n let c = array.shift()\r\n let n = array.shift()\r\n if (c >= n) break\r\n }\r\n output += (array.length == 0 ? \"YES\" : \"NO\") + '\\n'\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n amount--\r\n }\r\n return output\r\n}\r\n\r\nlet inputs, str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});"}, {"source_code": "// var gcd = function(a, b) {\n// if (!b) {\n// return a;\n// }\n\n// return gcd(b, a % b);\n// }\nlet ryan = '';//.map(Number).sort(function(a, b){return a - b})\nprocess.stdin.on('data', c => ryan += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = ryan.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n var e = lines[j], a = new Map(), f= false\n }else{\n k = lines[j].split(' ').map(Number)\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n f = true\n break;\n }\n }\n console.log(f === true ? 'NO' : 'YES')\n }\n \n }\n});"}, {"source_code": "// var gcd = function(a, b) {\n// if (!b) {\n// return a;\n// }\n\n// return gcd(b, a % b);\n// }\nlet ryan = '';//.map(Number).sort(function(a, b){return a - b})\nprocess.stdin.on('data', c => ryan += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = ryan.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n var e = lines[j], a = new Map(), f= false\n }else{\n k = lines[j].split(' ').map(Number)\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n f = true\n break;\n }\n }\n console.log(f === true ? 'NO' : 'YES')\n break;\n }\n \n }\n});"}, {"source_code": " const fs = require('fs');\r\n const input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\n \r\n let currentline = 0;\r\n function readline(){\r\n return input[currentline++];\r\n }\r\n \r\n let T = readline();\r\n for(let i = 1; i <= T; i++){\r\n let N = readline().split(' ');\r\n let arr = readline().split(' ').map(Number);\r\n console.log(N, arr);\r\n console.log(solve(arr, N));\r\n }\r\n \r\n \r\n function solve(arr, N){\r\n let itms = new Set();\r\n for(let i=0;i a[i]) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n if (!isDecreasing(a)) {\r\n print('YES');\r\n }\r\n else {\r\n print('NO');\r\n }\r\n}\r\n\r\n\r\nmain();\r\n"}, {"source_code": "// run on javascript V8 4.8.0\r\n// https://codeforces.com/contest/1742/problem/A\r\n// You are given an array a of n positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that a1Number(i));\r\n input = input.sort();\r\n var b = true;\r\n for(var i=1;i {\n if (c === 0) {\n c++;\n [n, m] = d.split(' ').map(Number);\n return;\n }\n\n if (n) {\n strs.push(d);\n n--;\n return;\n }\n\n points.push(...d.split(' ').map(Number));\n\n c++;\n});\n\nrl.on('close', () => {\n let ans = 0;\n\n for (let i = 0; i < strs[0].length; i++) {\n const obj = {};\n for (let j = 0; j < strs.length; j++) {\n if (obj[strs[j][i]]) {\n obj[strs[j][i]]++;\n }\n else {\n obj[strs[j][i]] = 1;\n }\n }\n\n const values = Object.values(obj).sort((a, b) => b - a);\n ans += values[0] * points[i];\n }\n\n console.log(ans);\n});\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', (c) => {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = i.split(EOL);\n const scores = [];\n for (let i = 1; i < lines.length - 2; i++) {\n scores.push(lines[i]);\n }\n let values = lines[lines.length - 2].split(' ');\n values = values.map(val => parseInt(val, 10));\n getMaxScore(scores, values);\n});\n\nfunction getMaxScore(scores, values) {\n const buckets = [];\n buckets.length = 5;\n buckets.fill(0);\n\n const mapping = {\n A: 0,\n B: 1,\n C: 2,\n D: 3,\n E: 4,\n };\n\n let score = 0;\n for (let i = 0; i < scores[0].length; i++) {\n for (let j = 0; j < scores.length; j++) {\n const answer = scores[j][i];\n buckets[mapping[answer]]++;\n }\n const max = Math.max(...buckets);\n score += (max * values[i]);\n buckets.fill(0);\n }\n console.log(score);\n}\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n\nconst solution = () => {\n\tlet line = data.split('\\n');\n\tlet [n, k] = line.shift().split(' ').map(v => parseInt(v,10));\n\tlet ans = [];\n\tfor(let i = 0; i < n; i++){\n\t\tans.push(line.shift());\n\t}\n\tlet point = line.shift().split(' ').map(v => parseInt(v, 10));\n\t\n\tlet sum = 0;\n\tlet a = 'A'.charCodeAt(0);\n\tfor(let i = 0; i < k; i++){\n\t\tlet o = [0,0,0,0,0];\n\t\tfor(let j = 0 ; j < n; j++){\n\t\t\to[ans[j].charCodeAt(i) - a]++;\n\t\t}\n\t\t\n\t\tsum += Math.max(...o) * point[i];\n\t}\n\tconsole.log(sum);\n}\n\nprocess.stdin.on('end', solution);"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n\nconst solution = () => {\n\tlet line = data.split('\\n');\n\tlet [n, k] = line.shift().split(' ').map(v => parseInt(v,10));\n\tlet ans = [];\n\tfor(let i = 0; i < n; i++){\n\t\tans.push(line.shift());\n\t}\n\tlet point = line.shift().split(' ').map(v => parseInt(v, 10));\n\t\n\tlet sum = 0;\n\tfor(let i = 0; i < k; i++){\n\t\tlet o = {A: 0, B: 0, C: 0, D: 0, E: 0};\n\t\tfor(let j = 0 ; j < n; j++){\n\t\t\to[ans[j][i]]++;\n\t\t}\n\t\t\n\t\tlet max = 0;\n\t\tfor(let m in o){\n\t\t\tmax = Math.max(o[m], max);\n\t\t}\n\t\tsum += max * point[i];\n\t}\n\tconsole.log(sum);\n}\n\nprocess.stdin.on('end', solution);"}, {"source_code": "var keys = { A: 0, B: 1, C: 2, D: 3, E: 4 };\n\nvar nm = readline().split(' ').map(item => +item);\n\nvar answers = [];\nfor(var i = 0; i < nm[0]; i++) {\n answers.push(readline());\n}\n\nvar sum = 0, vals = readline().split(' ').map(item => +item), ans = new Array(5);\n\nfor(var i = 0; i < nm[1]; i++) {\n ans.fill(0);\n for(var j = 0; j < nm[0]; j++) {\n ans[keys[answers[j][i]]]++;\n }\n sum += Math.max(...ans) * vals[i];\n}\n\nprint(sum);\n"}, {"source_code": "(function() {\nvar INPUT = ``;\nvar OUTPUT = ``;\n\nvar main = function() {\"use strict\";\n // TODO\n var input = rdArN();\n var n = input[0];\n var m = input[1];\n var M = crAr(m);\n for (var i = 0; i < M.length; ++i) {\n M[i] = {};\n M[i]['A'] = 0;\n M[i]['B'] = 0;\n M[i]['C'] = 0;\n M[i]['D'] = 0;\n M[i]['E'] = 0;\n }\n for (var i = 0; i < n; ++i) {\n var s = rdS();\n for (var j = 0; j < s.length; ++j) {\n ++M[j][s[j]];\n }\n }\n //prOb(M);\n var A = rdArN();\n var res = 0;\n for (var i = 0 ; i < m; ++i) {\n var max = -Infinity;\n for (var key in M[i]) {\n max = Math.max(max, M[i][key]);\n }\n res += max*A[i];\n //pr(max*A[i])\n }\n wr(res);\n};\n\nif(INPUT){INPUT=INPUT.split('\\n').reverse();\nreadline=()=>INPUT.pop();\nwrite=(...s)=>{OUTPUT+=[...s].join(' ')};\nprint=(...s)=>{write(...s);OUTPUT+='\\n'};}\nconst\nrdS=readline,\nrdN=()=>+rdS(),\nrdArS=()=>rdS().split(' '),\nrdArN=()=>rdArS().map(v=>+v),\nwr=write,\npr=print,\nprAr=(a)=>pr(...a),\nprOb=(o)=>pr(JSON.stringify(o,null,4)),\ncrAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},\ngetPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},\ndefineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});\ndefineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});\ndefineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});\n\nmain();\nreturn OUTPUT;\n})();"}], "negative_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', (c) => {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = i.split(EOL);\n const scores = [];\n for (let i = 1; i < lines.length - 1; i++) {\n scores.push(lines[i]);\n }\n let values = lines[lines.length - 1].split(' ');\n values = values.map(val => parseInt(val, 10));\n getMaxScore(scores, values);\n});\n\nfunction getMaxScore(scores, values) {\n const buckets = [];\n buckets.length = 5;\n buckets.fill(0);\n\n const mapping = {\n A: 0,\n B: 1,\n C: 2,\n D: 3,\n E: 4,\n };\n\n let score = 0;\n for (let i = 0; i < scores[0].length; i++) {\n for (let j = 0; j < scores.length; j++) {\n const answer = scores[j][i];\n buckets[mapping[answer]]++;\n }\n const max = Math.max(...buckets);\n score += (max * values[i]);\n buckets.fill(0);\n }\n console.log(score);\n}\n"}], "src_uid": "2022f53e5a88d5833e133dc3608a122c"} {"nl": {"description": "In Berland, there is the national holiday coming — 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 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — 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 — 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": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar data = tokenizeIntegers(readline());\n\tvar dancerNum = data[0], partyNum = data[1];\n\n\tvar colors = new Array(dancerNum);\n\tvar colorVariety = 3;\n\tvar initialAssignment = [];\n\tfor (var color = 0; color < colorVariety; ++color) {\n\t\tinitialAssignment.push(color);\n\t}\n\n\tfor (var partyIx = 0; partyIx < partyNum; ++partyIx) {\n\t\tvar party = tokenizeIntegers(readline());\n\t\tvar assignment = initialAssignment.slice(0);\n\t\tfor (var dancerIx = 0; dancerIx < colorVariety; ++dancerIx) {\n\t\t\tvar dancer = party[dancerIx]-1;\n\t\t\tif (colors[dancer] != undefined) {\n\t\t\t\tassignment[dancerIx] = colors[dancer];\n\t\t\t\tassignment[colors[dancer]] = dancerIx;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfor (dancerIx = 0; dancerIx < colorVariety; ++dancerIx) {\n\t\t\tcolors[party[dancerIx]-1] = assignment[dancerIx];\n\t\t}\n\t}\n\n\tfor (var colorIx = 0; colorIx < dancerNum; ++colorIx) {\n\t\tcolors[colorIx] += 1;\n\t}\n\tprint(colors.join(\" \"));\n}\n\nmain();\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$$$) — the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \\le n \\le 10^9$$$) — the number of matches.", "output_spec": "For each test case print one integer in single line — 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": "(function() {\n var q = Number(readline());\n while (q--) {\n var n = parseInt(readline());\n if (n == 2)\n print(2);\n else\n print(n % 2);\n }\n})();\n"}, {"source_code": "'use strict'\n \nlet n; readline();\nwhile(n = parseInt(readline())) { write((n < 5 ? 4 - n : n % 2) + '\\n'); }"}, {"source_code": "'use strict';\n\nmain();\n\nfunction main() {\n let cases = parseInt(readline());\n while ( cases-- > 0 ) {\n print(solve());\n }\n}\n\nfunction solve() {\n let matches = parseInt(readline());\n matches -= 4; // 1 + 1 = 2, basic equation\n\n return ( ( matches < 0 ) ? -1 * matches : matches % 2 );\n}"}, {"source_code": "var q = parseInt(readline());\nvar input = []\nwhile (q != 0) {\n q--;\n input.push(parseInt(readline()));\n}\ninput\n .map(n => n == 2 ? 2 : n % 2)\n .forEach(z => print(z))"}, {"source_code": "var q = parseInt(readline())\nvar mass = []\nmass.length = q\nfor (var i = 0; i < q; i++) mass[i] = parseInt(readline())\nfor (var i = 0; i < q; i++) {\n var n = mass[i]\n if (n == 2) print(2)\n else if (n % 2 == 0)\n print(0)\n else print(1)\n}"}, {"source_code": "n = +readline();\nvar q;\nfor (var i = 0; i < n;i ++){\n q = +readline();\n if (q === 1) { print(2)}\n else if (q === 2) { print(2)}\n else {\n if (q % 2 === 0){\n print(0);\n }\n else { print(1)}\n }\n}"}, {"source_code": "var q = readline();\nvar n;\nfor (var i = 0; i {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n i = i.trim()\n .split('\\n')\n .map(string => {\n return string.trim();\n });\n main();\n});\n\nfunction readLine() {\n return i[currentLine++];\n}\n\n\n\n\nfunction main() {\n var x = readLine();\n let j = 0;\n for (j = 0; j < x; j++) {\n var cq = readLine();\n //console.log('current query' + cq);\n if (cq == 2) {\n console.log(2);\n } else {\n var rs = cq - Math.floor(cq / 2); //console.log('rs ' + rs);\n var ls = Math.floor(cq / 2); //console.log('ls ' + ls);\n if (ls === rs)\n console.log('0');\n else {\n console.log(rs - ls);\n }\n }\n }\n}"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadline.on('line', line => { input.push(line); });\n\nreadline.on('close', () => {\n const n = Number(input[0]);\n const queries = input.slice(1).map(Number);\n queries.forEach(v => {\n if (v === 1) console.log(3);\n else if (v === 2) console.log(2); \n else {\n if (v % 2 === 1) console.log(1);\n else console.log(0); \n }\n })\n});"}, {"source_code": "const readline = require(\"readline\").createInterface(process.stdin, process.stdout);\nvar linesLeft,\n result = '';\nreadline.on(\"line\", line => {\n if (linesLeft === undefined)\n linesLeft = parseInt(line);\n else{\n solution(line);\n if (!(--linesLeft > 0))\n readline.close();\n }\n}).on(\"close\",() => {\n console.log(result)\n process.exit(0);\n});\n\nfunction solution (input){\n result += (input > 2 ? input % 2 : 2) + '\\n';\n return input % 2;\n}\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nlet cases, arr = [], toBuy = [];\n\nrl.on('line', n => {\n if (!cases) { cases = n } else {\n arr.push(n);\n cases--;\n if (cases === 0) {\n arr.map(Number).forEach(num => {\n num < 4 ? toBuy.push(4 - num) : num % 2 === 0 ? toBuy.push(0) : toBuy.push(1);\n });\n toBuy.forEach(num => console.log(num));\n rl.close();\n }\n }\n});"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var N = nextInt();\n if(N == 2){\n output[i] = 2;\n }else{\n output[i] = N % 2;\n }\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const n = +d;\n\n if (n === 2) {\n console.log(2);\n }\n else if (n % 2 === 0) {\n console.log(0);\n }\n else {\n console.log(1);\n }\n\n c++;\n});\n"}, {"source_code": "let fs=require('fs');\nlet txt=fs.readFileSync(0,\"utf-8\").split(\"\\r\\n\").filter(data=>{return data.length>0});\ntxt.shift()\n\ntxt.forEach(data=>{\n matches(data*1);\n})\n\nfunction matches(num){\n let res=Math.ceil(num/2);\n let other=Math.floor(num/2);\n let add=0\n if(other data += c);\nconst sol = () => {\n let [k, ...nums] = data.trim().split('\\n').map(v => Number(v));\n let ans = [];\n for(let n of nums){\n \tans.push((n < 3)?(4 - n):(n%2));\n }\n console.log(ans.join('\\n'));\n}\nprocess.stdin.on('end', sol);"}, {"source_code": "var s = '';\nvar n = 0;\n\nprocess.stdin.on('data', function (c) {\n s += c;\n});\n\nprocess.stdin.on('end', function () {\n s = s.trim().split('\\n');\n main();\n});\n\nfunction readline() {\n return s[n++];\n}\n\nfunction main() {\n var T = parseInt(readline());\n for (var t = 0; t < T; ++t) {\n var n = parseInt(readline());\n if (n === 2) {\n console.log(2);\n } else if (n % 2 == 1) {\n console.log(1);\n } else {\n console.log(0);\n }\n }\n}"}], "negative_code": [{"source_code": "'use strict'\n\nlet n; readline();\nwhile(n = parseInt(readline())) { write(n < 5 ? 4 - n : n % 2); }"}, {"source_code": "'use strict'\n \nlet n; readline();\nwhile(n = parseInt(readline())) { write(n < 5 ? 4 - n : n % 2 + '\\n'); }"}, {"source_code": "var q = parseInt(readline());\nvar input = []\nwhile (q != 0) {\n q--;\n input.push(parseInt(readline()));\n}\ninput\n .map(num => (num % 2) + (num < 4 ? (4 - num) : 0))\n .forEach(z => print(z))"}, {"source_code": "//'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet t = Date.now();\n\nlet currentLine = 0;\nlet i = '';\nprocess.stdin.on('data', c => {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n i = i.trim()\n .split('\\n')\n .map(string => {\n return string.trim();\n });\n main();\n});\n\nfunction readLine() {\n return i[currentLine++];\n}\n\n\n\n\nfunction main() {\n var x = readLine();\n console.log(x);\n let j = 0;\n for (j = 0; j < x; j++) {\n var cq = readLine();\n //console.log('current query' + cq);\n if (cq == 2) {\n console.log(2);\n } else {\n var rs = cq - Math.floor(cq / 2); //console.log('rs ' + rs);\n var ls = Math.floor(cq / 2); //console.log('ls ' + ls);\n if (ls === rs)\n console.log('0');\n else {\n console.log(rs - ls);\n }\n }\n }\n}"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadline.on('line', line => { input.push(line); });\n\nreadline.on('close', () => {\n const n = Number(input[0]);\n const queries = input.slice(1).map(Number);\n console.log(queries);\n queries.forEach(v => {\n if (v === 1) console.log(3);\n else if (v === 2) console.log(2); \n else {\n if (v % 2 === 1) console.log(1);\n else console.log(0); \n }\n })\n});"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\nconst sol = () => {\n let nums = data.split('\\n').map(v => Number(v));\n nums.shift();\n let ans = [];\n for(let n of nums){\n \tans.push((n < 3)?(4 - n):(n%2));\n }\n console.log(ans.join('\\n'));\n}\nprocess.stdin.on('end', sol);"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\nconst sol = () => {\n let [k, ...nums] = data.split('\\n').map(v => Number(v));\n let ans = [];\n for(let n of nums){\n \tans.push((n < 3)?(4 - n):(n%2));\n }\n console.log(ans.join('\\n'));\n}\nprocess.stdin.on('end', sol);"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\nconst sol = () => {\n let nums = data.split('\\n').map(v => parseInt(v,10));\n nums.shift();\n let ans = [];\n for(let n of nums){\n \tans.push((n < 3)?(4 - n):(n%2));\n }\n console.log(ans.join('\\n'));\n}\nprocess.stdin.on('end', sol);"}], "src_uid": "178876bfe161ba9ccfd80c9310f75cbc"} {"nl": {"description": "You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.You must paint a fence which consists of $$$10^{100}$$$ planks in two colors in the following way (suppose planks are numbered from left to right from $$$0$$$): if the index of the plank is divisible by $$$r$$$ (such planks have indices $$$0$$$, $$$r$$$, $$$2r$$$ and so on) then you must paint it red; if the index of the plank is divisible by $$$b$$$ (such planks have indices $$$0$$$, $$$b$$$, $$$2b$$$ and so on) then you must paint it blue; if the index is divisible both by $$$r$$$ and $$$b$$$ you can choose the color to paint the plank; otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $$$k$$$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) — the number of test cases. The next $$$T$$$ lines contain descriptions of test cases — one per line. Each test case contains three integers $$$r$$$, $$$b$$$, $$$k$$$ ($$$1 \\le r, b \\le 10^9$$$, $$$2 \\le k \\le 10^9$$$) — the corresponding coefficients.", "output_spec": "Print $$$T$$$ words — one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.", "sample_inputs": ["4\n1 1 2\n2 10 4\n5 2 3\n3 2 2"], "sample_outputs": ["OBEY\nREBEL\nOBEY\nOBEY"], "notes": null}, "positive_code": [{"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let j = 0; j < t; j++) {\n let [r, b, k] = arr[j].split(' ').map(a => parseInt(a))\n let x = 0\n\n let gc = gcd(r, b)\n r /= gc\n b /= gc\n\n if(r == b) {\n wr('OBEY')\n continue\n }\n if(r > b) {\n let temp = r\n r = b\n b = temp\n }\n\n let mod = b % r\n if(mod <= 1) x = Math.floor(b / r)\n else x = Math.ceil(b / r)\n\n if((k - 1) * r + 1 < b) wr('REBEL')\n else wr('OBEY')\n }\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction max(...x) {\n return Math.max(...x)\n}\n\nfunction min(...x) {\n return Math.min(...x)\n}\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n}\n"}], "negative_code": [{"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let j = 0; j < t; j++) {\n const [r, b, k] = arr[j].split(' ').map(a => parseInt(a))\n let x = 0\n\n if(r == b) {\n wr('OBEY')\n continue\n }\n else if(r < b) {\n let mod = b % r\n if(mod <= 1) x = Math.floor(b / r)\n else x = Math.ceil(b / r)\n }\n else {\n let mod = r % b\n if(mod <= 1) x = Math.floor(r / b)\n else x = Math.ceil(r / b)\n }\n\n if(x >= k) wr('REBEL')\n else wr('OBEY')\n }\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction max(...x) {\n return Math.max(...x)\n}\n\nfunction min(...x) {\n return Math.min(...x)\n}\n"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let j = 0; j < t; j++) {\n let [r, b, k] = arr[j].split(' ').map(a => parseInt(a))\n let x = 0\n\n let gc = gcd(r, b)\n r /= gc\n b /= gc\n\n if(r == b) {\n wr('OBEY')\n continue\n }\n if(r > b) {\n let temp = r\n r = b\n b = temp\n }\n\n let mod = b % r\n if(mod <= 1) x = Math.floor(b / r)\n else x = Math.ceil(b / r)\n\n if((k - 1) * r + 1 < b) wr('OBEY')\n else wr('REBEL')\n }\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction max(...x) {\n return Math.max(...x)\n}\n\nfunction min(...x) {\n return Math.min(...x)\n}\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n}\n"}], "src_uid": "be141f316d6e5d9d8f09192913f4be47"} {"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$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$) — 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$$$) — 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 i = '';//.map(Number).sort(function(a, b){return a - b})\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0], e= 0, g = 0\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j], g= 0\n }else{\n var k = lines[j].split(' ').map(Number).sort(function(a, b){return a - b}), a = k[0]\n for(l = 1; l < e; l++){\n g += k[l] - a\n }\n console.log(g)\n }\n }\n \n});//k[k.length - 1] == '' || "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var e = 0;\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j];\n }else{\n var k = lines[j].split(' ').map(Number).sort(function(a, b){return a - b});\n var ans = 0;\n var a = k[0];\n for(i = 1; i < e; i++){\n ans += k[i] - a;\n }\n console.log(ans);\n }\n }\n});\n"}, {"source_code": "/*\r\nFile Created: Tuesday, 17 May 2022\r\nAuthor: Lukas Rimkus\r\n*/\r\n'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\n data += chunk;\r\n});\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '').split('\\n').map(str => str.replace(/\\s*$/, ''));\r\n let testCases = parseInt(readLine());\r\n while(testCases--) {\r\n const n = parseInt(readLine());\r\n const arr = get_ints();\r\n console.log(solve([n,arr]));\r\n }\r\n});\r\nfunction get_ints() { \r\n return data[currentLine++].split(' ').map(Number);\r\n}\r\n\r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction solve(input){\r\n let candies = 0;\r\n const min = Math.min(...input[1]);\r\n for (let index = 0; index < input[1].length; index++) {\r\n candies+= input[1][index] - min;\r\n } \r\n return candies;\r\n}\r\n\r\nmodule.exports = solve;"}, {"source_code": "\r\n\r\nconst { createInterface } = require('readline');\r\n/*\r\nconst { createWriteStream, createReadStream } = require('fs');\r\nconst { format } = require('util');\r\nconst log_file = createWriteStream('output.txt', { flags: 'w' }\r\n);\r\nconst log_stdout = process.stdout;\r\nconsole.log = function (d) {\r\n log_file.write(format(d) + '\\n');\r\n log_stdout.write(format(d) + '\\n');\r\n};\r\nconst fileStream = createReadStream('input.txt');\r\n*/\r\nfunction main() {\r\n const readline = createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let lineNb = 0;\r\n let n;\r\n let t = [];\r\n let currentLength = -1;\r\n readline.on('line', line => {\r\n if (!lineNb)\r\n n = parseInt(line) * 2;\r\n else if (!(lineNb % 2)) {\r\n let sum = 0;\r\n let array = line.split(\" \");\r\n let min = parseInt(array[0])\r\n t = (line.split(\" \").map(i => {\r\n let currentNumber = Number(i);\r\n sum += currentNumber\r\n if (min > currentNumber) min = currentNumber\r\n return Number(i);\r\n }));\r\n console.log(sum - min * currentLength)\r\n } else {\r\n currentLength = parseInt(line)\r\n }\r\n if (lineNb === n)\r\n readline.close();\r\n lineNb++;\r\n });\r\n\r\n}\r\n\r\nmain()"}, {"source_code": "\r\n\r\nconst { createInterface } = require('readline');\r\n/*\r\nconst { createWriteStream, createReadStream } = require('fs');\r\nconst { format } = require('util');\r\nconst log_file = createWriteStream('output.txt', { flags: 'w' }\r\n);\r\nconst log_stdout = process.stdout;\r\nconsole.log = function (d) {\r\n log_file.write(format(d) + '\\n');\r\n log_stdout.write(format(d) + '\\n');\r\n};\r\nconst fileStream = createReadStream('input.txt');\r\n*/\r\nfunction main() {\r\n const readline = createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let lineNb = 0;\r\n let n;\r\n let t = [];\r\n let currentLength = -1;\r\n readline.on('line', line => {\r\n if (!lineNb)\r\n n = parseInt(line) * 2;\r\n else if (!(lineNb % 2)) {\r\n let sum = 0;\r\n t = (line.split(\" \").map(i => {\r\n var currentNumber = Number(i);\r\n sum += currentNumber\r\n return Number(i);\r\n }));\r\n const min = Math.min(...t);\r\n console.log(sum - min * currentLength)\r\n } else {\r\n currentLength = parseInt(line)\r\n }\r\n if (lineNb === n)\r\n readline.close();\r\n lineNb++;\r\n });\r\n\r\n}\r\n\r\nmain()"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n\tvar t = lines[0];\n var e = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n e = lines[i];\n }else{\n var k = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});\n var a = k[0];\n var ans = 0;\n for(j = 1; j < e; j++){\n ans += k[j] - a;\n }\n console.log(ans);\n }\n }\n});"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var n = lines[0];\n var e = 0;\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j];\n }else{\n var k = lines[j].split(' ').map(Number).sort(function(a, b){return a - b});\n var ans = 0;\n var a = k[0];\n for(i = 1; i < e; i++){\n ans += k[i] - a;\n }\n console.log(ans);\n }\n }\n});"}, {"source_code": "const main = (input) => {\r\n input = input.split('\\n')\r\n\r\n const t = Number(input[0])\r\n for (let i = 0; i < t; i++) {\r\n const n = parseInt(input[1 + i * 2])\r\n const a = input[1 + i * 2 + 1].split(' ').map((x) => parseInt(x))\r\n\r\n const ans =\r\n a.reduce((prev, current) => prev + current, 0) - Math.min(...a) * n\r\n console.log(ans)\r\n }\r\n}\r\n\r\nmain(require('fs').readFileSync(0).toString())"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2 !== 0) {\n c++;\n return;\n }\n\n const arr = d\n .split(\" \")\n .map(Number)\n .sort((a, b) => a - b);\n const min = arr[0];\n let ans = 0;\n\n for (let i = 1; i < arr.length; i++) {\n if (min < arr[i]) {\n ans += arr[i] - min;\n }\n }\n\n console.log(ans);\n\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n let arr = readline().split(' ').map(Number);\r\n\r\n let min = Math.min(...arr);\r\n\r\n let sum = 0;\r\n for (let i = 0; i < n; i++) {\r\n sum += arr[i] - min;\r\n }\r\n\r\n output(sum);\r\n }\r\n}\r\n"}, {"source_code": "const rdline = require('readline');\r\nconst rl = rdline.createInterface({\r\n input: process.stdin\r\n});\r\n\r\nlet lines = [];\r\nrl.on('line', (line) => {\r\n lines.push(line);\r\n}).on('close', () => {\r\n // input in lines\r\n solve();\r\n});\r\n\r\nlet line = 0;\r\nconst readline = () => lines[line++];\r\nsolve = () => {\r\n const t = parseInt(readline());\r\n for (let i = 0; i < t; i++) {\r\n var n = parseInt(readline());\r\n var a = readline().split(\" \").map(Number).sort(function(a, b) {\r\n return a - b;\r\n });\r\n var sum = 0;\r\n var min = a[0];\r\n for (let j = 0; j < n; j++) {\r\n \r\n if (a[j] === min) {\r\n sum = 0 + sum;\r\n } else {\r\n sum = sum + a[j] - min;\r\n }\r\n }\r\n \r\n console.log(sum)\r\n }\r\n}"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet n = nl.num();\n\t\tlet a = nl.nums();\n\t\tlet s = a.reduce((x, ac) => ac + x, 0);\n\t\tlet m = a.reduce((x, ac) => x < ac?x:ac, a[0]);\n\t\tans.push(s - m*n);\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "let i = '';\r\nprocess.stdin.on('data', c => i += c);\r\nprocess.stdin.on('end', () => {\r\n const {EOL} = require('os');\r\n const lines = i.split(EOL);\r\n \r\n function foo (data) {\r\n const numberData = data.split(' ').map(Number);\r\n const min = Math.min(...numberData);\r\n\r\n return numberData.reduce((acc, value) => {\r\n const diff = value - min;\r\n return acc + diff;\r\n }, 0);\r\n }\r\n \r\n let testCount = 1;\r\n const rowsInTest = 2;\r\n let answer = '';\r\n while(testCount <= +lines[0]) {\r\n let data = lines[testCount * rowsInTest];\r\n let result = foo(data);\r\n answer += result +\"\\n\";\r\n testCount += 1;\r\n }\r\n console.log(answer);\r\n})\r\n"}, {"source_code": "const solve = (arr,n) => {\r\n let min = Infinity,cnt = 0;\r\n for(let i=0;iparseInt(cur));\r\n solve(arr,l);\r\n }\r\n}\r\nmain();"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n let min = Math.min(...a);\r\n let res = 0;\r\n for (let num of a) {\r\n res += num - min;\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "let readline = require(\"readline\");\nlet rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\nconst findMinimum = (array) => {\n let result = array[0];\n for (let index = 0; index < array.length; index++) {\n const element = array[index];\n if (result > element) {\n result = element;\n }\n }\n\n return result;\n};\n\nlet lines = 0;\n\nrl.on(\"line\", function (line) {\n if (lines !== 0 && lines % 2 === 0) {\n let input = line.split(\" \").map(Number);\n const minimum = findMinimum(input);\n console.log(input.reduce((sum, candies) => sum + candies - minimum, 0));\n }\n lines++;\n});\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n let n = parseInt(input());\r\n const a = input().split(' ').map(Number);\r\n let min_a = 1e7;\r\n for(let i of a) min_a = Math.min(min_a, i);\r\n let ans = 0;\r\n for(let i of a) if(i > min_a) ans += i-min_a;\r\n console.log(ans);\r\n }\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n console.log(solve());\r\n }\r\n}\r\nfunction solve() {\r\n readLine();\r\n let arr = readLine().split(\" \").map(i => parseInt(i));\r\n let min = Number.MAX_VALUE;\r\n for (let i = 0; i < arr.length; i++) {\r\n min = Math.min(min, arr[i]);\r\n }\r\n let eat = 0;\r\n for (let i = 0; i < arr.length; i++) {\r\n eat += arr[i] !== min ? arr[i] - min : 0;\r\n }\r\n return eat;\r\n}\r\n"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nvar T = readline();\r\nfor(var q=1;q<=T;q++) {\r\n var n = readline();\r\n var a = readline().split(' ').map((x)=>parseInt(x));\r\n var ans = 0;\r\n var mn = 100000001;\r\n var sum = 0;\r\n for(var i=0;i{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n \nconst calc = ()=>{\n // READING:\n let [n] = ra();\n let A = ra();\n LT({n, A});\n // PROCESSING:\n let min = Math.min.apply(null, A);\n let ans = 0;\n for (let a of A)\n ans += a-min;\n return ans;\n};\n "}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n let min = arr[0]\n for (let i = 0; i < arr.length; i++) {\n min = Math.min(min, arr[i])\n }\n let ans = 0\n for (let i = 0; i < arr.length; i++) {\n ans += arr[i] - min\n }\n return ans\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar min = 100000000;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tmin = Math.min(min, list[i]);\r\n\t\t}\r\n\t\tvar output = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\toutput += list[i] - min;\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}, {"source_code": "var testCase = +readline(),counter\r\nfor(var i=0;i+node)\r\n var minValue=sequence.reduce((a,b)=>Math.min(a,b))\r\n for(var j=0;j readline();\r\nconst readStrArr = () => readline().split(' ');\r\n\r\nconst n = readStr();\r\nfor(var i = 0; i < n; i++) {\r\n var k = readStr();\r\n var a = readStrArr();\r\n if(k === '1'){\r\n print(0);\r\n continue;\r\n }\r\n var min = Math.min(...a), sum = 0;\r\n for(var j = 0; j < k; j++) {\r\n sum += a[j] - min;\r\n }\r\n print(sum);\r\n}\r\n"}, {"source_code": "var t = parseInt(readline());\r\n \r\nfor (var test = 0; test < t; test++) {\r\n var n = parseInt(readline());\r\n var arr = readline().split(' ');\r\n\r\n var sum = parseInt(arr[0]);\r\n var min = parseInt(arr[0]);\r\n\r\n for (var i = 1; i < n; i++) {\r\n sum += parseInt(arr[i]);\r\n min = Math.min(min, parseInt(arr[i]));\r\n }\r\n\r\n print(sum - min * n);\r\n}"}, {"source_code": "var t = readline();\r\nfor(var i = 0 ; i < t ;i++){\r\n var n = readline();\r\n var a = readline().split(' ');\r\n a.sort( (a,b) => {return a-b});\r\n var min = a[0] , counter = 0;\r\n for(var j = 0 ; j < n ; j++){\r\n counter+= (a[j] - a[0]);\r\n }\r\n print(counter);\r\n}"}, {"source_code": "var n = +readline()\r\n\r\nfor(var i=0;i max){\r\n max =+arr[j];\r\n }\r\n }\r\n \r\n if(min === max){\r\n print(0);\r\n }else{\r\n var op = 0;\r\n for(var j=0;j min){\r\n op += +arr[j] - min;\r\n }\r\n }\r\n print(op)\r\n }\r\n}"}, {"source_code": "T = readline()\r\nwhile (T--) {\r\n n = +readline()\r\n a = readline().split(' ').map(a => +a)\r\n a.sort((prev, next) => prev - next)\r\n\r\n ans = 0\r\n for(i=1; i< n; i++){\r\n ans += a[i] - a[0]\r\n }\r\n print(ans)\r\n}\r\n"}, {"source_code": "t = parseInt(readline());\r\nfor(i = 0; i < t; i++)\r\n{\r\n var n = readline();\r\n n = readline().split(\" \");\r\n var min = 10000001;\r\n var sum = 0;\r\n for(j = 0; j < n.length; j++)\r\n {\r\n sum += parseInt(n[j]);\r\n if(parseInt(n[j]) < min) min = n[j];\r\n }\r\n print(sum - min*n.length);\r\n}"}, {"source_code": "var n = readline()\r\n\r\nfor(var i=0 ; i +t);\r\n \r\n print(Task2(b));\r\n}\r\n \r\nfunction Task2 (arr){\r\n \r\n var min = Math.min(...arr);\r\n var count = 0;\r\n for(var i = 0; i i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0], e= 0, g = 0\n for(j = 1; j <= n; j++){\n if(j % 2 == 1){\n e = lines[j], g= 0\n }else{\n var k = lines[j].split(' ').map(Number).sort(function(a, b){return a - b}), a = k[0]\n for(l = 1; l < e; l++){\n g += k[l] - a\n }\n console.log(g)\n }\n }\n \n});//k[k.length - 1] == '' || "}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main()\r\n}); \r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n const n = input().split('').map(Number);\r\n const a = input().split('').map(Number);\r\n console.log(solve([n,a]))\r\n }\r\n}\r\n\r\nfunction solve(input){\r\n let candies = 0;\r\n const min = Math.min(...input[1]);\r\n for (let index = 0; index < input[1].length; index++) {\r\n candies+= input[1][index] - min;\r\n } \r\n console.log(candies)\r\n return candies;\r\n}\r\n\r\nmodule.exports = solve;"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main()\r\n}); \r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n const n = input().split('').map(Number);\r\n const a = input().split('').map(Number);\r\n ans = solve([n,a]);\r\n console.log(ans)\r\n }\r\n}\r\n\r\nfunction solve(input){\r\n let candies = 0;\r\n const min = Math.min(...input[1]);\r\n for (let index = 0; index < input[1].length; index++) {\r\n candies+= input[1][index] - min;\r\n } \r\n return candies;\r\n}\r\n\r\nmodule.exports = solve;"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main()\r\n}); \r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n const n = input().split('').map(Number);\r\n const a = input().split('').map(Number);\r\n console.log(solve([n,a]))\r\n }\r\n}\r\n\r\nfunction solve(input){\r\n let candies = 0;\r\n const min = Math.min(...input[1]);\r\n for (let index = 0; index < input[1].length; index++) {\r\n candies+= input[1][index] - min;\r\n } \r\n return candies;\r\n}\r\n\r\nmodule.exports = solve;"}, {"source_code": "var testCase = readline().split(\"\"),counter\r\nfor(var i=0;i+node)\r\n var minValue=sequence.reduce((a,b)=>Math.min(a,b))\r\n for(var j=0;j {\n inputString += inputStdin\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n')\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++]\n}\n\nconst s2i = s => parseInt(s, 10)\n\nfunction main() {\n let T = s2i(readLine())\n let out = ''\n while (T--) {\n const n = s2i(readLine())\n const arr = readLine().split(' ').map(s2i)\n\n let sumEven = arr[0]\n let sum01 = 0\n let sum12 = 0\n let max = 0\n for (let i = 1, even = false, curr = sumEven; i < n; i++, even = !even) {\n const prev = curr\n curr = arr[i]\n if (even) {\n sumEven += curr\n sum01 += prev - curr\n if (sum01 < 0) {\n sum01 = 0\n } else {\n max = Math.max(max, sum01)\n }\n } else {\n sum12 += curr - prev\n if (sum12 < 0) {\n sum12 = 0\n } else {\n max = Math.max(max, sum12)\n }\n }\n }\n\n out += (sumEven + max) + '\\n'\n }\n console.log(out)\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n D();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction C(){\n let [n,m] = ti(readline().split(' '));\n let a = ti(readline().split(' '));\n let b = ti(readline().split(' '));\n let o = new Array(10);\n let z = new Array(10);\n o.fill(0);\n z.fill(0);\n for(let i = 0; i < m; i++){\n let t = 1;\n for(let j = 0; j < 10; j++){\n if(b[i] & t !== 0)\n o[j] = 1;\n else\n z[j] = 1;\n\n t << 1;\n }\n }\n\n let c = new Array(10);\n for(let i = 0; i < n; i++){\n let t = 1;\n for(let j = 0; j < 10; j++){\n if(a[i] & t !== 0){\n if(z[j] === 1)\n c[j] = 0;\n else\n c[j] = 1;\n }\n t << 1;\n }\n }\n\n let res = 0;\n for(let i = 9; i >= 0; i--){\n res += pi(c[i])*Math.pow(2,9-i);\n }\n console.log(res);\n}\n\nfunction B(){\n let t = pi(readline());\n while(t){\n t--;\n let [n,k,z] = ti(readline().split(' '));\n let a = ti(readline().split(' '));\n\n // pre -> 0,1 -> right,left\n let dp = new Array(z+1);\n for(let i = 0; i < z+1; i++){\n dp[i] = new Array(n);\n dp[i].fill(-1);\n }\n \n let solve = (i,j,index,pre) => {\n if(index < 0 || index >= n)\n return 0;\n if(i > k)\n return 0;\n if(dp[j][index] !== -1)\n return dp[j][index];\n if(pre){\n return dp[j][index] = a[index] + solve(i+1, j, index+1, 0);\n }else{\n return dp[j][index] = a[index] + Math.max(j < z ? solve(i+1,j+1,index-1,1) : 0, solve(i+1,j,index+1,0));\n }\n }\n\n console.log(solve(0,0,0,1));\n }\n}\n\nfunction E1(){\n let [n,k] = ti(readline().split(' '));\n let t = new Array(n);\n for(let i = 0; i < n; i++){\n t[i] = ti(readline().split(' '));\n }\n let ab = [];\n let a = [];\n let b = [];\n let unlikeCount = 0;\n\n for(let i = 0; i < n; i++){\n if(t[i][1] === 1 && t[i][2] === 1){\n ab.push(t[i]);\n }else if(t[i][1] === 1){\n a.push(t[i]);\n }else if(t[i][2] === 1){\n b.push(t[i]);\n }else{\n unlikeCount += 1;\n }\n }\n\n ab.sort((x,y) => x[0]-y[0]);\n a.sort((x,y) => x[0]-y[0]);\n b.sort((x,y) => x[0]-y[0]);\n // let max = Math.max(max, ab.length, a.length, b.length);\n // let min = Math.min(min, ab.length, a.length, b.length);\n // let inf = 9999999999;\n // for(let i = min+1; i <= max; i++){\n // if(i >= ab.length) ab.push(inf);\n // if(i >= a.length) a.push(inf);\n // if(i >= b.length) b.push(inf);\n // }\n\n let p1 = p2 = p3 = 0;\n let ka = k;\n let kb = k;\n let res = 0;\n while(p1 < ab.length || p2 < a.length || p3 < b.length){\n if(ka === 0 && kb === 0)\n break;\n if(p2 < a.length && p3 < b.length){\n if(p1 < ab.length){\n if(a[p2][0]+b[p3][0] > ab[p1][0]){\n res += ab[p1][0];\n p1++;\n }else{\n res += a[p2][0]+b[p3][0];\n p2++;\n p3++;\n }\n }else{\n res += a[p2][0]+b[p3][0];\n p2++;\n p3++;\n }\n ka--;\n kb--;\n }else{\n if(p1 >= ab.length){\n console.log(-1);\n return;\n }\n res += ab[p1][0];\n ka--;\n kb--;\n p1++;\n }\n }\n if(ka !== 0 || kb !== 0){\n console.log(-1);\n return;\n }\n console.log(res);\n}\n\nfunction D(){\n let t = pi(readline());\n while(t){\n t--;\n let n = pi(readline());\n let a = ti(readline().split(' '));\n let sum1 = new Array(n);\n let sum2 = new Array(n);\n sum1[0] = -1*a[0];\n sum2[0] = a[0];\n for(let i = 1; i < n; i++){\n if(i%2 === 0){\n sum1[i] = sum1[i-1] - a[i]; \n }else{\n sum1[i] = sum1[i-1] + a[i];\n }\n }\n\n let min = 99999999999;\n let [l,r] = [-1,-1];\n let max = 0;\n let minIndex = 0;\n for(let i = 0; i < n; i+=2){\n if(min > sum1[i]){\n min = sum1[i];\n minIndex = i;\n }\n\n if(max < sum1[i]-min){\n max = sum1[i]-min;\n [l,r] = [minIndex+1,i];\n }\n }\n\n min = 0;\n minIndex = -1;\n for(let i = 1; i < n; i+=2){\n if(min > sum1[i]){\n min = sum1[i];\n minIndex = i;\n }\n\n if(max < sum1[i]-min){\n max = sum1[i]-min;\n [l,r] = [minIndex+1,i];\n }\n }\n\n let res = 0;\n for(let i = 0; i < n; i++){\n if(i < l || i > r){\n if(i%2 === 0)\n res += a[i];\n }\n else{\n if(i%2 !== 0)\n res += a[i];\n }\n }\n\n console.log(res);\n }\n}"}, {"source_code": "function solve() {\n var T = Number(read());\n for (var t = 0; t < T; t++) {\n var n = Number(read());\n var a = read().split(' ').map(Number);\n var sum = a[0];\n var x = 0;\n var y = 0;\n var ans = 0;\n for (var i = 1; i < n; i += 2) {\n x += (a[i] - a[i - 1]);\n if (x > ans) {\n ans = x;\n }\n if (x < 0) {\n x = 0;\n }\n if (i + 1 < n) {\n sum += a[i + 1];\n y += (a[i] - a[i + 1]);\n if (y > ans) {\n ans = y;\n }\n if (y < 0) {\n y = 0;\n }\n }\n }\n write(ans + sum);\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n\n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n\n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n solve();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n\n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n\n RL.on('close', solve);\n }\n} else {\n solve();\n}\n\nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}], "negative_code": [], "src_uid": "3696b769bfd32cba34e739b74e13693f"} {"nl": {"description": "Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.", "input_spec": "The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.", "output_spec": "Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.", "sample_inputs": ["6\n549871", "7\n1198733"], "sample_outputs": ["54-98-71", "11-987-33"], "notes": null}, "positive_code": [{"source_code": "var size = readline(), number = readline(), ans = []\nvar go = number.length, index = 0\nwhile (go){\n\tvar nxt = (go%2) ? 3 : 2\n\tans.push(number.slice(index,index+nxt))\n\tindex+= nxt; go-=nxt\n}\nprint(ans.join(\"-\"))"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar digitNum = parseInt(readline());\n\tvar s = trim(readline());\n\n\tvar pos = (digitNum%2 == 0 ? 2 : 3);\n\twrite(s.substring(0, pos));\n\n\twhile (pos < digitNum) {\n\t\twrite(\"-\"+s.substring(pos, pos+2));\n\t\tpos += 2;\n\t}\n\tprint();\n}\n\nmain();\n"}, {"source_code": "'use strict'\n\nlet N = +readline()\nlet L = readline()\n\nlet res = []\n\nfor (let i = 0; i <= N; i = i + 2) {\n res.push(L.slice(i, i + 2))\n}\n\nres = res.filter(Boolean)\n\nif (N % 2) {\n res[res.length - 2] += res[res.length - 1]\n res.length--\n}\n\nprint(res.filter(Boolean).join('-'))"}, {"source_code": "var n=readline(); n=parseInt(n);\nvar arr=readline(); \nvar three=0,two=0;\nfor(var i=0;i<=100;i++)\n{\n for(var j=0;j<=100;j++)\n {\n var temp=n-i*2-j*3; \n if(temp==0)\n {\n three=j; two=i;\n }\n }\n}\nvar num=0; var ans=\"\";\nfor(var i=0;i {if (num > max) max = num;}\nfor (var i = N; i--; ) {\n max = -Infinity;\n readline().split(' ').forEach(updateMax);\n q.push(max);\n}\nprint(q.join(' ').replace(N-1, N));\n"}, {"source_code": "var N = parseInt(readline());\nvar q = [], ans = [];\nfor (var i = N; i--; ) {\n q.push(' '+readline().replace(/0/g, ''));\n}\nfor (var i = 1, flag; i < N; ++i) {\n flag = false;\n for (var j = 0; j < N; ++j) {\n q[j] = q[j].replace(new RegExp(` ${i}`, 'g'), '');\n if (q[j] === ' ' && !ans[j] && !flag) {\n ans[j] = i;\n flag = true;\n }\n }\n}\nfor (var i = 0; i < N; ++i) {\n if (typeof ans[i] === 'undefined') {\n ans[i] = N;\n }\n}\nprint(ans.join(' '));\n"}], "src_uid": "1524c658129aaa4175208b278fdc467c"} {"nl": {"description": "There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.", "input_spec": "The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3).", "output_spec": "Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal.", "sample_inputs": ["9\n1 3 2 2 2 1 1 2 3"], "sample_outputs": ["5"], "notes": "NoteIn the example all the numbers equal to 1 and 3 should be replaced by 2."}, "positive_code": [{"source_code": "'use strict'\n\nlet N = +readline()\nlet lll = readline().split(' ').map(v => parseInt(v))\n\nlet c = [0, 0, 0]\nfor (let i = 0; i < N; i++) {\n c[lll[i] - 1]++\n}\nprint(c[0] + c[1] + c[2] - Math.max(c[0], c[1], c[2]))"}, {"source_code": "var cnt = new Array(4).fill(0);\ncnt[0] = Number.MAX_SAFE_INTEGER;\nreadline();\nreadline().split(\" \").map((x)=>{ cnt[x]++; });\nvar out = 0;\nvar min = Math.min(...cnt);\nout += min;\ncnt.splice(cnt.indexOf(min),1);\nout += Math.min(...cnt);\nprint(out);"}, {"source_code": "var getNums = function() {\n\treturn readline().split(' ').map(function(a) {return parseInt(a)});\n};\n\nvar n = parseInt(readline());\nvar input = getNums();\nvar hash = {};\n\nfor(var j = 1; j <= 3; j++) {\n\thash[j] = 0;\n}\n\nfor (var i = 0; i < n; i++) {\n\thash[input[i]]++;\n}\n\nprint(Math.min(hash[1] + hash[2], hash[1] + hash[3], hash[3] + hash[2]));"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet indicator = 0, N;\nrl.on('line', (input) => {\n if (indicator == 0){\n N = parseInt(input);\n indicator++;\n }\n else {\n let cont = input.split(' ').map(item => parseInt(item))\n let dict = {};\n let maxval = 0;\n cont.forEach(item => {\n if (item in dict)\n dict[item]++;\n else\n dict[item] = 1;\n\n if (maxval < dict[item])\n maxval = dict[item];\n\n\n });\n console.log(N - maxval);\n rl.close();\n }\n});"}], "negative_code": [{"source_code": "var cnt = new Array(4).fill(0);\nreadline();\nreadline().split(\" \").map((x)=>{ cnt[x]++; });\nvar max = Math.max(...cnt);\nvar out = 0;\ncnt.map((x)=>{if(x!=max)out+=x;});\nprint(out);"}, {"source_code": "var cnt = new Array(4).fill(0);\ncnt.splice(cnt.indexOf(0),1);\nreadline();\nreadline().split(\" \").map((x)=>{ cnt[x]++; });\nvar out = 0;\nvar min = Math.min(...cnt);\nout += min;\ncnt.splice(cnt.indexOf(min),1);\nout += Math.min(...cnt);\nprint(out);"}, {"source_code": "var cnt = new Array(4).fill(0);\nreadline();\nreadline().split(\" \").map((x)=>{ cnt[x]++; });\nvar out = 0;\nvar min = Math.min(...cnt);\nout += min;\ncnt.splice(cnt.indexOf(min),1);\nout += Math.min(...cnt);\nprint(out);"}, {"source_code": "var getNums = function() {\n\treturn readline().split(' ').map(function(a) {return parseInt(a)});\n};\n\nvar n = parseInt(readline());\nvar input = getNums();\nvar hash = {};\n\nfor (var i = 0; i < n; i++) {\n\tvar a = input[i];\n\tif (hash[a]) {\n\t\thash[a]++;\n\t} else {\n\t\thash[a] = 1;\n\t}\n}\n\nprint(Math.min(hash[1] + hash[2], hash[1] + hash[3], hash[3] + hash[2]));\n"}], "src_uid": "fcb6a715dfe302d7ae5a6695ca8976aa"} {"nl": {"description": "Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively \"Loves\" and \"Doesn't love\", at that Marina always starts with \"Loves\". There are n camomiles growing in the field, possessing the numbers of petals equal to a1, a2, ... an. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be \"Loves\". Help her do that; find the maximal number of petals possible in the bouquet.", "input_spec": "The first line contains an integer n (1 ≤ n ≤ 100), which is the number of flowers growing in the field. The second line contains n integers ai (1 ≤ ai ≤ 100) which represent the number of petals on a given i-th camomile.", "output_spec": "Print a single number which is the maximal number of petals in the bouquet, the fortune telling on which would result in \"Loves\". If there are no such bouquet, print 0 instead. The bouquet may consist of a single flower.", "sample_inputs": ["1\n1", "1\n2", "3\n5 6 7"], "sample_outputs": ["1", "0", "13"], "notes": null}, "positive_code": [{"source_code": "'use strict';\n\n// let inpFileStrArr = `\n// 3\n// 5 6 7\n// `.trim().split('\\n'), inpFileCounter = 0;\n// function readline() {\n// return inpFileStrArr[inpFileCounter++];\n// }\n// function print(x) {\n// console.log(x);\n// }\n\nvar isEven = function isEven(x) {\n return x % 2 === 0;\n};\n\nvar n = Number(readline());\nvar arr = readline().split(' ').map(Number);\n\nvar sum = arr.reduce(function (a, b) {\n return a + b;\n}, 0);\n\nif (!isEven(sum)) {\n print(sum);\n} else {\n arr.sort(function (a, b) {\n return a - b;\n });\n var needToRemove = arr.find(function (x) {\n return !isEven(x);\n });\n print(needToRemove ? sum - needToRemove : 0);\n}\n"}, {"source_code": "'use strict'\n\nlet N = +readline()\nlet lll = readline().split(' ').map(v => parseInt(v)).sort((a, b) => b - a)\n\nlet ss = 0\nlet p = [0]\nlet t = false\n\nfor (let n of lll) {\n if (n % 2) {\n t = true\n p.push(n)\n if (p.length == 2) {\n ss += p[0]\n ss += p[1]\n p = []\n }\n } else {\n ss += n\n }\n}\n\nprint(t ? ss : 0)"}, {"source_code": "'use strict';\n/*\nlet input = `\n1\n1\n`.trim().split('\\n');\nfunction print(output) {\n\tconsole.log(output);\n}\nfunction readline() {\n\treturn input.shift();\n}\n*/\n//code\n\nvar n = Number(readline());\nvar flowers = readline().split(' ').map(Number);\nvar sum = flowers.reduce(function (acc, curr) {\n\treturn acc + curr;\n}, 0);\nvar minOdd = flowers.filter(function (el) {\n\treturn el % 2 === 1;\n}).sort(function (a, b) {\n\treturn a - b;\n}).shift();\nprint(sum % 2 === 1 ? sum : minOdd === undefined ? 0 : sum - minOdd);\n"}, {"source_code": "var getNums = function() {\n\treturn readline().split(' ').map(function(a) {return parseInt(a)});\n};\n\nvar n = parseInt(readline());\nvar nums = getNums().sort(function(a, b){return b - a});\nvar sumParnih = 0, sumNeparnih = 0, prob = 0;\n\nfor (var i = 0; i < n; i++) {\n\tif (nums[i] % 2 === 0) {\n\t\tsumParnih += nums[i];\n\t} else {\n\t\tif (sumNeparnih == 0) {\n\t\t\tsumNeparnih = nums[i];\n\t\t} else {\n\t\t\tif (prob) {\n\t\t\t\tsumNeparnih = sumNeparnih + prob + nums[i];\n\t\t\t\tprob = 0;\n\t\t\t} else {\n\t\t\t\tprob = nums[i];\n\t\t\t}\n\t\t}\n\t}\n}\n\nif (sumNeparnih === 0) {\n\tprint(0);\n} else {\n\tprint(sumParnih + sumNeparnih);\n}\n"}, {"source_code": "readline = require('readline')\nlet stdinInput = '';\n\nfunction file1(){\n //file\n var fs = require('fs');\n const inputfile = '_in.txt';\n const outputfile = '_out.txt';\n fs.writeFileSync(outputfile, '');\n var myInterface = readline.createInterface({\n input: fs.createReadStream(inputfile),\n });\n myInterface.on('line', function (line) {\n stdinInput += line+'\\n';\n }).on('close', () => {\n main(); \n process.exit(0);\n })\n}\n\nfunction std1(){\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (input) => { stdinInput += input; });\n process.stdin.on('end', () => { main(); });\n}\n /*\n * Api Scanner\n */\n class Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n \n nextLine() {\n this.index += 1;\n return this.lines[this.index].trim();\n }\n nextArray(fn) {\n const array = this.nextLine().split(' ');\n return fn === String ? array : array.map(fn);\n }\n \n hasNext() {\n return this.index < this.lines.length;\n }\n }\n \n// file1();\nstd1();\n\nlet n, a, sum1;\nfunction main() {\n const is = new Scanner();\n n = parseInt(is.nextLine());\n a = is.nextArray(Number);\n\n sum1 = 0;\n minle = 101;\n for(let i=0; i stop += c);\nprocess.stdin.on('end', () => { \n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n console.log(1, 1, k[0], k[1]);\n }\n});\n"}, {"source_code": "// var gcd = function(a, b) {\n// if (!b) {\n// return a;\n// }\n\n// return gcd(b, a % b);\n// }\nlet ryan = '';//.map(Number).sort(function(a, b){return a - b})\nprocess.stdin.on('data', c => ryan += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = ryan.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n; j++){\n var k = lines[j].split(' ').map(Number)\n console.log(1, 1, k[0], k[1])\n }\n});"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, m, i, j] = rna();\r\n\r\n\t\tconsole.log(1, 1, n, m);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar H = nextInt();\r\n\t\tvar W = nextInt();\r\n\t\tvar i = nextInt();\r\n\t\tvar j = nextInt();\r\n\t\tmyout(H + \" \" + W + \" 1 1\");\r\n\t}\r\n}\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n const nsc = parseInt(await getLine());\r\n for(let sc = 0; sc < nsc; sc++) {\r\n let n, m, i, j;\r\n [n, m, i, j] = (await getLine()).split(' ').map(num => parseInt(num));\r\n let bestDist = -1, best1x, best2x, best1y, best2y;\r\n let getDist = function(x,y, x2, y2) {\r\n return Math.abs(x-x2) + Math.abs(y-y2);\r\n }\r\n let test = function(x1, y1, x2, y2) {\r\n const dist = getDist(i, j, x1, y1) + getDist(x1, y1, x2, y2) + getDist(i, j, x2, y2);\r\n if (dist > bestDist) {\r\n bestDist = dist;\r\n best1x = x1;\r\n best2x = x2;\r\n best1y = y1;\r\n best2y = y2;\r\n }\r\n }\r\n test(1,1,n, m);\r\n test(1, 1, 1, m);\r\n test(1, 1, n, 1);\r\n test(n, m, n, 1);\r\n test(n, m, 1, m);\r\n test(1, m, n, 1);\r\n console.log([best1x, best1y, best2x, best2y].join(' '));\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "var matr = 'haha';\r\n\r\nfunction create(str) {\r\n var hahaIndexArr = [];\r\n for (var i = 0; i < str.length; i++) {\r\n var hasWrong = false;\r\n for (var j = 0; j < matr.length; j++) {\r\n if (str[i + j] !== matr[j]) {\r\n hasWrong = true;\r\n break;\r\n }\r\n }\r\n if (!hasWrong) {\r\n hahaIndexArr.push(i);\r\n }\r\n }\r\n if (hahaIndexArr.length === 0) {\r\n if (str.length < 8) {\r\n return [str, -1, str];\r\n }\r\n return [str.substr(0, 4), 0, str.substr(str.length - 4, 0)];\r\n }\r\n var preff = str.substr(0, Math.min(4, hahaIndexArr[0])) || 'ha';\r\n var suff = str.substr(Math.max(hahaIndexArr[hahaIndexArr.length - 1] + 4, str.length - 4)) || 'ha';\r\n return [preff, hahaIndexArr.length, suff];\r\n}\r\nfunction summ(a, b) {\r\n var createMiddle = create(a[2] + b[0]);\r\n if (a[1] === -1 && b[1] === -1) {\r\n return createMiddle;\r\n }\r\n var preff = a[1] === -1 ? createMiddle[0] : a[0];\r\n var suff = b[1] === -1 ? createMiddle[2] : b[2];\r\n var asum = a[1] === -1 ? 0 : a[1];\r\n var bsum = b[1] === -1 ? 0 : b[1];\r\n var midSum = createMiddle[1] === -1 ? 0 : createMiddle[1];\r\n return [preff, asum + bsum + midSum, suff];\r\n}\r\n\r\nfunction solve() {\r\n var nmij = readArray(Number);\r\n var n = nmij[0];\r\n var m = nmij[1];\r\n write('1 1 ' + n + ' ' + m)\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n}\r\ninit();\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var arr = lines[l++].split(' ').map(Number)\n console.log(solve(...arr).join(' '));\n }\n});\n\nfunction solve(row, col, r, c) {\n if (r === 1) {\n return [row, 1, row, col]\n } else if (r === row) {\n return [1, 1, 1, col]\n } else if (c === 1) {\n return [1, col, row, col]\n } else if (c === col) {\n return [1, 1, row, 1]\n } else {\n return [1, 1, row, col]\n }\n}\n"}, {"source_code": "var cases = +readline();\r\n\r\nfor (var i = 1; i<=cases; i++){\r\n inp = readline().split(' ').map(x=>+x);\r\n n = inp[0];\r\n m = inp[1];\r\n \r\n print(1,1,n,m);\r\n}\r\n"}], "negative_code": [{"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => { \n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n console.log(1, 1, k[2], k[3]);\n }\n});\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => { \n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var q = lines[i].split(' ').map(Number);\n var n = q[0], k = q[1];\n var b = 0;\n for(j = 2; j <= n; j++){\n if(n % j === 0){\n b = j;\n break;\n }\n }\n k--;\n n += b;\n n += (2*k);\n console.log(n);\n }\n});\n"}, {"source_code": "let ryan = '';//.map(Number).sort(function(a, b){return a - b})\nprocess.stdin.on('data', c => ryan += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = ryan.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n; j++){\n var k = lines[j].split('')\n if(k[k.length - 2] == 'c' && k[k.length - 1] == 'h' || k[k.length - 1] == 'x' || k[k.length - 1] == 's' ||k[k.length - 1] == 'o' ){\n if(k[k.length - 2] == 'c' && k[k.length - 1] == 'h' ){\n k.push('es')\n }else{\n k.push('es')\n \n }\n }\n else if(k[k.length - 2] == 'e' && k[k.length - 1] == 'f' || k[k.length - 1] == 'f'){\n if(k[k.length - 2] == 'e' && k[k.length - 1] == 'f'){\n k.splice(k.length - 2, 2)\n k.push('ves')\n }else{\n k.splice(k.length - 1, 1)\n k.push('ves')\n }\n }\n else if(k[k.length - 1] == 'y'){\n k.splice(k.length - 1, 1)\n k.push('ies')\n }\n else{\n k.push('s')\n }\n s = ''\n for(l = 0; l < k.length; l++){\n s+=k[l]\n }\n console.log(s)\n }\n \n \n});"}], "src_uid": "5aae6b27f35852512a250751ef957ab9"} {"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$$$) — 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$$$) — 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 inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let len = +readLine();\n const arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n arr.sort((a, b) => a - b);\n let count = 0;\n for (let i = 0; i < len - 1; i++) {\n if (Math.abs(arr[i] - arr[i + 1]) > 1) count++;\n }\n if (count) console.log(\"NO\");\n else console.log(\"YES\");\n }\n}\n"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nlet input = [];\n\nrl.on('line', function (line) {\n input.push(line);\n});\n\nrl.on('close', function () {\n const total = Number(input[0]);\n for (let ii = 0; ii < 2*total; ii +=2) {\n let output = \"Yes\";\n const len = Number(input[ii+1]);\n let arr = input[ii+2].split(' ').map(x => Number(x));\n arr.sort((a, b) => a - b);\n for (let i = 0; i < total-1; i++) {\n if (arr[i + 1] - arr[i] > 1) {\n output = \"No\";\n break;\n }\n }\n console.log(output); \n }\n});\n\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin\n});\n \nlet tests = [];\nrl.on('line', (line) => {\n tests.push(line);\n}).on('close', () => {\n for (ii = 1; ii < tests.length; ii+= 2) {\n const test = tests[ii + 1].split(' ').sort((a, b) => +a - +b);\n let count = 0;\n for(i = 0; i < test.length; i++) {\n\n if (\n !test[i + 1] || \n Math.abs(+test[i] - +test[i + 1]) > 1\n ) {\n count++;\n }\n }\n if (count > 1) {\n process.stdout.write(`NO\\n`);\n } else {\n process.stdout.write(`YES\\n`);\n }\n }\n});"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + end + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var n = nextInt();\n var list = nextIntArray();\n list.sort(function(a,b){\n return a - b;\n });\n var isOK = true;\n for(var j = 0; j < n - 1; j++){\n if(Math.abs(list[j] - list[j + 1]) > 1){\n isOK = false;\n break;\n }\n }\n output[i] = (isOK) ? \"YES\" : \"NO\";\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\n\nconst runMain = () => {\n inputString = inputString.trim().split('\\n').map(string => string.trim());\n main();\n process.exit();\n}\nconst readLine = () => inputString[currentLine++];\n\nprocess.stdin.on('data', inputStdin => inputString += inputStdin);\nprocess.stdin.on('end', runMain);\nprocess.on('SIGINT', runMain);\n\nfunction main() {\n let t = readLine();\n while (t--) {\n const n = readLine();\n const a = readLine().split(' ').map(num => Number(num)).sort((a, b) => a - b);\n const res = a.reduce((acc, cur) => [cur, acc[1] + (Math.abs(acc[0] - cur) > 1 ? 1 : 0)], [a[0], 0]);\n console.log(res[1] > 0 ? 'NO' : 'YES');\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n\tdata = data.split('\\n');\n\tconst testCases = data[0] * 2;\n let i = 1;\n outer:\n\twhile (i <= testCases) {\n\t let n = data[i] * 1;\n\t let a = data[i + 1].trim().split(' ').map(Number);\n\t a.sort((a, b) => a - b);\n\t for (let j = 1; j < n; j += 1) {\n let diff = a[j] - a[j - 1];\n\t if (diff > 1) {\n\t console.log('NO');\n\t i += 2;\n\t continue outer;\n\t }\n\t }\n\t console.log('YES');\n i += 2;\n\t}\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n let t = +readline();\n for (let i = 0; i < t; i++) {\n const n = +readline();\n const a = readline().split(' ').map(x => parseInt(x)).sort((i, j) => i - j);\n let no = false;\n for (let j = 1; j < n; j++) {\n if (Math.abs(a[j] - a[j-1]) > 1) {\n print('NO\\n');\n no = true;\n break;\n }\n }\n if (!no) {\n print('YES\\n');\n }\n }\n}\n"}, {"source_code": "const readLine = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\n\nfunction splitAndParseInt(line) {\n return line.split(\" \").map((x) => parseInt(x));\n}\n\nreadLine.on(\"line\", (line) => input.push(line));\nreadLine.on(\"close\", () => {\n let t = parseInt(input[0]);\n\n for (let i = 1; i <= t * 2; i += 2) {\n const n = parseInt(input[i]);\n\n const nums = splitAndParseInt(input[i + 1]);\n nums.sort((a, b) => a - b);\n\n if (nums.length === 1) {\n console.log(\"YES\");\n continue;\n }\n\n let cnt = 0;\n for (let i = 1; i < nums.length; i += 1) {\n if (nums[i] - nums[i - 1] <= 1) cnt += 1;\n }\n\n if (nums.length - cnt <= 1) {\n console.log(\"YES\");\n } else {\n console.log(\"NO\");\n }\n }\n});\n"}, {"source_code": "const processData = (lines) => {\n let acc = 0\n const n = +lines[acc++]\n for (let i=0; i +x).sort((a, b) => a-b)\n let found = false\n for (let i=0; i 1) {\n found = true\n break\n }\n }\n\n console.log(found ? 'NO' : 'YES')\n }\n\n\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = ''\nlet currentLine = 0\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin\n})\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n')\n\n main()\n})\n\nfunction readLine() {\n return inputString[currentLine++]\n}\n\nconst s2i = s => parseInt(s, 10)\n\nconst readLineOfBigInts = () => {\n const split = readLine().split(' ')\n const result = []\n for (let i = 0, l = split.length; i < l; i++) {\n result.push(BigInt(split[i]));\n }\n return result\n}\n\nconst cmpi = (a, b) => a - b\n\nfunction main() {\n let T = s2i(readLine())\n let out = ''\n\n while (T--) {\n const n = s2i(readLine())\n const a = readLine().split(' ').map(s2i)\n\n let result = 'YES'\n\n a.sort(cmpi)\n\n for (let i = 1; i < a.length; i++) {\n if (a[i] - a[i-1] > 1) {\n result = 'NO'\n break\n }\n }\n\n out += result + '\\n'\n }\n\n console.log(out)\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tlet n = +readLine();\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => parseInt(x));\n\n\t\tarr.sort((a, b) => a - b);\n\t\tlet count = 0;\n\n\t\tfor (let i = 0; i < n - 1; i++) {\n\t\t\tlet diff = Math.abs(arr[i] - arr[i + 1]);\n\t\t\tif (diff > 1) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\n\t\tif (count) {\n\t\t\tconsole.log('NO');\n\t\t} else {\n\t\t\tconsole.log('YES');\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\n\t\tlet possible = true;\n\t\tarr.sort((a, b) => a - b);\n\n\t\tfor (let i = 1, l = arr.length; i < l; ++i) {\n\t\t\tlet diff = arr[i] - arr[i - 1];\n\t\t\tif (diff > 1) {\n\t\t\t\tpossible = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tpossible ? console.log('YES') : console.log('NO');\n\t}\n}\n"}, {"source_code": "function compare(x, y) {\n return (x < y) ? (- 1) : ((x > y) ? 1 : 0);\n}\n\nconst yes = 'YES';\nconst no = 'NO';\n\nfunction solve(xs) {\n if (xs.length < 1) {\n throw Error('input is empty');\n } else if (xs.length < 2) {\n return yes;\n } else {\n xs.sort(compare);\n let max_diff = 0;\n for (let i = 1; i < xs.length; i = i + 1) {\n const a = xs[i - 1];\n const b = xs[i];\n const diff = b - a;\n max_diff = Math.max(max_diff, diff);\n }\n return (max_diff < 2) ? yes : no;\n }\n}\n\nfunction main(lines) {\n for (let i = 1; (i + 1) < lines.length; i = i + 2) {\n const line = lines[i + 1];\n const t = line.trim();\n if (t.length > 0) {\n const xs = t.split(/\\s/).map(Number);\n const result = solve(xs);\n console.log(result)\n }\n }\n}\n\nasync function processLinesFromStream(rs, pf) {\n const content = [];\n rs.setEncoding(\"utf-8\");\n for await (let chunk of rs) {\n content.push(chunk);\n }\n const lines = content.join('').split(/\\n/);\n const result = pf(lines);\n return result;\n}\n\nprocessLinesFromStream(process.stdin, main);\n"}, {"source_code": "function compare(x, y) {\n return (x < y) ? (- 1) : ((x > y) ? 1 : 0);\n}\n\nconst yes = 'YES';\nconst no = 'NO';\n\nfunction solve(xs) {\n if (xs.length < 1) {\n throw Error('input is empty');\n } else if (xs.length < 2) {\n return yes;\n } else {\n xs.sort(compare);\n let max_diff = 0;\n for (let i = 1; i < xs.length; i = i + 1) {\n const a = xs[i - 1];\n const b = xs[i];\n const diff = b - a;\n max_diff = Math.max(max_diff, diff);\n }\n return (max_diff < 2) ? yes : no;\n }\n}\n\nfunction main(lines) {\n const whitespace = /\\s+/;\n for (let i = 1; (i + 1) < lines.length; i = i + 2) {\n const line = lines[i + 1];\n const xs = line.split(whitespace).map(Number);\n const result = solve(xs);\n console.log(result)\n }\n}\n\nfunction trim_line(s) {\n return s.trim();\n}\n\nfunction has_content(s) {\n return (s.length > 0);\n}\n\nasync function processLinesFromStream(rs, pf) {\n const chunks = [];\n const encoding = 'utf-8';\n rs.setEncoding(encoding);\n for await (let chunk of rs) {\n chunks.push(chunk);\n }\n const empty = '';\n const newline = /\\n/;\n const lines = chunks.join(empty)\n .split(newline)\n .map(trim_line)\n .filter(has_content);\n const result = pf(lines);\n return result;\n}\n\nprocessLinesFromStream(process.stdin, main);\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n const N = readline();\n\n for (let t = 0; t < N; ++t) {\n const b = readline();\n const arr = readline()\n .split(\" \")\n .map((x) => parseInt(x));\n\n arr.sort((i, j) => i - j);\n\n let isYes = true;\n for (let k = 1; k < arr.length; ++k) {\n if (arr[k] - arr[k - 1] > 1) {\n print(\"NO\\n\");\n isYes = false;\n break;\n }\n }\n\n if (isYes) {\n print(\"YES\\n\");\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = ''\nlet currentLine = 0\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin\n})\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n')\n \n main()\n})\n \nfunction readLine() {\n return inputString[currentLine++]\n}\n \nconst s2i = s => parseInt(s, 10)\n \nconst readLineOfBigInts = () => {\n const split = readLine().split(' ')\n const result = []\n for (let i = 0, l = split.length; i < l; i++) {\n result.push(BigInt(split[i]));\n }\n return result\n}\n \nconst cmpi = (a, b) => a - b\n \nfunction main() {\n let T = s2i(readLine())\n let out = ''\n \n while (T--) {\n const n = s2i(readLine())\n const a = readLine().split(' ').map(s2i)\n \n let result = 'YES'\n \n a.sort(cmpi)\n \n for (let i = 1; i < a.length; i++) {\n if (a[i] - a[i-1] > 1) {\n result = 'NO'\n break\n }\n }\n \n out += result + '\\n'\n }\n \n console.log(out)\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main(){\n let t = parseInt(readline());\n for(let i = 0; i < t; i++){\n let n = parseInt(readline());\n let arr = readline().split(' ');\n arr.sort((a,b) => a-b);\n let flag = true;\n for(let j = 1; j < arr.length; j++){\n if(parseInt(arr[j])-parseInt(arr[j-1]) > 1){\n flag = false;\n console.log('NO');\n break;\n }\n }\n\n if(flag)\n console.log('yes');\n }\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction lcm(a, b) {\n return (a / gcd(a, b) * b);\n}\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r x - y);\n if(a.length === 1) {\n console.log('YES');\n return;\n }\n\n for(let i=1;i 1) {\n console.log('NO');\n return;\n }\n }\n\n console.log('YES');\n\n}\n\n"}, {"source_code": "function solve() {\n var n = readInt()\n var arr = readIntArray().sort((a, b) => a - b)\n\n var prevNum = arr[0]\n var i\n for(i=1; i 1) {\n print(\"NO\")\n return\n }\n prevNum = arr[i]\n }\n print(\"YES\")\n}\n\nvar testCases = readInt();\nvar testCaseNum;\nfor(testCaseNum=0; testCaseNum {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let len = +readLine();\n const arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n arr.sort((a, b) => a - b);\n let count = 0;\n for (let i = 0; i < len - 1; i++) {\n if (Math.abs(arr[i] - arr[i + 1]) === 2) count++;\n }\n if (count) console.log(\"NO\");\n else console.log(\"YES\");\n }\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n let t = +readline();\n for (let i = 0; i < t; i++) {\n const n = +readline();\n const a = readline().split(' ').map(x => parseInt(x));\n let no = false;\n for (let j = 1; j < n; j++) {\n if (Math.abs(a[j] - a[j-1]) > 1) {\n print('NO\\n');\n no = true;\n break;\n }\n }\n if (!no) {\n print('YES\\n');\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = ''\nlet currentLine = 0\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin\n})\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n')\n\n main()\n})\n\nfunction readLine() {\n return inputString[currentLine++]\n}\n\nconst s2i = s => parseInt(s, 10)\n\nconst readLineOfBigInts = () => {\n const split = readLine().split(' ')\n const result = []\n for (let i = 0, l = split.length; i < l; i++) {\n result.push(BigInt(split[i]));\n }\n return result\n}\n\nfunction main() {\n let T = s2i(readLine())\n let out = ''\n\n while (T--) {\n const n = s2i(readLine())\n const a = readLine().split(' ').map(s2i)\n\n let result = 'Yes'\n\n a.sort()\n\n for (let i = 1; i < a.length; i++) {\n if (a[i] - a[i-1] > 1) {\n result = 'NO'\n break\n }\n }\n\n out += result + '\\n'\n }\n\n console.log(out)\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = ''\nlet currentLine = 0\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin\n})\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n')\n\n main()\n})\n\nfunction readLine() {\n return inputString[currentLine++]\n}\n\nconst s2i = s => parseInt(s, 10)\n\nconst readLineOfBigInts = () => {\n const split = readLine().split(' ')\n const result = []\n for (let i = 0, l = split.length; i < l; i++) {\n result.push(BigInt(split[i]));\n }\n return result\n}\n\nfunction main() {\n let T = s2i(readLine())\n let out = ''\n\n while (T--) {\n const n = s2i(readLine())\n const a = readLine().split(' ').map(s2i)\n\n let result = 'YES'\n\n a.sort()\n\n for (let i = 1; i < a.length; i++) {\n if (a[i] - a[i-1] > 1) {\n result = 'NO'\n break\n }\n }\n\n out += result + '\\n'\n }\n\n console.log(out)\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\n\t\tlet possible = true;\n\t\tarr.sort();\n\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tlet diff = arr[i] - arr[i - 1];\n\t\t\tif (diff > 1) {\n\t\t\t\tpossible = false;\n\t\t\t}\n\t\t}\n\n\t\tif (possible) {\n\t\t\tconsole.log('YES');\n\t\t} else {\n\t\t\tconsole.log('NO');\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\n\t\tif (n === 1) {\n\t\t\tconsole.log('YES');\n\t\t\treturn;\n\t\t}\n\n\t\tlet possible = true;\n\t\tarr.sort();\n\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tlet diff = Math.abs(arr[i] - arr[i - 1]);\n\t\t\tif (diff > 1) {\n\t\t\t\tpossible = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tpossible ? console.log('YES') : console.log('NO');\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\t\tarr.sort();\n\t\tlet flag = true;\n\n\t\tfor (let i = 0; i < n - 1; i++) {\n\t\t\tif (Math.abs(arr[i] - arr[i + 1]) > 1) {\n\t\t\t\tflag = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tflag ? console.log('YES') : console.log('NO');\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tlet n = +readLine();\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => parseInt(x));\n\n\t\tlet possible = true;\n\t\tarr.sort();\n\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tlet diff = arr[i] - arr[i - 1];\n\t\t\tif (diff > 1) {\n\t\t\t\tpossible = false;\n\t\t\t}\n\t\t}\n\n\t\tif (possible) {\n\t\t\tconsole.log('YES');\n\t\t} else {\n\t\t\tconsole.log('NO');\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tlet n = +readLine();\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => parseInt(x));\n\n\t\tarr.sort((a, b) => a - b);\n\t\tconsole.log(arr);\n\t\tlet count = 0;\n\n\t\tfor (let i = 0; i < n - 1; i++) {\n\t\t\tlet diff = Math.abs(arr[i] - arr[i + 1]);\n\t\t\tif (diff > 1) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\n\t\tif (count) {\n\t\t\tconsole.log('NO');\n\t\t} else {\n\t\t\tconsole.log('YES');\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tlet n = +readLine();\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => parseInt(x));\n\n\t\tarr.sort();\n\t\tlet count = 0;\n\n\t\tfor (let i = 0; i < n - 1; i++) {\n\t\t\tlet diff = Math.abs(arr[i] - arr[i + 1]);\n\t\t\tif (diff > 1) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\n\t\tif (count) {\n\t\t\tconsole.log('NO');\n\t\t} else {\n\t\t\tconsole.log('YES');\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\n\t\tlet possible = true;\n\t\tarr.sort();\n\n\t\tfor (let i = 1, l = arr.length; i < l; ++i) {\n\t\t\tlet diff = arr[i] - arr[i - 1];\n\t\t\tif (diff > 1) {\n\t\t\t\tpossible = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tpossible ? console.log('YES') : console.log('NO');\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tlet n = +readLine();\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => parseInt(x));\n\n\t\tlet possible = true;\n\t\tarr.sort();\n\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tlet diff = arr[i] - arr[i - 1];\n\t\t\tif (diff > 1) {\n\t\t\t\tpossible = false;\n\t\t\t}\n\t\t}\n\n\t\tif (possible) {\n\t\t\tconsole.log('YES');\n\t\t} else {\n\t\t\tconsole.log('NO');\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\n\t\tif (n === 1) {\n\t\t\tconsole.log('YES');\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet possible = true;\n\t\tarr.sort();\n\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tlet diff = Math.abs(arr[i] - arr[i - 1]);\n\t\t\tif (diff > 1) {\n\t\t\t\tpossible = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tpossible ? console.log('YES') : console.log('NO');\n\t}\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n const N = readline();\n\n for (let i = 0; i < N; ++i) {\n const arr = readline()\n .split(\" \")\n .map((x) => parseInt(x));\n\n arr.sort();\n\n const isYes = arr.every((x, i) => {\n if (i < 1) {\n return true;\n } else if (Math.abs(x - arr[i - 1]) <= 1) {\n return true;\n } else {\n return false;\n }\n });\n\n if (isYes) {\n print(\"YES\");\n } else {\n print(\"NO\");\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n const N = readline();\n\n for (let t = 0; t < N; ++t) {\n const b = readline();\n const arr = readline()\n .split(\" \")\n .map((x) => parseInt(x));\n\n arr.sort();\n\n let isYes = true;\n for (let k = 1; k < arr.length; ++k) {\n if (arr[k] - arr[k - 1] > 1) {\n print(\"NO\\n\");\n isYes = false;\n break;\n }\n }\n\n if (isYes) {\n print(\"YES\\n\");\n }\n }\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n \nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n const N = readline();\n\n for (let i = 0; i < N; ++i) {\n const arr = readline()\n .split(\" \")\n .map((x) => parseInt(x));\n\n arr.sort();\n\n const isYes = arr.every((x, i) => {\n if (i < 1) {\n return true;\n } else if (Math.abs(x - arr[i - 1]) <= 1) {\n return true;\n } else {\n return false;\n }\n });\n\n if (isYes) {\n print(\"YES\");\n } else {\n print(\"NO\");\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n const N = readline();\n\n for (let t = 0; t < N; ++t) {\n const arr = readline()\n .split(\" \")\n .map((x) => parseInt(x));\n\n arr.sort();\n\n const isYes = arr.every((x, i) => {\n if (i < 1) {\n return true;\n } else if (Math.abs(x - arr[i - 1]) <= 1) {\n return true;\n } else {\n return false;\n }\n });\n\n if (isYes) {\n print(\"YES\");\n } else {\n print(\"NO\");\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n const N = readline();\n\n for (let t = 0; t < N; ++t) {\n const b = readline();\n const arr = readline()\n .split(\" \")\n .map((x) => parseInt(x));\n\n arr.sort();\n\n let isYes = true;\n for (let k = 1; k < arr.length; ++k) {\n if (arr[k] - arr[k - 1] > 1) {\n print(\"NO\");\n isYes = false;\n break;\n }\n }\n\n if (isYes) {\n print(\"YES\");\n }\n }\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction lcm(a, b) {\n return (a / gcd(a, b) * b);\n}\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r 1) {\n console.log('NO');\n return;\n }\n }\n\n console.log('YES');\n\n}\n\n"}, {"source_code": "function solve() {\n var n = readInt()\n var arr = readIntArray().map( x => x * 1).sort()\n\n var prevNum = arr[0]\n var i\n for(i=1; i 1) {\n print(\"NO\")\n return\n }\n prevNum = arr[i]\n }\n print(\"YES\")\n}\n\nvar testCases = readInt();\nvar testCaseNum;\nfor(testCaseNum=0; testCaseNum 1) {\n print(\"NO\")\n return\n }\n prevNum = arr[i]\n }\n print(\"YES\")\n}\n\nvar testCases = readInt();\nvar testCaseNum;\nfor(testCaseNum=0; testCaseNum0) {\n positivex += 1;\n } else {\n negativex += 1; \n \n } \n }\n\t\n\tif (positivex===1 || positivex===0) {\t\n\t\twrite(\"Yes\");\n\t} else if (negativex===1 || negativex===0) {\n\t\twrite(\"Yes\");\n\t} else {\n\t\twrite(\"No\");\n\t}"}, {"source_code": "var num = parseInt(readline());\nvar xPos = 0;\nvar xNeg = 0;\nvar canBeDone = true;\n\nfor (var i = 0; i < num; i++) {\n var x = readline().split(' ').map(function(element) {\n return parseInt(element);\n })[0];\n\n if (x > 0) {\n xPos++;\n } else {\n xNeg++;\n }\n\n if (xPos > 1 && xNeg > 1) {\n canBeDone = false;\n print('No');\n break;\n }\n}\n\nif (canBeDone) {\n print('Yes');\n}\n"}, {"source_code": "var num = parseInt(readline());\nvar dev = 0;\n\nfor (var i = 0; i < num; i++) {\n var x = readline().split(' ').map(function(element) {\n return parseInt(element);\n })[0];\n\n if (x > 0) {\n dev++;\n } else {\n dev--;\n }\n}\n\nif (num - Math.abs(dev) <= 2) {\n print('Yes');\n} else {\n print('No');\n}\n"}, {"source_code": "var n = parseInt(readline());\nvar l = 0, r = 0;\nfor (var i = 0; i < n; i++) {\n var arr = readline().split(\" \");\n if (parseInt(arr[0]) < 0) {\n l++;\n } else {\n r++;\n }\n}\nif ((r === 1 || l === 1) || (l === 0 && r !== 0) || (l !== 0 && r === 0)) {\n print(\"Yes\");\n} else {\n print(\"No\");\n}"}, {"source_code": "function toInt(x) {\n\treturn parseInt(x);\n}\n\nvar n = toInt(readline());\nvar x, plus = 0, minus = 0;\n\nfor (var i = 0; i < n; i++) {\n\tx = readline().split(\" \").map(toInt);\n\tif (x[0] < 0) {\n\t\tminus++;\n\t} else {\n\t\tplus++;\n\t}\n}\n\nif (plus > 1 && minus > 1) {\n\tprint(\"NO\");\n} else {\n\tprint(\"YES\");\n}"}, {"source_code": "var n = readline();\nvar positiveCount = 0;\nvar negativeCount = 0;\nfor (var i = 0; i < n; i++) {\n var point = parseInt(readline());\n if (point > 0) {\n positiveCount++;\n } else {\n negativeCount++;\n }\n if (positiveCount > 1 && negativeCount > 1) {\n print('No');\n break;\n }\n}\nif (positiveCount <= 1 || negativeCount <= 1) {\n print('Yes');\n}"}, {"source_code": "function main() {\n var n = readline();\n\n var numNeg = 0;\n var numPos = 0;\n\n for (var i = 0; i < n; i++) {\n var x = readline().split(' ')[0];\n\n if (x > 0) {\n numPos++;\n } else {\n numNeg++;\n }\n }\n\n print(numPos < 2 || numNeg < 2 ? 'Yes' : 'No');\n}\n\nmain();\n"}, {"source_code": "var n = Number(readline());\nvar min = 0, plu = 0;\nfor(var i = 0; i < n; i++){\n var c = readline().split(' ').map(Number);\n if(c[0] < 0)\n min++;\n else\n plu++;\n}\nif(min <=1 || plu <=1)\nprint(\"Yes\");\nelse\nprint(\"No\");"}, {"source_code": "n=Number(readline())\nvar A=[]\nfor (var i=0;ia+(v<0),0)\nprint((!ne || ne===1 || ne===(n-1) || ne===n)?'Yes':'No')"}, {"source_code": "var n=readline();\nn=parseInt(n);\nvar cordinate,x,y;\nvar positivex=0;\nvar negativex=0;\n \n \n for (var i=0;i0) {\n positivex += 1;\n } else {\n negativex += 1; \n \n } \n }\n\t\n\tif (positivex===1 || positivex===0) {\t\n\t\twrite(\"Yes\");\n\t} else if (negativex===1 || negativex===0) {\n\t\twrite(\"Yes\");\n\t} else {\n\t\twrite(\"No\");\n\t}"}, {"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n')\n const n = parseInt(arr.shift())\n let xg = 0\n let xl = 0\n for(let i = 0; i < n; i ++) {\n const co = arr[i].split(' ')\n if(parseInt(co[0]) > 0) xg++\n else xl ++\n }\n if((xg <= 1 && xl >= 0) || (xl <= 1 && xg >= 0)) {\n console.log('Yes')\n }\n else {\n console.log('No')\n }\n \n})"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var L = 0;\n var R = 0;\n for(var i = 0; i < N; i++){\n var tmp = nextIntArray();\n if(tmp[0] < 0){\n L++;\n }else{\n R++;\n }\n }\n if(L > 1 && R > 1){\n myout(\"No\");\n }else{\n myout(\"Yes\");\n }\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet L = 0;\nlet R = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const [x, y] = d.split(' ').map(Number);\n\n if (x > 0) {\n R++;\n }\n else {\n L++;\n }\n\n c++;\n});\n\nrl.on('close', () => {\n if (L <= 1 || R <= 1) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n});\n"}], "negative_code": [{"source_code": "var num = parseInt(readline());\nvar dev = 0;\n\nfor (var i = 0; i < num; i++) {\n var x = readline().split(' ').map(function(element) {\n return parseInt(element);\n })[0];\n\n if (x > 0) {\n dev++;\n } else {\n dev--;\n }\n}\nprint(dev);\nif (num - Math.abs(dev) <= 2) {\n print('Yes');\n} else {\n print('No');\n}\n"}, {"source_code": "function toInt(x) {\n\treturn parseInt(x);\n}\n\nvar n = toInt(readline());\nvar x, plus = 0, minus = 0;\n\nfor (var i = 0; i < n; i++) {\n\tx = readline().split(\" \").map(toInt);\n\tif (x[0] < 0) {\n\t\tminus++;\n\t} else {\n\t\tplus++;\n\t}\n}\n\nif (Math.abs(plus-minus) < 2) {\n\tprint(\"YES\");\n} else {\n\tprint(\"NO\");\n}"}, {"source_code": "function main() {\n var n = readline();\n\n var numNeg = 0;\n var numPos = 0;\n\n for (var i = 0; i < n; i++) {\n var y = readline().split(' ')[1];\n\n if (y > 0) {\n numPos++;\n } else {\n numNeg++;\n }\n }\n\n print(numPos < 2 || numNeg < 2 ? 'Yes' : 'No');\n}\n\nmain();\n"}, {"source_code": "var n=readline();\nn=parseInt(n);\nvar cordinate,x,y;\nvar positivex=0;\nvar negativex=0;\n \n \n for (var i=0;i0) {\n positivex += 1;\n } else {\n negativex += 1; \n \n } \n }\n\t\n\tif (positivex===1) {\t\n\t\twrite(\"Yes\");\n\t} else if (negativex===1) {\n\t\twrite(\"Yes\");\n\t} else {\n\t\twrite(\"No\");\n\t}"}], "src_uid": "cf7bf89a6038586b69d3b8021cee0b27"} {"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$$$) — 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": "'use strict';\n\nconst parseProblem = (line, problem) => {\n if (!problem.T || problem.T === 0) {\n const result = {problem,\n T: parseInt(line),\n isProcessing: true,\n cases: []\n };\n return result;\n }\n\n const cases = problem.cases;\n\n if (cases.length === 0 || !cases[cases.length - 1].isProcessing) {\n cases.push({\n t: line\n });\n }\n\n const isProcessing = cases.length < problem.T;\n problem.isProcessing = isProcessing;\n\n return problem;\n};\n\nconst solve = data => {\n const [n, k] = data.t.split(' ');\n let result = [];\n\n const v1 = n - (k - 1);\n const v2 = n - 2 * (k - 1);\n\n if(v1 > 0 && v1 % 2 == 1) {\n for(let i = 0; i < k - 1; i++) {\n result.push(1);\n }\n result.push(v1);\n } else if (v2 > 0 && v2 % 2 == 0) {\n for(let i = 0; i < k - 1; i++) {\n result.push(2);\n }\n result.push(v2);\n }\n\n return result;\n}\n\nconst solveCases = cases => {\n for (let index = 0; index < cases.length; index++) {\n const result = solve(cases[index]);\n console.log((result.length) ? ('YES' + '\\n' + result.join(' ')) : 'NO');\n }\n};\n\nconst main = () => {\n const readline = require('readline');\n\n let problem = {\n T: 0,\n cases: [],\n isProcessing: true\n };\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n rl.on('line', line => {\n problem = parseProblem(line, problem);\n\n if (!problem.isProcessing) {\n rl.close();\n }\n }).on('close', () => {\n solveCases(problem.cases);\n process.exit(0);\n });\n};\n\nif (!module.parent) {\n main();\n}"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n\n\nfunction main() {\n const t = parseInt(readLine(), 10);\n for (let j = 0;jparseInt(x));\n if (k % 2 == 0 && n % 2 != 0) {\n console.log('NO')\n continue;\n }\n\n let solution = [];\n let odd = k % 2 == 0 || n % 2 != 0;\n let sum = 0;\n\n for (let i = 0; i 0 && (N - (K - 1) * 2) % 2 == 0){\n\t\t\toutput.push(\"YES\");\n\t\t\tvar list = new Array(K);\n\t\t\tlist.fill(2);\n\t\t\tlist[K - 1] = N - (K - 1) * 2;\n\t\t\toutput.push(myconv(list,8));\n\t\t\tcontinue;\n\t\t}\n\t\toutput.push(\"NO\");\n\t\t\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "\"use strict\";\nvar __spreadArrays = (this && this.__spreadArrays) || function () {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n};\nexports.__esModule = true;\nvar str = \"\", lines = [], idxLine = 0;\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', function (x) { str += x; });\nprocess.stdin.on('end', function () {\n lines = str.trim().split('\\n').map(function (x) { return x.trim(); });\n main();\n});\nfunction readline() {\n return lines[idxLine++];\n}\nvar print = console.log;\n//===============================\n//===============================\nfunction main() {\n var t = parseInt(readline());\n for (var _ = 0; _ < t; _++) {\n var _a = readline().split(\" \").map(function (e) { return parseInt(e); }), n = _a[0], k = _a[1];\n var a = n - (k - 1);\n var b = n - (k - 1) * 2;\n var x = [];\n if (a > 0 && a % 2 != 0) {\n x = __spreadArrays([a], (Array(k - 1).fill(1)));\n }\n else if (b > 0 && b % 2 == 0) {\n x = __spreadArrays([b], (Array(k - 1).fill(2)));\n }\n if (x.length) {\n print(\"YES\");\n print(x.join(\" \"));\n }\n else {\n print(\"NO\");\n }\n }\n}\n"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n\n\n\n\n\n function foo (num, col) {\n let body = col - 1;\n let rest = num - body;\n let arr = [];\n\n if (rest <= 0) return ['NO'];\n if (rest%2 === 1) {\n arr = Array(body).fill(1);\n arr.push(rest);\n return ['YES', arr.join(' ')];\n }\n\n body = 2 * (col - 1);\n rest = num - body;\n\n if (rest <= 0) return ['NO'];\n if (rest%2 === 0) {\n arr = Array(body/2).fill(2);\n arr.push(rest);\n return ['YES', arr.join(' ')]\n }\n\n return ['NO'];\n }\n\n let testCount = 1;\n let answer = '';\n while(testCount <= +lines[0]) {\n let data = lines[testCount].split(\" \").map(Number);\n let result = foo(data[0], data[1]);\n answer += result[0] +\"\\n\";\n if (result[1]) answer += result[1] +\"\\n\";\n testCount++;\n }\n console.log(answer);\n})"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x)\n\n if (a%2 === 1 && k%2 === 1) {\n if (k > a) {\n console.log('NO')\n } else {\n console.log('YES')\n const res = Array(k).fill(1)\n res[0] = a-k+1\n console.log(res.join(' '))\n }\n } else {\n if (a%2 === 1 && k%2 === 0) {\n console.log('NO')\n } else {\n if (k%2 === 0) {\n if (k>a) {\n console.log('NO')\n } else {\n console.log('YES')\n const res = Array(k).fill(1)\n res[0] = a-k+1\n console.log(res.join(' '))\n }\n } else {\n const min = k*2\n if (min > a) {\n console.log('NO')\n } else {\n console.log('YES')\n const res = Array(k).fill(2)\n res[0] = a-k*2+2\n console.log(res.join(' '))\n }\n }\n }\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\n// your code goes here\n\n// declare global variables\nvar input_stdin = \"\";\nvar noOfTestcase = 0;\n\n// standard input is stored into input_stdin\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\n// standard input is done and stored into an array\nprocess.stdin.on('end', function () {\n chunks = input_stdin.split(\"\\n\");\n noOfTestcase = chunks[0];\n process.stdout.write('\\n');\n for(let i=1; i < chunks.length; i++){\n let row = chunks[i].split(\" \");\n if(isNaN(row[0]) || isNaN(row[1])){\n // do nothing\n }else{\n start(Number(row[0]), Number(row[1]));\n }\n }\n});\n\nfunction isEven(val){\n if(val%2 == 0){\n return true\n }\n return false\n}\n\nfunction start(sum,K){\n // console.log(\"sum = \",sum, \" K=\",K);\n let eS = isEven(sum);\n let eK = isEven(K);\n // console.log(\"eS = \",eS, \" eK=\",eK);\n if(sum < K ){\n // console.log(\"less than\");\n process.stdout.write(\"NO\"+ '\\n');\n }else if (!eS && eK) {\n // console.log(\"odd - even condition\");\n process.stdout.write(\"NO\"+ '\\n');\n }else if (eS && !eK && sum < (2*K)) {\n // console.log(\"even - odd but twice condition\");\n process.stdout.write(\"NO\"+ '\\n');\n }else {\n process.stdout.write(\"YES\"+ '\\n');\n let str = \"\"\n if(!eS){\n for(let k=1; k < K; k++){\n str +=\"1 \"\n }\n str+=(sum-K+1)\n }else{\n if(!eK){\n for(let k=1; k < K; k++){\n str +=\"2 \"\n }\n str+=(sum-(2*K)+2)\n }else{\n for(let k=1; k < K; k++){\n str +=\"1 \"\n }\n str+=(sum-K+1)\n }\n }\n process.stdout.write(str+ '\\n');\n }\n return;\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction solve(n, k) {\n let res = [];\n let total = 0;\n let base = 1;\n for (let i = 1; i <= k; i++) {\n if (i === k) {\n let last = n - total;\n if (last > 0 && last % 2 === 1) {\n res.push(last);\n return res;\n }\n }\n res.push(base);\n total += base;\n }\n res = [];\n total = 0;\n base = 2;\n for (let i = 1; i <= k; i++) {\n if (i === k) {\n let last = n - total;\n if (last > 0 && last % 2 === 0) {\n res.push(last);\n return res;\n }\n }\n res.push(base);\n total += base;\n }\n return 0;\n}\n\nfunction main() {\n const t = parseInt(readLine());\n for (let i = 0; i < t; i++) {\n let [n, k] = readLine().split(' ').map((val) => parseInt(val));\n // let a = readLine().split(' ').map((val) => parseInt(val));\n let res = solve(n, k);\n if (res.length > 0) console.log('YES', res.join(' '));\n else console.log('NO');\n }\n //process.stdout.write(\"hello: \");\n}\n"}, {"source_code": "\"use strict\";\n\n\nvar ans =\"\";\n \nfunction hasEven(x1 , x2){\n \n\tans =\"\";\n \n\tvar eq1 =(x2 -1) *2;\n\tvar eq2 =x1 -eq1;\n \n\tif(eq2 >0 && !(eq2 &1) && eq1 +eq2 ==x1){\n \n x2 --;\n while(x2 --) ans +=\" \" +'2';\n ans +=\" \" +eq2.toString();\n \n return \"YES\";\n \n }\n return \"NO\";\n \n}\n \n \nfunction hasOdd(x1 , x2){\n \n\tans =\"\";\n \n\tvar eq1 =(x2 -1);\n\tvar eq2 =x1 -eq1;\n \n\tif(eq2 >0 && (eq2 &1) && eq1 +eq2 ==x1){\n \n x2 --;\n while(x2 --) ans +=\" \" +'1';\n ans +=\" \" +eq2.toString();\n \n return \"YES\";\n \n }\n return \"NO\";\n \n}\n \n \nvar cases =parseInt(readline());\n \nwhile(cases --){\n \n\tans =\"\";\n\tvar read =readline().split(\" \");\n\tvar n =parseInt(read[0]);\n\tvar k =parseInt(read[1]);\n \n\tif(k <=n && hasEven(n , k) ==\"YES\"){\n \n\t\tprint(\"YES\");\n\t\tprint(ans.trim());\n \n \n\t}else if(k <=n && hasOdd(n , k) ==\"YES\"){\n \n\t\tprint(\"YES\");\n\t\tprint(ans.trim());\n \n\t}else{\n\t\tprint(\"NO\");\n\t}\n \n}"}, {"source_code": "\nvar ans =\"\";\n \nfunction hasEven(x1 , x2){\n \n\tans =\"\";\n \n\tvar eq1 =(x2 -1) *2;\n\tvar eq2 =x1 -eq1;\n \n\tif(eq2 >0 && !(eq2 &1) && eq1 +eq2 ==x1){\n \n x2 --;\n while(x2 --) ans +=\" \" +'2';\n ans +=\" \" +eq2.toString();\n \n return \"YES\";\n \n }\n return \"NO\";\n \n}\n \n \nfunction hasOdd(x1 , x2){\n \n\tans =\"\";\n \n\tvar eq1 =(x2 -1);\n\tvar eq2 =x1 -eq1;\n \n\tif(eq2 >0 && (eq2 &1) && eq1 +eq2 ==x1){\n \n x2 --;\n while(x2 --) ans +=\" \" +'1';\n ans +=\" \" +eq2.toString();\n \n return \"YES\";\n \n }\n return \"NO\";\n \n}\n \n \nvar cases =parseInt(readline());\n \nwhile(cases --){\n \n\tans =\"\";\n\tvar read =readline().split(\" \");\n\tvar n =parseInt(read[0] , 10);\n\tvar k =parseInt(read[1] , 10);\n \n\tif(k <=n && hasEven(n , k) ==\"YES\"){\n \n\t\tprint(\"YES\");\n\t\tprint(ans.trim());\n \n \n\t}else if(k <=n && hasOdd(n , k) ==\"YES\"){\n \n\t\tprint(\"YES\");\n\t\tprint(ans.trim());\n \n\t}else{\n\t\tprint(\"NO\");\n\t}\n \n}"}, {"source_code": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var nk = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n var n = nk[0],\n k = nk[1];\n var res = \"\";\n var flag = false;\n if (n % k == 0) {\n for (var j = 0; j < k; j++) {\n res += \" \" + n / k;\n flag = true;\n }\n } else if (n - k + 1 < 2) res = \"No\";\n else {\n if (n % 2 == 0) {\n if (k % 2 == 0) {\n res += n - k + 1;\n for (var i = 0; i < k - 1; i++) res += \" \" + 1;\n flag = true;\n } else {\n if (n - 2 * (k - 1) >= 4) {\n res += n - 2 * (k - 1);\n for (var i = 0; i < k - 1; i++) res += \" \" + 2;\n flag = true;\n } else res = \"No\";\n }\n } else {\n if (k % 2 == 0) {\n res = \"No\";\n } else {\n res += n - k + 1;\n for (var i = 0; i < k - 1; i++) res += \" \" + 1;\n flag = true;\n }\n }\n }\n if (flag) {\n print(\"Yes\");\n print(res.trim());\n } else print(res.trim());\n}\n"}, {"source_code": "function main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var nk = readline().split(\" \").map(Number);\n var n = nk[0];\n var k = nk[1];\n\n var nk1 = n - k + 1;\n var arr = new Array(k - 1).fill(1);\n if (nk1 % 2 === 1 && nk1 > 0) {\n arr.push(nk1);\n print(\"YES\");\n print(arr.join(\" \"));\n continue;\n }\n\n var nk2 = n - (k - 1) * 2;\n var arr2 = new Array(k - 1).fill(2);\n if (nk2 % 2 === 0 && nk2 > 0) {\n arr2.push(nk2);\n print(\"YES\");\n print(arr2.join(\" \"));\n continue;\n }\n print(\"NO\");\n }\n}\n\nmain();"}, {"source_code": "'use strict';\n\nlet t = parseInt(readline(), 10);\n\nwhile (t--) {\n const parts = readline().split(' ');\n let n = parseInt(parts[0], 10);\n let k = parseInt(parts[1], 10);\n\n function helper(N, K, result, sub) {\n const mod = sub % 2;\n while (N > 0 && K > 0) {\n if (N % K === 0 && N / K % 2 === mod) {\n const div = N / K;\n N -= div;\n K -= 1;\n result.push(div);\n } else {\n N -= sub;\n K -= 1;\n result.push(sub);\n }\n }\n return {N, K, result};\n }\n\n const resultOdd = helper(n, k, [], 1);\n const resultEven = helper(n, k, [], 2);\n\n if (resultOdd.N === 0 && resultOdd.K === 0) {\n print('YES');\n print(resultOdd.result.join(' '));\n } else if (resultEven.N === 0 && resultEven.K === 0) {\n print('YES');\n print(resultEven.result.join(' '));\n } else {\n print('NO');\n }\n}\n"}, {"source_code": "'use strict';\n\nlet t = parseInt(readline(), 10);\n\nwhile (t--) {\n const parts = readline().split(' ');\n let n = parseInt(parts[0], 10);\n let k = parseInt(parts[1], 10);\n\n function helper(N, K, result, sub) {\n while (K > 1) {\n N -= sub;\n K -= 1;\n result.push(sub);\n }\n if (N <= 0 || N % 2 !== sub % 2) {\n return null;\n }\n result.push(N);\n return result;\n }\n\n const resultOdd = helper(n, k, [], 1);\n const resultEven = helper(n, k, [], 2);\n\n if (resultOdd) {\n print('YES');\n print(resultOdd.join(' '));\n } else if (resultEven) {\n print('YES');\n print(resultEven.join(' '));\n } else {\n print('NO');\n }\n}\n"}, {"source_code": "'use strict';\n\nlet t = parseInt(readline(), 10);\n\nwhile (t--) {\n const parts = readline().split(' ');\n let n = parseInt(parts[0], 10);\n let k = parseInt(parts[1], 10);\n\n if (k > n) {\n print('NO');\n continue;\n }\n\n function helper(N, K, result, subs) {\n while (N > 0 && K > 0) {\n if (\n N % K === 0 &&\n (N / K) % 2 === (subs === 2 ? 0 : 1)\n ) {\n const div = N / K;\n N -= div;\n K -= 1;\n result.push(div);\n } else {\n N -= subs;\n K -= 1;\n result.push(subs);\n }\n }\n return {N, K, result};\n }\n\n const resultOdd = helper(n, k, [], 1);\n const resultEven = helper(n, k, [], 2);\n\n if (resultOdd.N === 0 && resultOdd.K === 0) {\n print('YES');\n print(resultOdd.result.join(' '));\n } else if (resultEven.N === 0 && resultEven.K === 0) {\n print('YES');\n print(resultEven.result.join(' '));\n } else {\n print('NO');\n }\n}\n"}, {"source_code": " var nCases = parseInt(readline());\n for (var i = 0; i < nCases; i++){\n \n var line = readline().split(\" \");\n var n = parseInt(line[0]);\n var k = parseInt(line[1]);\n \n var str = '';\n \n if (n % 2 === 0 && (n - ((k - 1) * 2)) % 2 === 0 && n - ((k - 1) * 2) > 0){\n print(\"YES\\n\");\n for (var j = 0; j < k - 1; j++){\n str += \"2 \";\n }\n str += \"\"+ (n - ((k - 1) * 2));\n }\n else if ((n - (k - 1)) % 2 !== 0 && (n - (k - 1)) % 2 > 0){\n print('YES\\n');\n for (var j = 0; j < k - 1; j++){\n str += '1 ';\n }\n str += '' + (n - (k - 1));\n }\n else{ \n print('NO\\n');\n continue;\n }\n print(str + '\\n');\n }"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nvar input = []\nrl.on('line', function(line){\n input.push(line);\n})\n\nrl.on(\"close\", ContestResponse); \n\n\nfunction ContestResponse(){\n let index = 0;\n var nCases = parseInt(input[index++]);\n for (let i = 0; i < nCases; i++){\n\n var line = input[index++].split(\" \");\n var n = parseInt(line[0]);\n var k = parseInt(line[1]);\n\n var str = '';\n\n if (n % 2 === 0 && (n - ((k - 1) * 2)) % 2 === 0 && n - ((k - 1) * 2) > 0){\n console.log(\"YES\");\n for (var j = 0; j < k - 1; j++){\n str += \"2 \";\n }\n str += \"\"+ (n - ((k - 1) * 2));\n }\n else if ((n - (k - 1)) % 2 !== 0 && (n - (k - 1)) % 2 > 0){\n console.log('YES');\n for (var j = 0; j < k - 1; j++){\n str += '1 ';\n }\n str += '' + (n - (k - 1));\n }\n else{ \n console.log('NO');\n continue;\n }\n console.log(str);\n }\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9\n\n\n\n\n**/\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r= n) {\n console.log('NO');\n continue;\n }\n\n output.push(n - count);\n console.log('YES');\n console.log(output.join(\" \"));\n }\n\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\n\nfunction main() {\n\n let cases = parseInt(readline(), 10);\n for (var X = 0; X < cases; X++) {\n const [n,k] = readline().split(\" \").map(e => parseInt(e));\n let result = new Array(k);\n\n let pairity = (k % 2) != (n %2) ? 0 : 1;\n if (pairity === 0) {\n result.fill(2);\n let first = n - ((k-1) * 2);\n if (first % 2 != 0 || first <= 0) {\n console.log('NO');\n continue;\n }\n result[0] = first;\n } else {\n result.fill(1);\n let first = n - (k-1);\n if (first % 2 != 1 || first <= 0) {\n console.log('NO');\n continue;\n }\n result[0] = first;\n }\n\n console.log('YES');\n console.log(result.join(' '))\n\n\n }\n\n\n}\n"}], "negative_code": [{"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n\n\n\n\n\n function foo (num, col) {\n let body = col - 1;\n let rest = num - body;\n\n if (rest < 0) return ['NO'];\n if (rest%2 === 1) {\n return ['YES', `${Array(body).fill(1).join(' ')} ${rest}`];\n }\n\n body = 2 * (col - 1);\n rest = num - body;\n\n if (rest < 0) return ['NO'];\n if (rest%2 === 0) {\n return ['YES', `${Array(body/2).fill(2).join(' ')} ${rest}`]\n }\n\n return ['NO'];\n }\n\n let testCount = 1;\n let answer = '';\n while(testCount <= +lines[0]) {\n let data = lines[testCount].split(\" \").map(Number);\n let result = foo(data[0], data[1]);\n answer += result[0] +\"\\n\";\n if (result[1]) answer += result[1] +\"\\n\";\n testCount++;\n }\n console.log(answer);\n})"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n\n\n\n\n\n function foo (num, col) {\n let body = col - 1;\n let rest = num - body;\n let arr = [];\n\n if (rest < 0) return ['NO'];\n if (rest%2 === 1) {\n arr = Array(body).fill(1);\n arr.push(rest);\n return ['YES', arr.join(' ')];\n }\n\n body = 2 * (col - 1);\n rest = num - body;\n\n if (rest < 0) return ['NO'];\n if (rest%2 === 0) {\n arr = Array(body/2).fill(2);\n arr.push(rest);\n return ['YES', arr.join(' ')]\n }\n\n return ['NO'];\n }\n\n let testCount = 1;\n let answer = '';\n while(testCount <= +lines[0]) {\n let data = lines[testCount].split(\" \").map(Number);\n let result = foo(data[0], data[1]);\n answer += result[0] +\"\\n\";\n if (result[1]) answer += result[1] +\"\\n\";\n testCount++;\n }\n console.log(answer);\n})"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\n// your code goes here\n\n// declare global variables\nvar input_stdin = \"\";\nvar noOfTestcase = 0;\n\n// standard input is stored into input_stdin\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\n// standard input is done and stored into an array\nprocess.stdin.on('end', function () {\n chunks = input_stdin.split(\"\\n\");\n noOfTestcase = chunks[0];\n process.stdout.write('\\n');\n for(let i=1; i < chunks.length; i++){\n let row = chunks[i].split(\" \");\n start(Number(row[0]), Number(row[1]));\n }\n});\n\nfunction isEven(val){\n if(val%2 == 0){\n return true\n }\n return false\n}\n\nfunction start(sum,K){\n // console.log(\"sum = \",sum, \" K=\",K);\n let eS = isEven(sum);\n let eK = isEven(K);\n // console.log(\"eS = \",eS, \" eK=\",eK);\n if(sum < K ){\n // console.log(\"less than\");\n process.stdout.write(\"NO\"+ '\\n');\n }else if (!eS && eK) {\n // console.log(\"odd - even condition\");\n process.stdout.write(\"NO\"+ '\\n');\n }else if (eS && !eK && sum < (2*K)) {\n // console.log(\"even - odd but twice condition\");\n process.stdout.write(\"NO\"+ '\\n');\n }else {\n process.stdout.write(\"YES\"+ '\\n');\n let str = \"\"\n if(!eS){\n for(let k=1; k < K; k++){\n str +=\"1 \"\n }\n str+=(sum-K+1)\n }else{\n if(!eK){\n for(let k=1; k < K; k++){\n str +=\"2 \"\n }\n str+=(sum-(2*K)+2)\n }else{\n for(let k=1; k < K; k++){\n str +=\"1 \"\n }\n str+=(sum-K+1)\n }\n }\n process.stdout.write(str+ '\\n');\n }\n return;\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction solve(n, k) {\n let res = [];\n let base = n % 2 === 0 ? Math.ceil(n / k) : Math.floor(n / k);\n if (base === 0) return 0;\n let total = 0;\n for (let i = 1; i <= k; i++) {\n if (i === k) {\n let last = n - total;\n if ((last <= 0) || last % 2 !== base % 2) return 0;\n res.push(last);\n return res;\n }\n res.push(base);\n total += base;\n }\n return res;\n}\n\nfunction main() {\n const t = parseInt(readLine());\n for (let i = 0; i < t; i++) {\n let [n, k] = readLine().split(' ').map((val) => parseInt(val));\n // let a = readLine().split(' ').map((val) => parseInt(val));\n let res = solve(n, k);\n if (res.length > 0) console.log('YES', res.join(' '));\n else console.log('NO');\n }\n //process.stdout.write(\"hello: \");\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction solve(n, k) {\n let res = [];\n let base = n % 2 === 0 ? Math.ceil(n / k) : Math.floor(n / k);\n let total = 0;\n for (let i = 1; i <= k; i++) {\n if (i === k) {\n let last = n - total;\n if ((last <= 0) || last % 2 !== base % 2) return 0;\n res.push(last);\n return res;\n }\n res.push(base);\n total += base;\n }\n return res;\n}\n\nfunction main() {\n const t = parseInt(readLine());\n for (let i = 0; i < t; i++) {\n let [n, k] = readLine().split(' ').map((val) => parseInt(val));\n // let a = readLine().split(' ').map((val) => parseInt(val));\n let res = solve(n, k);\n if (res.length > 0) console.log('YES', res.join(' '));\n else console.log('NO');\n }\n //process.stdout.write(\"hello: \");\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction solve(n, k) {\n if ((n % 2 === 1 && k % 2 === 0) || k > n) return 0;\n let res = [];\n let base = n % 2 === 0 ? Math.ceil(n / k) : Math.floor(n / k);\n let total = 0;\n for (let i = 1; i <= k; i++) {\n if (i === k) {\n let last = n - total;\n if ((last < 0) || last % 2 !== base % 2) return 0;\n res.push(last);\n break;\n }\n res.push(base);\n total += base;\n }\n return res;\n}\n\nfunction main() {\n const t = parseInt(readLine());\n for (let i = 0; i < t; i++) {\n let [n, k] = readLine().split(' ').map((val) => parseInt(val));\n // let a = readLine().split(' ').map((val) => parseInt(val));\n let res = solve(n, k);\n if (res.length > 0) console.log('YES', res.join(' '));\n else console.log('NO');\n }\n //process.stdout.write(\"hello: \");\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction solve(n, k) {\n let res = [];\n let base = n % 2 === 0 ? Math.ceil(n / k) : Math.floor(n / k);\n let total = 0;\n for (let i = 1; i <= k; i++) {\n if (i === k) {\n let last = n - total;\n if ((last < 0) || last % 2 !== base % 2) return 0;\n res.push(last);\n return res;\n }\n res.push(base);\n total += base;\n }\n return res;\n}\n\nfunction main() {\n const t = parseInt(readLine());\n for (let i = 0; i < t; i++) {\n let [n, k] = readLine().split(' ').map((val) => parseInt(val));\n // let a = readLine().split(' ').map((val) => parseInt(val));\n let res = solve(n, k);\n if (res.length > 0) console.log('YES', res.join(' '));\n else console.log('NO');\n }\n //process.stdout.write(\"hello: \");\n}\n"}, {"source_code": "\nvar ans =\"\";\n\nfunction hasEven(x1 , x2){\n\n\tans =\"\";\n\n\tvar eq1 =(x2 -1) *2;\n\tvar eq2 =x1 -eq1;\n\n\tif(eq2 >0 && !(eq2 &1) && eq1 +eq2 ==x1){\n\n x2 --;\n while(x2 --) ans +=\" \" +'2';\n ans +=\" \" +eq2.toString();\n\n return \"YES\";\n\n }\n return \"NO\";\n\n}\n\n\nfunction hasOdd(x1 , x2){\n\n\tans =\"\";\n\n\tvar eq1 =(x2 -1);\n\tvar eq2 =x1 -eq1;\n\n\tif(eq2 >0 && (eq2 &1) && eq1 +eq2 ==x1){\n\n x2 --;\n while(x2 --) ans +=\" \" +'1';\n ans +=\" \" +eq2.toString();\n\n return \"YES\";\n\n }\n return \"NO\";\n\n}\n\n\nvar cases =parseInt(readline());\n\nwhile(cases --){\n\n\tans =\"\";\n\tvar read =readline().split(\" \");\n\tvar n =parseInt(read[0] , 12);\n\tvar k =parseInt(read[1] , 12);\n\n\tif(k <=n && hasEven(n , k) ==\"YES\"){\n\n\t\tprint(\"YES\");\n\t\tprint(ans.trim());\n\n\n\t}else if(k <=n && hasOdd(n , k) ==\"YES\"){\n\n\t\tprint(\"YES\");\n\t\tprint(ans.trim());\n\n\t}else{\n\t\tprint(\"NO\");\n\t}\n\n}\n"}, {"source_code": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var nk = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n var n = nk[0],\n k = nk[1];\n var res = \"\";\n var flag = false;\n if (n % k == 0) {\n for (var j = 0; j < k; j++) {\n res += \" \" + n / k;\n flag = true;\n }\n } else if (n - k + 1 < k) res = \"No\";\n else {\n if (n % 2 == 0) {\n if (k % 2 == 0) {\n res += n - k + 1;\n for (var i = 0; i < k - 1; i++) res += \" \" + 1;\n flag = true;\n } else {\n res += n - 2 * (k - 1);\n for (var i = 0; i < k - 1; i++) res += \" \" + 2;\n flag = true;\n }\n } else {\n if (k % 2 == 0) {\n res = \"No\";\n } else {\n res += n - k + 1;\n for (var i = 0; i < k - 1; i++) res += \" \" + 1;\n flag = true;\n }\n }\n }\n if (flag) {\n print(\"Yes\");\n print(res.trim());\n } else print(res.trim());\n}\n"}, {"source_code": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var nk = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n var n = nk[0],\n k = nk[1];\n var res = \"\";\n var flag = false;\n if (n % k == 0) {\n for (var j = 0; j < 2; j++) {\n res += \" \" + n / k;\n flag = true;\n }\n } else if (n - k + 1 < k) res = \"No\";\n else {\n if (n % 2 == 0) {\n if (k % 2 == 0) {\n res += n - k + 1;\n for (var i = 0; i < k - 1; i++) res += \" \" + 1;\n flag = true;\n } else {\n if (n - 2 * (k - 1) >= 4) {\n res += n - 2 * (k - 1);\n for (var i = 0; i < k - 1; i++) res += \" \" + 2;\n flag = true;\n } else res = \"No\";\n }\n } else {\n if (k % 2 == 0) {\n res = \"No\";\n } else {\n res += n - k + 1;\n for (var i = 0; i < k - 1; i++) res += \" \" + 1;\n flag = true;\n }\n }\n }\n if (flag) {\n print(\"Yes\");\n print(res.trim());\n } else print(res.trim());\n}\n"}, {"source_code": "'use strict';\n\nlet t = parseInt(readline(), 10);\n\nwhile (t--) {\n const result = [];\n const parts = readline().split(' ');\n let n = parseInt(parts[0], 10);\n let k = parseInt(parts[1], 10);\n\n if (k === 1) {\n result.push(n);\n print('YES');\n print(result.join(' '));\n continue;\n }\n\n if (k > n) {\n print('NO');\n continue;\n }\n\n if (k === n) {\n for (let i = 0; i < k; i++) {\n result.push(1);\n }\n print('YES');\n print(result.join(' '));\n continue;\n }\n\n let chooseEven = n % 2 === 0;\n\n while (n > 0 && k > 0) {\n if (n % k === 0) {\n const div = n / k;\n if ((chooseEven && div % 2 === 0) || (!chooseEven && div % 2 !== 0)) {\n result.push(div);\n n -= div;\n k -= 1;\n continue;\n }\n }\n\n if (chooseEven) {\n result.push(2);\n n -= 2;\n } else {\n result.push(1);\n n -= 1;\n }\n k -= 1;\n }\n\n if (n === 0 && k === 0) {\n print('YES');\n print(result.join(' '));\n } else {\n print('NO');\n }\n}\n"}, {"source_code": "'use strict';\n\nlet t = parseInt(readline(), 10);\n\nwhile (t--) {\n const parts = readline().split(' ');\n let n = parseInt(parts[0], 10);\n let k = parseInt(parts[1], 10);\n\n function helper(N, K, result, sub) {\n while (N > 0 && K > 1) {\n N -= sub;\n K -= 1;\n result.push(sub);\n }\n if (N % 2 === sub % 2) {\n result.push(N);\n K -= 1;\n }\n return {K, result};\n }\n\n const resultOdd = helper(n, k, [], 1);\n const resultEven = helper(n, k, [], 2);\n\n if (resultOdd.K === 0) {\n print('YES');\n print(resultOdd.result.join(' '));\n } else if (resultEven.K === 0) {\n print('YES');\n print(resultEven.result.join(' '));\n } else {\n print('NO');\n }\n}\n"}, {"source_code": " var nCases = parseInt(readline());\n for (var i = 0; i < nCases; i++){\n\n var line = readline().split(\" \");\n var n = parseInt(line[0]);\n var k = parseInt(line[1]);\n\n var str = '';\n\n if (n % 2 === 0 && (n - ((k - 1) * 2)) % 2 === 0 && n - ((k - 1) * 2) > 0){\n print(\"YES\\n\");\n for (var j = 0; j < k - 1; j++){\n str += \"2 \";\n }\n str += \"\"+ (n - ((k - 1) * 2));\n }\n else if ((n - (k - 1)) % 2 !== 0){\n print('YES\\n');\n for (var j = 0; j < k - 1; j++){\n str += '1 ';\n }\n str += '' + (n - (k - 1));\n }\n else{ \n print('NO\\n');\n continue;\n }\n print(str + '\\n');\n }"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9\n\n\n\n\n**/\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9\n\n\n\n\n**/\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r= n) {\n console.log('NO');\n continue;\n }\n\n output.push(n - count);\n\n console.log('YES');\n console.log(output.join(\" \"));\n continue;\n } else {\n let output = [];\n let count = 0;\n\n for(let i=0;i= n) {\n console.log('NO');\n continue;\n }\n output.push(n - count);\n console.log('YES');\n console.log(output.join(\" \"));\n continue;\n }\n } else {\n if(k % 2 !== 0) {\n let output = [];\n let count = 0;\n\n for(let i=0;i= n) {\n console.log('NO');\n continue;\n }\n console.log('YES');\n console.log(output.join(\" \"));\n continue;\n } else {\n console.log('NO');\n continue;\n }\n }\n\n }\n\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9\n\n\n\n\n**/\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9\n\n\n\n\n**/\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9\n\n\n\n\n**/\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r= 1001) {\r\n break;\r\n }\r\n }\r\n }\r\n const T = array[0];\r\n for (let i = 0; i < T; i++) {\r\n const k = array[i + 1];\r\n console.log(arr[k - 1]);\r\n }\r\n}\r\n\r\nlet inputString = '';\r\n\r\nprocess.stdin.on('data', (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', (_) => {\r\n inputString = inputString.trim().split('\\n').map((string) => string.trim());\r\n\r\n main(inputString);\r\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var a = [];\n for(l = 1; l < 1667; l++){\n if(l % 10 == 3 || l % 3 === 0){\n \n }else{\n a.push(l);\n }\n }\n for(j = 1; j <= n; j++){\n var k = lines[j];\n console.log(a[k - 1]);\n }\n});"}, {"source_code": "let data = \"\";\r\n\r\nfunction solve(){\r\n\r\n let polycarp = [];\r\n let input = data.split(/ |\\n/);\r\n let testCaseNumber = parseInt(input[0]);\r\n let k = 1;\r\n\r\n for (let i = 1; k <= 1000; i++){\r\n\r\n if (i % 3 != 0 && i%10 !=3){\r\n polycarp[k] = i;\r\n k++;\r\n }\r\n\r\n }\r\n\r\n for (let i = 1; i <= testCaseNumber; i++){\r\n let a = input[i];\r\n a = parseInt(a);\r\n console.log(polycarp[a]);\r\n }\r\n\r\n}\r\n\r\nprocess.stdin.on('data', function(chunk){\r\n data += chunk;\r\n})\r\n\r\nprocess.stdin.on('end', function(chunk){\r\n solve();\r\n})"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\nconst k = [];\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n\n let i = 1;\n while (k.length <= 1000) {\n if (i % 3 === 0 || i % 10 === 3) {\n i++;\n continue;\n }\n\n k.push(i);\n i++;\n }\n return;\n }\n\n console.log(k[Number(d - 1)]);\n\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "// Common Template Starts //\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\"\r\nlet currentLine = 0\r\n\r\nprocess.stdin.on(\"data\", inputStdin => inputString += inputStdin)\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => string.trim())\r\n main()\r\n})\r\n\r\nconst readline = () => inputString[currentLine++]\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n \r\n let n = 0\r\n let arr = []\r\n let str = ''\r\n \r\n let nums = generateUptoNwithoutK(1000, 3)\r\n \r\n // with testcases\r\n //* \r\n let t = parseInt( readline() ) \r\n while (t--) {\r\n n = parseInt( readline() )\r\n // arr = readline().split(' ').map(Number)\r\n // str = readline()\r\n console.log( solve(n, nums, arr, str) )\r\n } \r\n //*/\r\n\r\n // without testcases\r\n /* \r\n n = parseInt( readline() )\r\n arr = readline().split(' ').map(Number)\r\n str = readline()\r\n console.log( solve(n, arr, str) )\r\n //*/\r\n}\r\n// Driver Function Ends //\r\n\r\nconst generateUptoNwithoutK = (n, k) => {\r\n let a = [], i = 1\r\n while( a.length <= n ){\r\n // if( i%k != 0 && !stringHasCharacter(i.toString(), k ) ) a.push( i )\r\n if( i%k != 0 && i%10 != k ) a.push( i )\r\n i++\r\n }\r\n return a\r\n}\r\n\r\n// MAIN LOGIC\r\nconst solve = (n, nums, arr, str) => { \r\n \r\n return nums[n-1]\r\n}\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sortDesc = (arr) => arr.sort( (a, b) => b - a )\r\nconst isSorted = (arr) => arr.every((v, i, a) => !i || a[i - 1] <= v)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)\r\nconst splitAt = index => x => [x.slice(0, index), x.slice(index)]\r\nconst elemFrequency = (arr) => arr.reduce( (acc, curr) => { return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc }, {}) \r\n\r\nconst reverseText = (str) => str.split('').reverse().join('')\r\nconst stringHasDuplicates = (str) => (/([a-z])\\1/i).test(str)\r\nconst stringHasDuplicateChar = (str, char) => str.indexOf(char) !== str.lastIndexOf(char)\r\nconst stringHasCharacter = (str, char) => str.indexOf(char) > -1 ? true : false\r\n\r\nconst findAllIndicesOfChar = (str, char) => {\r\n str = str.split('')\r\n let indices = [];\r\n for (let i = 0; i < str.length; i++) {\r\n if (str[i] === char) indices.push(i);\r\n }\r\n return indices\r\n}\r\n\r\nconst isUpper = str => !/[a-z]/.test(str) && /[A-Z]/.test(str)\r\nconst escapeRegExp = (string) => string.replace(/[.*+\\-?^$$${}()|[\\]\\\\]/g, '\\\\$$$&')\r\nconst replaceAll = (str, find, replace) => str.replace(new RegExp(escapeRegExp(find), 'g'), replace)\r\n\r\nconst findUnique = (str) => {\r\n return [...str].reduce((acc, curr) => {\r\n return acc.includes(curr) ? acc : acc + curr;\r\n }, \"\")\r\n}\r\n\r\nconst unique = (str) => {\r\n const cleanStr = str.replace(/ /gi, '');\r\n const set = [...new Set(cleanStr)];\r\n return set;\r\n}\r\n\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf8\");\nprocess.stdin.on(\"data\", function(chunk) {\n let data = chunk.trim().split(\"\\n\");\n let times = parseInt(data[0]);\n let map = [...Array(10e3).keys()].filter(e => {\n return !(e % 3 === 0 || e % 10 === 3);\n }).slice(0, 1000);\n for(let i = 1; i <= times; i++) {\n let [ num ] = data[i].trim().split(\" \").map(Number);\n console.log(map[num - 1]);\n }\n});\n\t \t \t\t\t \t\t \t \t \t\t"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split('\\n')\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let tests = parseInt(readline());\r\n while (tests--) {\r\n let k = parseInt(readline());\r\n let num = 0;\r\n for (let i = 0; i < k; i++) {\r\n num++;\r\n while (num % 10 === 3 || num % 3 === 0) num++;\r\n }\r\n console.log(num);\r\n }\r\n}\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var a = [];\n for(var l = 1; l < 1667; l++){\n if(l % 10 == 3 || l % 3 === 0){\n \n }else{\n a.push(l);\n }\n }\n for(var j = 1; j <= n; j++){\n var k = lines[j];\n console.log(a[k - 1]);\n }\n});"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tlet a = [];\n\tfor(let i = 0; a.length <= 1000; i++){\n\t\tif (i % 3 != 0 && i % 10 != 3) {\n\t\t\ta.push(i);\n\t\t}\n\t}\n\tfor(let i = 0; i < t; i++){\n\t\tlet k = nl.num();\n\t\tans.push(a[k-1]);\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet k = rn();\r\n\r\n\t\tlet nxt = 0;\r\n\t\twhile (k) {\r\n\t\t\tnxt++;\r\n\t\t\tk -= nxt%3 && nxt%10 != 3;\r\n\t\t}\r\n\r\n\t\tconst ans = nxt;\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "/**\r\n * Bismillahir Rahmanir Rahim\r\n * This code has been taken from: https://codeforces.com/blog/entry/69610\r\n */\r\n process.stdin.resume();\r\n process.stdin.setEncoding('utf-8');\r\n \r\n let inputString = '';\r\n let currentLine = 0;\r\n \r\n process.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n });\r\n \r\n process.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n });\r\n \r\n function readLine() {\r\n return inputString[currentLine++];\r\n }\r\n \r\n \r\n /****** BELOW HERE START WRITING YOUR CODE IN main() FUNCTION ***************************************/\r\n /**\r\n * Use \"readLine()\" function for input, which will return a string consisting the entire line, so accordingly split the string \r\n * when required.\r\n *\r\n * I am using console.log() to output\r\n */\r\n// function main() {\r\n// let t = readLine();\r\n// t = parseInt(t);\r\n// console.log(\"mai yahan aaya\")\r\n// while(t--) {\r\n// let line = readLine();\r\n// line = line.split(\" \");\r\n// let n = parseInt(line[0]);\r\n// let m = parseInt(line[1]);\r\n// if(n === 1) {\r\n// console.log(\"0\");\r\n// } else if (n === 2) {\r\n// console.log(m);\r\n// } else {\r\n// console.log(2*m);\r\n// }\r\n// }\r\n// }\r\n\r\nfunction main() {\r\n\t\r\n\tlet t = parseInt(readLine());\r\n\tresults = []\r\n\tprecompute(results);\r\n\t// t = parseInt(t);\r\n\twhile(t--) {\r\n\t\tlet n = readLine();\r\n\t\tn = parseInt(n);\r\n\t\t//let s = readLine().split(\" \").map(item=>parseInt(item));\r\n\t\tconsole.log(solve(n));\r\n\t\t\r\n\t}\r\n // console.log(t);\r\n}\r\n\r\nfunction solve(n) {\r\n\treturn results[n-1];\r\n}\r\n\r\nfunction precompute(results) {\r\n\tk = 1 ;\r\n\ti = 1 ;\r\n\twhile(k<=1000) {\r\n\t\tif (i%3===0 || i%10===3) i++;\r\n\t\telse {\r\n\t\t\tresults.push(i);\r\n\t\t\ti++;\r\n\t\t\tk++;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "const readline = require('readline')\r\n \r\nconst read = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst inputString = []\r\n\r\nread.on('line', (input) => {\r\n inputString.push(input.trim());\r\n})\r\nread.on('close', () => {\r\n\r\n main(inputString.map(num => parseInt(num)).filter(Boolean)); \r\n})\r\n \r\nfunction main(nums) {\r\n const total = nums[0];\r\n const remaining = nums.slice(1)\r\n const max = Math.max(...remaining.slice(0,total));\r\n const list = [];\r\n let i = 1;\r\n while(list.length < max){\r\n if(i%3 !== 0 && i%10 !== 3){\r\n list.push(i)\r\n }\r\n i++;\r\n }\r\n remaining.forEach(element => {\r\n console.log(list[element-1]);\r\n });\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ************************ Code Start ***************************\r\n \r\nfunction main() {\r\n \r\n var t=parseInt(readline())\r\n\r\nwhile(t--){\r\n var k=parseInt(readline())\r\n \r\n for(var i=1;;i++){\r\n if(i%3==0 ||(i%10==3)){\r\n continue;\r\n }\r\n k--;\r\n if(k==0){\r\n print(i)\r\n break;\r\n }\r\n\r\n }\r\n}\r\n \r\n}"}, {"source_code": "process.stdin.resume();\r\n \r\nprocess.stdin.setEncoding('utf8');\r\n \r\nvar input = '';\r\n \r\nprocess.stdin.on('data' , data=>{\r\n input += data;\r\n});\r\nprocess.stdin.on('end' , ()=>{\r\n main(input);\r\n});\r\n\r\nfunction main(input) {\r\n input = input.split(\"\\n\");\r\n let z = 0;\r\n let testCases = +input[z++];\r\n\r\n while(testCases--){\r\n let index = +input[z++];\r\n let number = 0;\r\n for (let i = 1; i <= index; i++) {\r\n if((i % 3) == 0 || i.toString()[i.toString().length - 1] == '3'){\r\n index++;\r\n }\r\n number++;\r\n }\r\n if((number % 3) == 0 || number.toString()[number.toString().length - 1] == '3'){\r\n number++;\r\n }\r\n console.log(number);\r\n }\r\n}"}, {"source_code": "// define file test.inp\r\n// npm install -D @types/node\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf8\");\r\nvar jsin = \"\";\r\nvar input = [];\r\nvar jscur = 0;\r\nvar readLine = function () { return input[jscur++]; };\r\nvar readLines = function () { return readLine().split(' '); };\r\nvar readInt = function () { return +(readLine()); };\r\nvar readInts = function () { return readLine().split(' ').map(function (x) { return +(x); }); };\r\nvar debug = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n console.log(\"[\" + args.join(\",\") + \"]\");\r\n};\r\nprocess.stdin.on('data', function (chunk) { return jsin += chunk; });\r\nprocess.stdin.on('end', function () {\r\n input = jsin.split('\\n').filter(function (curline) { return curline !== ''; });\r\n // multitest\r\n var nTest = readInt();\r\n while (nTest--) {\r\n main();\r\n }\r\n});\r\n//// CODE BELOW\r\nfunction main() {\r\n var k = readInt();\r\n var val = 1;\r\n for (; k > 0; ++val) {\r\n if (val % 3 == 0 || val % 10 == 3) {\r\n continue;\r\n }\r\n --k;\r\n }\r\n console.log(val - 1);\r\n}\r\n"}, {"source_code": "// var arr = [];\r\n// for (var j = 1; arr.length <= 1000; j++) {\r\n// if (j % 3 == 0 || j % 10 == 3) {\r\n// continue;\r\n// } else {\r\n// arr.push(j);\r\n// }\r\n// //console.log(j);\r\n// }\r\n\r\n// //console.log((arr));\r\n// var t = Number(readline());\r\n\r\n// for (var i = 1; i <= t; i++) {\r\n// var n = Number(readline());\r\n// console.log(arr[n - 1]);\r\n\r\n\r\n// }\r\n\r\n\r\n\r\n\r\n\r\n\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// ************************ Code Start ***************************\r\n\r\nfunction main() {\r\n var arr = [];\r\n for (var j = 1; arr.length <= 1000; j++) {\r\n if (j % 3 == 0 || j % 10 == 3) {\r\n continue;\r\n } else {\r\n arr.push(j);\r\n }\r\n //console.log(j);\r\n }\r\n\r\n //console.log((arr));\r\n var t = Number(readline());\r\n\r\n for (var i = 1; i <= t; i++) {\r\n var n = Number(readline());\r\n console.log(arr[n - 1]);\r\n\r\n\r\n }\r\n\r\n\r\n}"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst assert = (condition) => { if (!condition) throw new Error(\"Assertion failed\"); }\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst int = parseInt;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg2 = Math.log2;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };\r\nconst initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\nconst ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);\r\nconst isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 08/18/21 morning\r\n * https://codeforces.com/contest/1560/problem/A\r\n */\r\nlet dp = [];\r\nconst solve = (k) => {\r\n // pr(k);\r\n pr(dp[k - 1]);\r\n};\r\n\r\nconst endWithThree = (x) => {\r\n let s = x + '';\r\n return s[s.length - 1] == '3';\r\n};\r\n\r\nconst prepare = () => {\r\n let x = 1;\r\n while (dp.length < 1001) {\r\n if (x % 3 != 0 && !endWithThree(x)) dp.push(x);\r\n x++;\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(Number(line));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0];\r\n let i = 1;\r\n prepare();\r\n // pr(dp);\r\n while (t--) {\r\n solve(input[i]);\r\n i++;\r\n }\r\n });\r\n};\r\n\r\nmain()\r\n\r\n// pr(hasThree(13))"}, {"source_code": "function checkIsValid (i) {\n if (i % 3 === 0) {\n return false;\n }\n if (i % 10 === 3) {\n return false;\n }\n return true;\n}\nfunction main(array) {\n let i = 0;\n let arr = [];\n while (true) {\n i += 1;\n if (checkIsValid(i)) {\n arr.push(i);\n if (arr.length >= 1001) {\n break;\n }\n }\n }\n const T = array[0];\n for (let i = 0; i < T; i++) {\n const k = array[i + 1];\n console.log(arr[k - 1]);\n }\n}\n\nlet inputString = '';\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString.trim().split('\\n').map((string) => string.trim());\n\n main(inputString);\n});"}, {"source_code": "let inputs = []\n\nfunction read() {\n return inputs.pop();\n}\n\nfunction readInt() {\n return parseInt(read());\n}\n\nfunction solve() {\n ar = []\n for (let i = 1; i < 1e4; i++) {\n if (i % 3 != 0 && i % 10 != 3) {\n ar.push(i);\n }\n }\n let test = readInt();\n while (test--) {\n let k = readInt();\n console.log(ar[k - 1]);\n }\n}\n\nfunction main() {\n inputs = inputString.replace(' ', '\\n').trim().split('\\n').map((string) => string.trim());\n inputs.reverse(); \n solve();\n}\n\nlet inputString = '';\n\nprocess.stdin.on('data', (inputStdin) => { inputString += inputStdin; });\n\nprocess.stdin.on('end', (_) => { main(); });\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n console.log(solve(n))\n }\n// })()\n})\n\nfunction solve(n) {\n let k = 0\n while (n--) {\n k++\n while ((k % 10) === 3 || !(k % 3)) {\n k++\n }\n }\n return k\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar list = [];\r\n\tvar now = 1;\r\n\twhile(list.length < 1000){\r\n\t\tif(now % 3 != 0 && now % 10 != 3){\r\n\t\t\tlist.push(now);\r\n\t\t}\r\n\t\tnow++;\r\n\t}\r\n\twhile(hasNext()){\r\n\t\tvar K = nextInt();\r\n\t\tmyout(list[K - 1]);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nvar maxN = 2 * 1e5 + 10\r\nvar mod = BigInt(1e9 + 7)\r\n\r\nfunction main() {\r\n const xx = readline();\r\n var array = []\r\n var i=0\r\n while (true) {\r\n i++\r\n if (array.length === 1000) break\r\n if (i % 3 === 0 || i % 10 === 3) continue\r\n array.push(i)\r\n\r\n }\r\n // console.log(array)\r\n Array(Number(xx)).fill(1).map((t, i) => {\r\n var n = parseInt(readline());\r\n\r\n console.log(array[n - 1])\r\n })\r\n}\r\n\r\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(String(e))\r\n }\r\n println(e) {\r\n stdout.write(String(e)), stdout.write('\\n')\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(n => {\r\n stdin.on('data', n => e.push(n)),\r\n stdin.on('end', function () {\r\n const t = e.join('').split(os.EOL)\r\n n(t)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const n = new InputAndOutput()\r\n await n.init(), e(n)\r\n}\r\nconst nums = [0]\r\nfor (\r\n let e = 1;\r\n e < 1e7 && !(e % 3 != 0 && e % 10 != 3 && (nums.push(e), nums.length > 1010));\r\n ++e\r\n);\r\nfunction solve(e) {\r\n return nums[e]\r\n}\r\n__main__(function (e) {\r\n const n = e.readLineAsNumber()\r\n for (let t = 1; t <= n; ++t) {\r\n const n = solve(e.readLineAsNumber())\r\n e.print(n + '\\n')\r\n }\r\n})\r\n"}, {"source_code": "const arr = [];\r\nlet i = 0;\r\nwhile(arr.length < 1000) {\r\n i++;\r\n if (i % 10 === 3 || i % 3 === 0) {\r\n continue;\r\n }\r\n arr.push(i);\r\n}\r\n\r\n\r\nfunction solve() {\r\n const k = Number(read());\r\n write(arr[k - 1]); \r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e + e.stack);\r\n }\r\n}\r\n\r\nfunction modPow(a, n, mod) {\r\n let d = a;\r\n let curN = n;\r\n let ans = 1n;\r\n while(curN) {\r\n if (curN & 1n) {\r\n ans = modMul(ans, d, mod);\r\n }\r\n curN >>= 1n;\r\n d = modMul(d, d, mod);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction modMul(a, b, mod) {\r\n return (a * b) % mod;\r\n}\r\n\r\nfunction modSum(a, b, mod) {\r\n return (a + b) % mod;\r\n}\r\n\r\nfunction modDiff(a, b, mod) {\r\n return (a + mod - b) % mod;\r\n}\r\n\r\nfunction isZero(num) {\r\n if (typeof num === 'bigint') {\r\n return num === 0n;\r\n }\r\n return num === 0;\r\n}\r\nfunction div(a, b) {\r\n if (typeof a !== typeof b) {\r\n throw new Error('Different types on division');\r\n }\r\n if (typeof a === 'bigint') {\r\n return a / b;\r\n }\r\n return Math.floor(a / b);\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if (isZero(y)) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction lcm(x, y) {\r\n return div(x * y, gcd(x, y));\r\n}\r\n\r\nfunction allIndexOf(arr, value) {\r\n var index = arr.indexOf(value)\r\n var ans = [];\r\n while (index !== -1) {\r\n ans.push(index);\r\n index = arr.indexOf(value, index + 1);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction xor(a, b, k) {\r\n if (k === 2) {\r\n return a ^ b;\r\n }\r\n}\r\n\r\nfunction decToBin(num) {\r\n let n = num;\r\n const ans = [];\r\n while(n > 0) {\r\n ans.push(n & 1);\r\n n = (n >> 1);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction binToDec(binN) {\r\n let ans = 0;\r\n for (let i = binN.length - 1; i >= 0; i--) {\r\n ans = ((ans << 1) | binN[i]);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "// var fs = new require('fs');\r\nvar arr = new Array();\r\nvar t = 0;\r\nwhile(arr.length < 1000) {\r\n if(t % 10 != 3 && t % 3 != 0){\r\n arr.push(t);\r\n }\r\n t++;\r\n}\r\nvar t = Number(readline()); // readline()\r\nwhile(t > 0) {\r\n var a = Number(readline());\r\n// if(t != 0) { //\r\n// a = 10 - t; //\r\n// } //\r\n// else { //\r\n// a = 1000; //\r\n// } // redline()\r\n print(arr[a-1]);\r\n t--;\r\n}"}, {"source_code": "var nLoop = readline();\r\nvar dataArray = [];\r\nvar MAX_NUM = 2000;\r\n\r\nfor(var j = 1, indx = 0; j <= MAX_NUM; j++) {\r\n if ( j%3 !== 0 && j%10 !== 3 ) {\r\n dataArray[indx] = j;\r\n indx++;\r\n }\r\n}\r\n\r\nfor(var i = 0; i < nLoop; i++) {\r\n inpUser = readline();\r\n print(dataArray[inpUser - 1]);\r\n}"}, {"source_code": "var input = readline();\r\n\r\nfunction getSequense() {\r\n var seq = [];\r\n \r\n for (var i = 1; seq.length <= 1000; i++) {\r\n var isEnd3 = (\"\" + i).slice(-1) === \"3\"\r\n var isCratne = i % 3 === 0;\r\n \r\n if (!(isEnd3 || isCratne)) {\r\n seq.push(i);\r\n }\r\n }\r\n \r\n return seq;\r\n}\r\n\r\n\r\nvar sequense = getSequense();\r\nfor(var i=0;i<=input;i++) {\r\n var value = readline();\r\n\r\n if(value) {\r\n print(sequense[value-1])\r\n }\r\n}\r\n"}, {"source_code": "// 1560 A -Dislike of Threes\r\n\r\n// number tests\r\nvar numTests = parseInt( readline() );\r\n\r\nfor (var i = 0; i < numTests; i++) {\r\n \r\n // input data\r\n var numMaxDislike = parseInt( readline() );\r\n var str = numMaxDislike.toString()\r\n\r\n // variable program\r\n var numDislike = 0;\r\n var numberReach = 0;\r\n\r\n // old version\r\n /*\r\n for (var i = 1; i < numMaxDislike; i++) {\r\n var str = i.toString();\r\n if( i % 3 != 0 && str.charAt( str.length-1 ) != '3' ){\r\n k++;\r\n }\r\n }\r\n */\r\n\r\n // new version\r\n while ( numDislike < numMaxDislike){\r\n \r\n // trasform integer to string\r\n var str = (numberReach+1).toString();\r\n\r\n // numero non divisibile per 3 e che non finisca con 3 alla fine\r\n if( (numberReach+1) % 3 != 0 && str.charAt( str.length-1 ) != '3' ){\r\n numDislike++;\r\n }\r\n \r\n // increment the couter\r\n numberReach++\r\n \r\n }\r\n\r\n // output - print number raggiunto da numeri like, arrivando a k numeri dislike same a numMaxDislike\r\n print(numberReach);\r\n\r\n}\r\n"}, {"source_code": "var a=[1]\r\nvar num=2\r\nwhile(a.length<1000){\r\n if(num%3!==0&&num%10!==3)a.push(num)\r\n num++\r\n}\r\nvar n=readline()\r\nfor(i=0;i (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n const seq = [];\r\n \r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n \r\n let [count, ...entry] = lines;\r\n \r\n for(let z = 0; z < entry.length; z++) {\r\n console.log(seq[entry[z]-1])\r\n }\r\n process.exit();\r\n return;\r\n \r\n});"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n for(let z = 0; z < entry.length; z++) {\r\n console.log(seq[entry[z]-1])\r\n }\r\n return 0;\r\n\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nvar input= '', readline, print;\r\n\r\nprocess.stdin.on('data', function(chunk) {\r\n input+=chunk;\r\n});\r\n\r\nprocess.stdin.on('end', function() {\r\n input = input.split('\\n');\r\n print = function(data) {process.stdout.write(data)};\r\n var inputLineIndex = 0;\r\n readline = function(){return inputLineIndex>=input.length?undefined:input[inputLineIndex++]};\r\n main();\r\n});\r\n\r\nfunction main()\r\n{\r\n const lines = [...input]; /*your input text, split by lines*/\r\n \r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n for(let z = 0; z < entry.length; z++) {\r\n console.log(seq[entry[z]-1])\r\n }\r\n}"}, {"source_code": "const { EOL } = require(\"os\");\r\nlet inp = \"\";\r\nprocess.stdin.on(\"data\", (c) => (inp+= c));\r\nprocess.stdin.on(\"end\", () => {\r\n const lines1 = inp.split(EOL); /*your input text, split by lines*/\r\nm(lines1)\r\n});\r\n\r\nfunction m(lines) {\r\n\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n for(let z = 0; z < entry.length; z++) {\r\n console.log(seq[entry[z]-1])\r\n }\r\n return 0;\r\n}\r\n"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n const seq = [];\r\n \r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n \r\n let [count, ...entry] = lines;\r\n \r\n for(let z = 0; z < entry.length; z++) {\r\n console.log(seq[entry[z]-1],'\\n')\r\n }\r\n return 0;\r\n \r\n});"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n for(let z = 0; z < entry.length; z++) {\r\n console.log(seq[entry[z]-1])\r\n }\r\n return 0;\r\n\r\n});\r\n"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n function main() {\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n console.log(entry)\r\n\r\n for(let z = 0; z < entry.length; z++) {\r\n console.log(seq[entry[z]-1])\r\n }\r\n return 0;\r\n }\r\n main()\r\n});\r\n"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n function main() {\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n entry.forEach((k) => {\r\n console.log(seq[k-1])\r\n });\r\n return 0;\r\n }\r\n main()\r\n});\r\n"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n function main() {\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n entry.forEach((k) => {\r\n console.log(seq[k-1])\r\n });\r\n }\r\n});\r\n"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n function main() {\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n entry.forEach((k) => {\r\n console.log(seq[k-1])\r\n });\r\n }\r\n main()\r\n});\r\n"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n function main() {\r\n let out = [];\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n entry.forEach((k) => {\r\n out.push(seq[k]);\r\n console.log(seq[k])\r\n });\r\n // console.log(out)\r\n // return 0;\r\n }\r\n main()\r\n});\r\n"}, {"source_code": "let i = \"\";\r\nprocess.stdin.on(\"data\", (c) => (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const lines = i.split(EOL); /*your input text, split by lines*/\r\n \r\n function main() {\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if (!(!(i % 3) || (\"\" + i).slice(-1) === \"3\")) {\r\n seq.push(i);\r\n }\r\n }\r\n\r\n let [count, ...entry] = lines;\r\n\r\n entry.forEach((k) => {\r\n console.log(seq[k]);\r\n });\r\n return 0;\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nvar input= '', readline, print;\n\nprocess.stdin.on('data', function(chunk) {\n input+=chunk;\n});\n\nprocess.stdin.on('end', function() {\n input = input.split('\\n');\n print = function(data) {process.stdout.write(data+'\\n')};\n var inputLineIndex = 0;\n readline = function(){return inputLineIndex>=input.length?undefined:input[inputLineIndex++]};\n process.exit(main() || 0);\n});\n\nfunction main()\n{\n const seq = [];\n\n for (let i = 1; seq.length <= 1000; i++) {\n if(!(!(i % 3) || (''+i).slice(-1) === '3')) {\n seq.push(i)\n }\n }\n \n let [count, ...entry] = input;\n \n entry.forEach(k => {\n console.log(seq[k])\n });\n return 0;\n}\n\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nvar input= '', readline, print;\r\n\r\nprocess.stdin.on('data', function(chunk) {\r\n input+=chunk;\r\n});\r\n\r\nprocess.stdin.on('end', function() {\r\n input = input.split('\\n');\r\n print = function(data) {process.stdout.write(data+'\\n')};\r\n var inputLineIndex = 0;\r\n readline = function(){return inputLineIndex>=input.length?undefined:input[inputLineIndex++]};\r\n process.exit(main() || 0);\r\n});\r\n\r\nfunction main()\r\n{\r\n const seq = [];\r\n\r\n for (let i = 1; seq.length <= 1000; i++) {\r\n if(!(!(i % 3) || (''+i).slice(-1) === '3')) {\r\n seq.push(i)\r\n }\r\n }\r\n \r\n let [count, ...entry] = input;\r\n \r\n entry.forEach(k => {\r\n console.log(seq[k])\r\n });\r\n return 0;\r\n}\r\n\r\nmain()"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var s = 0\n var b = 0\n for(j = 1; j <= lines[0]; j ++){\n var a = lines[j]\n while(b <= lines[0]){\n b++\n if(b % 3 === 0 || b[b.length - 1] == 3){\n b+=2 \n Number(lines[0]+3) \n\n }\n console.log(b)\n\n }\n\n }\n \n \n \n})"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var s = 0\n var p = 0\n for(j = 1; j<=lines[0]; j++){\n var a = lines[j]\n if(a != 3 || a % 3 === 0){\n p++\n }\n }\n for(k = 0; k < p; k++){\n var ak = lines[j]\n console.log(ak)\n }\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var s = 0\n for(j = 1; j<=lines[0]; j++){\n var a = lines[j]\n if(a != 3 || a % 3 === 0){\n s = a\n console.log(s)\n }\n }\n \n \n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var s = 0\n for(j = 1; j<=lines[0]; j++){\n var a = lines[j]\n if(a != 3 || a % 3 === 0){\n s = a\n console.log(a)\n }\n }\n \n \n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var s = 0\n for(j = 1; j<=lines[0]; j++){\n var a = lines[j]\n var b = a.split('')\n if(b != 3 || a % 3 === 0){\n s = a\n }\n console.log(a)\n }\n \n \n});"}, {"source_code": "let data = \"\";\r\n\r\nfunction solve(){\r\n\r\n let polycarp = [];\r\n let input = data.split(/ |\\n/);\r\n let testCaseNumber = parseInt(input[0]);\r\n let k = 1;\r\n\r\n for (let i = 1; k <= 1000; i++){\r\n\r\n if (i % 3 != 0 && i%10 !=3){\r\n polycarp[k] = i;\r\n k++;\r\n }\r\n\r\n }\r\n\r\n for (let i = 1; i <= testCaseNumber; i++){\r\n let a = input[i];\r\n console.log(parseInt(polycarp[a]));\r\n }\r\n\r\n}\r\n\r\nprocess.stdin.on('data', function(chunk){\r\n data += chunk;\r\n})\r\n\r\nprocess.stdin.on('end', function(chunk){\r\n solve();\r\n})"}, {"source_code": "let data = \"\";\r\n\r\nfunction solve(){\r\n\r\n let polycarp = [1001];\r\n let input = data.split(/ |\\n/);\r\n let testCaseNumber = parseInt(input[0]);\r\n let k = 1;\r\n\r\n for (let i = 1; k <= 1000; i++){\r\n\r\n if (i % 3 != 0 && i%10 !=3){\r\n polycarp[k] = i;\r\n k++;\r\n }\r\n\r\n }\r\n\r\n for (let i = 1; i <= testCaseNumber; i++){\r\n let a = input[i];\r\n parseInt(a);\r\n console.log(polycarp[a]);\r\n }\r\n\r\n}\r\n\r\nprocess.stdin.on('data', function(chunk){\r\n data += chunk;\r\n})\r\n\r\nprocess.stdin.on('end', function(chunk){\r\n solve();\r\n})"}, {"source_code": "let data = \"\";\r\n\r\nfunction solve(){\r\n\r\n let polycarp = [1001];\r\n let input = data.split(/ |\\n/);\r\n let testCaseNumber = parseInt(input[0]);\r\n let k = 1;\r\n\r\n for (let i = 1; k <= 1000; i++){\r\n\r\n if (i % 3 != 0 && i%10 !=3){\r\n polycarp[k] = i;\r\n k++;\r\n }\r\n\r\n }\r\n\r\n for (let i = 1; i <= testCaseNumber; i++){\r\n let a = input[i];\r\n console.log(polycarp[a]);\r\n }\r\n\r\n}\r\n\r\nprocess.stdin.on('data', function(chunk){\r\n data += chunk;\r\n})\r\n\r\nprocess.stdin.on('end', function(chunk){\r\n solve();\r\n})"}, {"source_code": "let data = \"\";\r\n\r\nfunction solve(){\r\n\r\n let polycarp = [1001];\r\n let input = data.split(/ |\\n/);\r\n let testCaseNumber = parseInt(input[0]);\r\n let k = 1;\r\n\r\n for (let i = 1; k <= 1000; i++){\r\n\r\n if (i % 3 != 0 && i%10 !=3){\r\n polycarp[k] = i;\r\n k++;\r\n }\r\n\r\n }\r\n\r\n for (let i = 1; i <= testCaseNumber; i++){\r\n let a = input[i];\r\n console.log(polycarp[a]);\r\n }\r\n\r\n\r\n}\r\n\r\nprocess.stdin.on('data', function(chunk){\r\n data += chunk;\r\n})\r\n\r\nprocess.stdin.on('end', function(chunk){\r\n solve();\r\n})"}, {"source_code": "let data = \"\";\r\n\r\nfunction solve(){\r\n\r\n let polycarp = [1001];\r\n let input = data.split(/ |\\n/);\r\n let testCaseNumber = parseInt(input[0]);\r\n let k = 1;\r\n let a = 1;\r\n\r\n for (let i = 1; k <= 1000; i++){\r\n\r\n if (i % 3 != 0 && i%10 !=3){\r\n polycarp[k] = i;\r\n k++;\r\n }\r\n\r\n }\r\n\r\n for (let i = 0; i < testCaseNumber; i++){\r\n console.log(polycarp[a]);\r\n a++;\r\n }\r\n\r\n\r\n\r\n\r\n\r\n}\r\n\r\nprocess.stdin.on('data', function(chunk){\r\n data += chunk;\r\n})\r\n\r\nprocess.stdin.on('end', function(chunk){\r\n solve();\r\n})"}, {"source_code": "let data = \"\";\r\n\r\nfunction solve(){\r\n\r\n let polycarp = [1001];\r\n let input = data.split(/ |\\n/);\r\n let testCaseNumber = parseInt(input[0]);\r\n let k = 1;\r\n let a = 1;\r\n\r\n for (let i = 1; k <= 1000; i++){\r\n\r\n if (i % 3 != 0 && i%10 !=3){\r\n polycarp[k] = i;\r\n k++\r\n }\r\n\r\n }\r\n\r\n for (let i = 0; i < testCaseNumber; i++){\r\n console.log(polycarp[a]);\r\n a++;\r\n }\r\n\r\n\r\n\r\n\r\n\r\n}\r\n\r\nprocess.stdin.on('data', function(chunk){\r\n data += chunk;\r\n})\r\n\r\nprocess.stdin.on('end', function(chunk){\r\n solve();\r\n})"}, {"source_code": "// var fs = new require('fs');\r\nvar arr = new Array();\r\nvar t = 0;\r\nwhile(arr.length < 1000) {\r\n if(t % 10 != 3 && t % 3 != 0){\r\n arr.push(t);\r\n }\r\n t++;\r\n}\r\nvar t = Number(readline()); // readline()\r\nwhile(t > -1) {\r\n var a = Number(readline());\r\n// if(t != 0) { //\r\n// a = 10 - t; //\r\n// } //\r\n// else { //\r\n// a = 1000; //\r\n// } // redline()\r\n print(arr[a-1]);\r\n t--;\r\n}"}, {"source_code": "var nLoop = readline();\r\nvar dataArray = [];\r\nvar MAX_NUM = 10;\r\n\r\nfor(var j = 1, indx = 0; j <= MAX_NUM; j++) {\r\n if ( j%3 !== 0 && j%10 !== 3 ) {\r\n dataArray[indx] = j;\r\n indx++;\r\n }\r\n}\r\n\r\nfor(var i = 0; i < nLoop; i++) {\r\n inpUser = readline();\r\n print(dataArray[inpUser - 1]);\r\n}"}], "src_uid": "c37604d5d833a567ff284d7ce5eda059"} {"nl": {"description": "This is the hard version of this problem. In this version, we have queries. Note that we do not have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.An array $$$b$$$ of length $$$m$$$ is good if for all $$$i$$$ the $$$i$$$-th element is greater than or equal to $$$i$$$. In other words, $$$b$$$ is good if and only if $$$b_i \\geq i$$$ for all $$$i$$$ ($$$1 \\leq i \\leq m$$$).You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and you are asked $$$q$$$ queries. In each query, you are given two integers $$$p$$$ and $$$x$$$ ($$$1 \\leq p,x \\leq n$$$). You have to do $$$a_p := x$$$ (assign $$$x$$$ to $$$a_p$$$). In the updated array, find the number of pairs of indices $$$(l, r)$$$, where $$$1 \\le l \\le r \\le n$$$, such that the array $$$[a_l, a_{l+1}, \\ldots, a_r]$$$ is good.Note that all queries are independent, which means after each query, the initial array $$$a$$$ is restored. ", "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 n$$$). The third line contains an integer $$$q$$$ ($$$1 \\leq q \\leq 2 \\cdot 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contains two integers $$$p_j$$$ and $$$x_j$$$ ($$$1 \\leq p_j, x_j \\leq n$$$) – the description of the $$$j$$$-th query.", "output_spec": "For each query, print the number of suitable pairs of indices after making the change. ", "sample_inputs": ["4\n2 4 1 4\n3\n2 4\n3 3\n2 1", "5\n1 1 3 2 1\n3\n1 3\n2 5\n4 5"], "sample_outputs": ["6\n10\n5", "7\n9\n8"], "notes": "NoteHere are notes for first example.In first query, after update $$$a=[2,4,1,4]$$$. Now $$$(1,1)$$$, $$$(2,2)$$$, $$$(3,3)$$$, $$$(4,4)$$$, $$$(1,2)$$$, and $$$(3,4)$$$ are suitable pairs.In second query, after update $$$a=[2,4,3,4]$$$. Now all subarrays of $$$a$$$ are good.In third query, after update $$$a=[2,1,1,4]$$$. Now $$$(1,1)$$$, $$$(2,2)$$$, $$$(3,3)$$$, $$$(4,4)$$$, and $$$(3,4)$$$ are suitable."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n res = new Array(m),\r\n f = new Array(n),\r\n g = new Array(n),\r\n max = [0, 0],\r\n s = new Array(n);\r\n for (let i = 0; i < n; i++) {\r\n let d = i - a[i] + 1;\r\n if (max[0] < d) {\r\n max[1] = max[0];\r\n max[0] = d;\r\n } else if (max[1] < d) {\r\n max[1] = d;\r\n }\r\n f[i] = Math.max(0, max[0]);\r\n g[i] = Math.max(0, max[1]);\r\n if (i) s[i] = [s[i - 1][0] + f[i], s[i - 1][1] + g[i]];else s[i] = [f[i], g[i]];\r\n }\r\n s[n] = s[n - 1];\r\n const search = (nums, l, r, d) => {\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (nums[m] >= d) {\r\n r = m;\r\n } else {\r\n l = m + 1;\r\n }\r\n }\r\n return r;\r\n };\r\n let ans = n * (n + 1) / 2;\r\n for (let x = 0; x < m; x++) {\r\n var _f;\r\n let [i, v] = rns(2);\r\n i--;\r\n const d = Math.max(i - v + 1, (_f = f[i - 1]) !== null && _f !== void 0 ? _f : 0);\r\n if (d === f[i]) res[x] = ans - s[n - 1][0];else {\r\n if (d > f[i]) {\r\n const j = search(f, i + 1, n, d);\r\n res[x] = ans - (s[n - 1][0] - s[j - 1][0] + (j - i) * d);\r\n if (i) res[x] -= s[i - 1][0];\r\n } else {\r\n const j = search(g, i, n, d),\r\n k = search(g, j, n, f[i]);\r\n res[x] = ans - (s[n - 1][0] - s[k - 1][0] + (j - i) * d + (s[k - 1][1] - s[j - 1][1]));\r\n if (i) res[x] -= s[i - 1][0];\r\n }\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n res = new Array(m),\r\n f = new Array(n),\r\n g = new Array(n),\r\n max = [0, 0],\r\n s = new Array(n);\r\n for (let i = 0; i < n; i++) {\r\n let d = i - a[i] + 1;\r\n if (max[0] < d) {\r\n max[1] = max[0];\r\n max[0] = d;\r\n } else if (max[1] < d) {\r\n max[1] = d;\r\n }\r\n f[i] = Math.max(0, max[0]);\r\n g[i] = Math.max(0, max[1]);\r\n if (i) s[i] = [s[i - 1][0] + f[i], s[i - 1][1] + g[i]];else s[i] = [f[i], g[i]];\r\n }\r\n s[n] = s[n - 1];\r\n const search = (nums, l, r, d) => {\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (nums[m] >= d) {\r\n r = m;\r\n } else {\r\n l = m + 1;\r\n }\r\n }\r\n return r;\r\n };\r\n const b = new Array(m);\r\n let ans = n * (n + 1) / 2;\r\n for (let x = 0; x < m; x++) {\r\n var _f;\r\n let [i, v] = rns(2);\r\n i--;\r\n b[x] = [i, v, x];\r\n const d = Math.max(i - v + 1, (_f = f[i - 1]) !== null && _f !== void 0 ? _f : 0);\r\n if (d === f[i]) res[x] = ans - s[n - 1][0];else {\r\n if (d > f[i]) {\r\n const j = search(f, i + 1, n, d);\r\n res[x] = ans - (s[n - 1][0] - s[j - 1][0] + (j - i) * d);\r\n if (i) res[x] -= s[i - 1][0];\r\n } else {\r\n const j = search(g, i, n, d),\r\n k = search(g, j, n, f[i]);\r\n res[x] = ans - (s[n - 1][0] - s[k - 1][0] + (j - i) * d + (s[k - 1][1] - s[j - 1][1]));\r\n if (i) res[x] -= s[i - 1][0];\r\n }\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n res = new Array(m),\r\n f = new Array(n),\r\n g = new Array(n),\r\n max = [0, 0],\r\n s = new Array(n);\r\n for (let i = 0; i < n; i++) {\r\n let d = i - a[i] + 1;\r\n if (max[0] < d) {\r\n max[1] = max[0];\r\n max[0] = d;\r\n } else if (max[1] < d) {\r\n max[1] = d;\r\n }\r\n f[i] = Math.max(0, max[0]);\r\n g[i] = Math.max(0, max[1]);\r\n if (i) s[i] = [s[i - 1][0] + f[i], s[i - 1][1] + g[i]];else s[i] = [f[i], g[i]];\r\n }\r\n s[n] = s[n - 1];\r\n const search = (nums, l, r, d) => {\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (nums[m] >= d) {\r\n r = m;\r\n } else {\r\n l = m + 1;\r\n }\r\n }\r\n return r;\r\n };\r\n const b = new Array(m);\r\n let ans = n * (n + 1) / 2;\r\n for (let x = 0; x < m; x++) {\r\n var _f;\r\n let [i, v] = rns(2);\r\n i--;\r\n b[x] = [i, v, x];\r\n const d = Math.max(i - v + 1, (_f = f[i - 1]) !== null && _f !== void 0 ? _f : 0);\r\n if (d === f[i]) res[x] = ans - s[n - 1][0];else {\r\n if (d > f[i]) {\r\n const j = search(f, i + 1, n, d);\r\n res[x] = ans - (s[n - 1][0] - s[j - 1][0] + (j - i) * d);\r\n if (i) res[x] -= s[i - 1][0];\r\n } else {\r\n var _s$, _s;\r\n const j = search(g, i, n, d),\r\n k = search(g, j + 1, n, f[i]);\r\n res[x] = ans - (s[n - 1][0] - s[k - 1][0] + (j - i) * d + (s[k - 1][1] - ((_s$ = (_s = s[j - 1]) === null || _s === void 0 ? void 0 : _s[1]) !== null && _s$ !== void 0 ? _s$ : 0)));\r\n if (i) res[x] -= s[i - 1][0];\r\n }\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n b = new Array(m);\r\n for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];\r\n b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);\r\n const dp = new Array(n).fill(0),\r\n sum = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _dp, _sum;\r\n dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;\r\n sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);\r\n }\r\n const st = [];\r\n const res = [];\r\n let pre = n - 1;\r\n for (let i = n - 1, j = m - 1; i >= 0 && j >= 0; i--) {\r\n if (i === n - 1 || dp[i + 1] <= dp[i]) {\r\n pre = i;\r\n }\r\n const d = dp[i] - i;\r\n while (st.length && st[st.length - 1][0] > d) {\r\n st.pop();\r\n }\r\n if (!st.length || d > st[st.length - 1][0]) st.push([d, i]);\r\n while (j >= 0 && b[j][0] === i) {\r\n if (b[j][1] < dp[i]) {\r\n var _sum2;\r\n const d = b[j][1] - i;\r\n let l = 0,\r\n r = st.length;\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (st[m][0] < d) {\r\n l = m + 1;\r\n } else {\r\n r = m;\r\n }\r\n }\r\n const [, k] = st[l];\r\n const x = k - i + 1;\r\n res[b[j][2]] = ((_sum2 = sum[i - 1]) !== null && _sum2 !== void 0 ? _sum2 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;\r\n } else {\r\n var _dp2;\r\n let d = Math.min((_dp2 = dp[i - 1]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;\r\n if (dp[i] === d) res[b[j][2]] = sum[n - 1];else {\r\n const x = pre - i + 1;\r\n d -= dp[i];\r\n res[b[j][2]] = sum[n - 1] + x * d;\r\n }\r\n }\r\n j--;\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n b = new Array(m);\r\n for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];\r\n b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);\r\n const dp = new Array(n).fill(0),\r\n sum = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _dp, _sum;\r\n dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;\r\n sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);\r\n }\r\n const st = [];\r\n const res = [];\r\n let pre = n - 1;\r\n for (let i = n - 1, j = m - 1; i >= 0; i--) {\r\n if (i === n - 1 || dp[i + 1] <= dp[i]) {\r\n pre = i;\r\n }\r\n const d = dp[i] - i;\r\n while (st.length && st[st.length - 1][0] > d) {\r\n st.pop();\r\n }\r\n if (!st.length || d > st[st.length - 1][0]) st.push([d, i]);\r\n while (j >= 0 && b[j][0] === i) {\r\n if (b[j][0] === n - 1) {\r\n var _sum2, _dp2;\r\n res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;\r\n j--;\r\n continue;\r\n } else if (b[j][1] < dp[i]) {\r\n var _sum3;\r\n const d = b[j][1] - i;\r\n let l = 0,\r\n r = st.length;\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (st[m][0] < d) {\r\n l = m + 1;\r\n } else {\r\n r = m;\r\n }\r\n }\r\n const [, k] = st[l];\r\n const x = k - i + 1;\r\n res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;\r\n } else {\r\n var _dp3;\r\n if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {\r\n const x = pre - i + 1,\r\n d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);\r\n res[b[j][2]] = sum[n - 1] + x * d;\r\n }\r\n }\r\n j--;\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n b = new Array(m);\r\n for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];\r\n b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);\r\n const dp = new Array(n).fill(0),\r\n sum = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _dp, _sum;\r\n dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;\r\n sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);\r\n }\r\n const st = [];\r\n const res = [];\r\n let pre = n - 1;\r\n for (let i = n - 1, j = m - 1; i >= 0; i--) {\r\n if (i === n - 1 || dp[i + 1] <= dp[i]) {\r\n const d = dp[i] - i;\r\n pre = i;\r\n while (st.length && st[st.length - 1][0] >= d) {\r\n st.pop();\r\n }\r\n st.push([d, i]);\r\n }\r\n while (j >= 0 && b[j][0] === i) {\r\n if (b[j][0] === n - 1) {\r\n var _sum2, _dp2;\r\n res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;\r\n j--;\r\n continue;\r\n } else if (b[j][1] < dp[i]) {\r\n var _sum3;\r\n const d = b[j][1] - i;\r\n let l = 0,\r\n r = st.length;\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (st[m][0] < d) {\r\n l = m + 1;\r\n } else {\r\n r = m;\r\n }\r\n }\r\n const [, k] = st[l];\r\n const x = k - i + 1;\r\n res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;\r\n } else {\r\n var _dp3;\r\n if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {\r\n const x = pre - i + 1,\r\n d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);\r\n res[b[j][2]] = sum[n - 1] + x * d;\r\n }\r\n }\r\n j--;\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n b = new Array(m);\r\n for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];\r\n b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);\r\n const dp = new Array(n).fill(0),\r\n sum = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _dp, _sum;\r\n dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;\r\n sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);\r\n }\r\n const st = [];\r\n const res = [];\r\n let pre = n - 1;\r\n for (let i = n - 1, j = m - 1; i >= 0; i--) {\r\n if (i === n - 1 || dp[i + 1] <= dp[i]) {\r\n const d = dp[i] - i;\r\n pre = i;\r\n while (st.length && st[st.length - 1][0] > d) {\r\n st.pop();\r\n }\r\n st.push([d, i]);\r\n }\r\n while (j >= 0 && b[j][0] === i) {\r\n if (b[j][0] === n - 1) {\r\n var _sum2, _dp2;\r\n res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;\r\n j--;\r\n continue;\r\n } else if (b[j][1] < dp[i]) {\r\n var _sum3;\r\n const d = b[j][1] - i;\r\n let l = 0,\r\n r = st.length;\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (st[m][0] < d) {\r\n l = m + 1;\r\n } else {\r\n r = m;\r\n }\r\n }\r\n const [, k] = st[l];\r\n const x = k - i + 1;\r\n res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;\r\n } else {\r\n var _dp3;\r\n if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {\r\n const x = pre - i + 1,\r\n d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);\r\n res[b[j][2]] = sum[n - 1] + x * d;\r\n }\r\n }\r\n j--;\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction _defineProperty(obj, key, value) {\r\n if (key in obj) {\r\n Object.defineProperty(obj, key, {\r\n value: value,\r\n enumerable: true,\r\n configurable: true,\r\n writable: true\r\n });\r\n } else {\r\n obj[key] = value;\r\n }\r\n\r\n return obj;\r\n}\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n b = new Array(m);\r\n for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];\r\n b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);\r\n const dp = new Array(n).fill(0),\r\n sum = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _dp, _sum;\r\n dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;\r\n sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);\r\n }\r\n const tr = new BinarySearchTree((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);\r\n const res = [];\r\n let pre = n - 1;\r\n for (let i = n - 1, j = m - 1; i >= 0; i--) {\r\n if (dp[i + 1] <= dp[i]) {\r\n pre = i;\r\n tr.insert([dp[i] - i, i]);\r\n }\r\n while (j >= 0 && b[j][0] === i) {\r\n if (b[j][0] === n - 1) {\r\n var _sum2, _dp2;\r\n res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;\r\n j--;\r\n continue;\r\n } else if (b[j][1] < dp[i]) {\r\n var _sum3;\r\n const [, k] = tr.ceiling([b[j][1] - i, i]);\r\n const x = k - i + 1;\r\n res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;\r\n } else {\r\n var _dp3;\r\n if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {\r\n const x = pre - i + 1,\r\n d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);\r\n res[b[j][2]] = sum[n - 1] + x * d;\r\n }\r\n }\r\n j--;\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\nclass BinarySearchTree {\r\n constructor(_compare = (a, b) => a - b) {\r\n _defineProperty(this, \"root\", null);\r\n _defineProperty(this, \"length\", 0);\r\n _defineProperty(this, \"min\", null);\r\n _defineProperty(this, \"max\", null);\r\n _defineProperty(this, \"minCache\", true);\r\n _defineProperty(this, \"maxCache\", true);\r\n _defineProperty(this, \"deleteResult\", false);\r\n this._compare = _compare;\r\n this.compare = this.compare.bind(this);\r\n }\r\n isT(t) {\r\n return t !== undefined && t !== null;\r\n }\r\n compare(a, b) {\r\n const {\r\n isT\r\n } = this;\r\n if (isT(a) && isT(b)) return this._compare(a, b);\r\n if (isT(a)) return 1;\r\n if (isT(b)) return -1;\r\n return 0;\r\n }\r\n isEmpty() {\r\n return !this.root;\r\n }\r\n size() {\r\n return this.root ? this.root.size : 0;\r\n }\r\n getRoot() {\r\n return this.root;\r\n }\r\n getMin() {\r\n if (this.minCache) {\r\n return this.min;\r\n }\r\n const min = this.searchKth(this.size());\r\n this.min = min;\r\n this.minCache = true;\r\n return min;\r\n }\r\n getMax() {\r\n if (this.maxCache) {\r\n return this.max;\r\n }\r\n const max = this.searchKth(1);\r\n this.max = max;\r\n this.maxCache = true;\r\n return max;\r\n }\r\n balance(node) {\r\n node.height = this.getHeight(node);\r\n const blance = this.getBalance(node);\r\n let res;\r\n if (Math.abs(blance) === 2) {\r\n if (blance > 0) {\r\n var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;\r\n const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRight(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeftRight(node);\r\n }\r\n } else {\r\n var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;\r\n const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRightLeft(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeft(node);\r\n }\r\n }\r\n }\r\n return res ? res : node;\r\n }\r\n rotateRight(node) {\r\n const left = node.left;\r\n const leftRight = left.right;\r\n left.right = node;\r\n node.left = leftRight;\r\n node.height = this.getHeight(node);\r\n left.height = this.getHeight(left);\r\n node.size = this.getSize(node);\r\n left.size = this.getSize(left);\r\n return left;\r\n }\r\n rotateLeft(node) {\r\n const right = node.right;\r\n const rightLeft = right.left;\r\n right.left = node;\r\n node.right = rightLeft;\r\n node.height = this.getHeight(node);\r\n right.height = this.getHeight(right);\r\n node.size = this.getSize(node);\r\n right.size = this.getSize(right);\r\n return right;\r\n }\r\n rotateLeftRight(node) {\r\n node.left = this.rotateLeft(node.left);\r\n return this.rotateRight(node);\r\n }\r\n rotateRightLeft(node) {\r\n node.right = this.rotateRight(node.right);\r\n return this.rotateLeft(node);\r\n }\r\n getBalance(node) {\r\n return this.getHeight(node.left) - this.getHeight(node.right);\r\n }\r\n getHeight(node) {\r\n var _node$left$height, _node$left3, _node$right$height, _node$right3;\r\n if (!node) return 0;\r\n return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;\r\n }\r\n getSize(node) {\r\n var _node$left$size, _node$left4, _node$right$size, _node$right4;\r\n if (!node) return 0;\r\n return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;\r\n }\r\n createNode(val) {\r\n return {\r\n id: Math.random() * new Date().valueOf(),\r\n val,\r\n left: null,\r\n right: null,\r\n size: 1,\r\n height: 1,\r\n count: 1\r\n };\r\n }\r\n insert(val) {\r\n let cur = this.createNode(val);\r\n if (this.isEmpty()) {\r\n this.root = cur;\r\n this.length++;\r\n } else {\r\n [, cur] = this.insertNode(this.root, cur);\r\n }\r\n if (this.min === null || this.compare(this.min, val) > 0) {\r\n this.min = val;\r\n }\r\n if (this.max === null || this.compare(this.max, val) < 0) {\r\n this.max = val;\r\n }\r\n }\r\n insertNode(node, cur, parent = null) {\r\n node.size++;\r\n const compareResult = this.compare(cur.val, node.val);\r\n let res;\r\n if (compareResult === 0) {\r\n node.count++;\r\n return [false, node];\r\n } else if (compareResult > 0) {\r\n if (node.right) {\r\n res = this.insertNode(node.right, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.right = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n } else {\r\n if (node.left) {\r\n res = this.insertNode(node.left, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.left = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n }\r\n let preHeight = node.height;\r\n const newNode = this.balance(node);\r\n if (newNode === node && node.height === preHeight) {\r\n res = [false, res[1]];\r\n } else if (newNode !== node) {\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n res = [false, res[1]];\r\n }\r\n return res;\r\n }\r\n delete(val) {\r\n this.deleteResult = false;\r\n if (!this.root) return this.deleteResult;\r\n this.deleteNode(val, this.root, null);\r\n return this.deleteResult;\r\n }\r\n deleteNode(val, node, parent) {\r\n if (!node) return null;\r\n let res = this.compare(val, node.val);\r\n if (res === 0) {\r\n this.deleteResult = true;\r\n node.count--;\r\n node.size--;\r\n if (node.count > 0) return node;\r\n if (!node.left || !node.right) {\r\n if (this.min === val) {\r\n this.minCache = false;\r\n }\r\n if (this.max === val) {\r\n this.maxCache = false;\r\n }\r\n this.length--;\r\n if (!parent) {\r\n var _node$left5;\r\n this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;\r\n return this.root;\r\n } else {\r\n var _node$left6;\r\n return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;\r\n }\r\n } else {\r\n const selectLeft = node.left.height > node.right.height;\r\n let replaceNode = selectLeft ? this.pre(node) : this.next(node),\r\n name = selectLeft ? 'left' : 'right';\r\n node.val = replaceNode.val;\r\n node.count = replaceNode.count;\r\n replaceNode.count = 0;\r\n node[name] = this.deleteNode(replaceNode.val, node[name], node);\r\n }\r\n } else if (res > 0) {\r\n node.right = this.deleteNode(val, node.right, node);\r\n } else {\r\n node.left = this.deleteNode(val, node.left, node);\r\n }\r\n node.size = this.getSize(node);\r\n node.height;\r\n const newNode = this.balance(node);\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n return newNode;\r\n }\r\n next(node) {\r\n let next = node.right;\r\n while ((_next = next) !== null && _next !== void 0 && _next.left) {\r\n var _next;\r\n next = next.left;\r\n }\r\n return next;\r\n }\r\n pre(node) {\r\n let pre = node.left;\r\n while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {\r\n var _pre;\r\n pre = pre.right;\r\n }\r\n return pre;\r\n }\r\n search(val, compare) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);\r\n return node.val;\r\n }\r\n searchCeilingNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.searchCeilingNode(node.right, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n const [p, value] = this.searchCeilingNode(node.left, val, compare, node);\r\n if (compare(value.val, val) < 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n ceiling(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) >= 0 ? node.val : null;\r\n }\r\n searchFloorNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n const [p, value] = this.searchFloorNode(node.right, val, compare, node);\r\n if (compare(value.val, val) > 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n return this.searchFloorNode(node.left, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n floor(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchFloorNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) <= 0 ? node.val : null;\r\n }\r\n searchKth(k) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n if (k <= 0 || k > this.size()) {\r\n return null;\r\n }\r\n const node = this.searchNodeKth(this.root, k);\r\n return node.val;\r\n }\r\n searchNodeKth(node, k) {\r\n var _node$right$size2, _node$right5, _node$right$size3, _node$right6;\r\n const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;\r\n if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;\r\n if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);\r\n }\r\n countGreaterThanEq(val) {\r\n if (!this.root) return 0;\r\n return this.countCompare(val, (a, b) => this._compare(a, b), this.root);\r\n }\r\n countCompare(val, compare, node, pre = 0) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n var _node$right$size4, _node$right7;\r\n return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.countCompare(val, compare, node.right, pre);\r\n } else {\r\n return pre;\r\n }\r\n } else {\r\n var _node$right$size5, _node$right8;\r\n let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;\r\n if (node.left) {\r\n return this.countCompare(val, compare, node.left, count);\r\n } else {\r\n return count;\r\n }\r\n }\r\n }\r\n toArray() {\r\n if (!this.root) return [];\r\n const res = [];\r\n const dfs = node => {\r\n if (node.left) dfs(node.left);\r\n res.push(node.val);\r\n if (node.right) dfs(node.right);\r\n };\r\n dfs(this.root);\r\n return res;\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n m = rn(),\r\n b = new Array(m);\r\n for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];\r\n b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);\r\n const dp = new Array(n).fill(0),\r\n sum = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _dp, _sum;\r\n dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;\r\n sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);\r\n }\r\n const st = [];\r\n const res = [];\r\n for (let i = n - 1, j = m - 1; i >= 0; i--) {\r\n if (!st.length || dp[st[st.length - 1]] <= dp[i]) st.push(i);\r\n while (j >= 0 && b[j][0] === i) {\r\n if (b[j][0] === n - 1) {\r\n var _sum2, _dp2;\r\n res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1]) + 1;\r\n j--;\r\n continue;\r\n }\r\n if (b[j][1] < dp[i]) {\r\n var _sum3;\r\n let len = dp[i] - b[j][1] - 1;\r\n let l = 0,\r\n r = st.length - 1;\r\n while (l < r) {\r\n const m = l + r + 1 >> 1;\r\n if (st[m] >= i + len) {\r\n l = m;\r\n } else {\r\n r = m - 1;\r\n }\r\n }\r\n const x = st[l] - i + 1;\r\n res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[st[l]]) + b[j][1] * x + x * (x - 1) / 2;\r\n } else {\r\n var _dp3;\r\n if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {\r\n const x = st[st.length - 1] - i + 1,\r\n d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);\r\n res[b[j][2]] = sum[n - 1] + x * d;\r\n }\r\n }\r\n j--;\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "src_uid": "8a3b87734e221d3ec613525d35eebfd5"} {"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$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of a description contains a keyboard — 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": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n a = lines[i].split('');\n }else{\n var b = lines[i].split('');\n var v = new Map();\n for(j = 0; j < a.length; j++){\n v.set(a[j], j);\n }\n var ans = 0;\n for(j = 1; j < b.length; j++){\n var x = v.get(b[j]);\n var y = v.get(b[j - 1]);\n ans += Math.abs(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n a = lines[i].split('');\n }else{\n var b = lines[i].split('');\n var v = new Map();\n for(j = 0; j < a.length; j++){\n v.set(a[j], j);\n }\n var ans = 0;\n for(j = 1; j < b.length; j++){\n var x = v.get(b[j]);\n var y = v.get(b[j - 1]);\n ans += Math.abs(x - y);\n }\n console.log(ans);\n }\n }\n});\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.abs(x - y);\n }\n console.log(ans);\n }\n }\n});"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.abs(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n\n\n\n\n\n\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var a = new Map();\n for(var j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n a = new Map();\n var keyboard = lines[j];\n for(var l = 1; l < 27; l++){\n a.set(keyboard[l - 1], l);\n }\n }else{\n var word = lines[j];\n var answer = 0;\n var b = 0;\n var c = 0;\n for(var h = 1; h < word.length; h++){\n b = a.get(word[h]);\n c = a.get(word[h - 1]);\n answer += Math.abs(b - c);\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n run(...inputString);\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nconst input = readline();\r\n\r\nfunction run(...args) {\r\n\r\n const findDistance = (keyboard, word) => {\r\n const keyboardMap = {};\r\n for (let i = 0; i <= keyboard.length; i++) {\r\n if (!keyboardMap[keyboard[i]]) {\r\n keyboardMap[keyboard[i]] = i + 1;\r\n }\r\n }\r\n\r\n let sum = 0;\r\n for (let i = 0; i < word.length - 1; i++) {\r\n let firstValue = keyboardMap[word[i]];\r\n let secondValue = keyboardMap[word[i + 1]];\r\n\r\n if (firstValue > secondValue) {\r\n sum += firstValue - secondValue;\r\n } else {\r\n sum += secondValue - firstValue;\r\n }\r\n }\r\n return sum;\r\n };\r\n\r\n for (let i = 1; i < args.length - 1; i+=2) {\r\n const r = findDistance(args[i], args[i + 1]);\r\n console.log(r)\r\n \r\n }\r\n \r\n}"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var a = new Map();\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n a = new Map();\n var keyboard = lines[j];\n for(l = 1; l < 27; l++){\n a.set(keyboard[l - 1], l);\n }\n }else{\n var word = lines[j];\n var answer = 0;\n var b = 0;\n var c = 0;\n for(h = 1; h < word.length; h++){\n b = a.get(word[h]);\n c = a.get(word[h - 1]);\n answer += Math.abs(b - c);\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "\"use strict\";\r\nexports.__esModule = true;\r\nvar readline = require(\"readline\");\r\nvar process = require(\"process\");\r\nvar console_1 = require(\"console\");\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false\r\n});\r\nvar lines = [];\r\nrl.on(\"line\", function (line) {\r\n lines.push(line);\r\n});\r\nrl.on(\"close\", function () {\r\n main();\r\n});\r\nfunction main() {\r\n for (var i = 1; i < lines.length; i += 2) {\r\n var time = solve(lines[i], lines[i + 1]);\r\n console.log(time);\r\n }\r\n}\r\nfunction range(start, length) {\r\n (0, console_1.assert)(length > 0);\r\n return Array.from(Array(length).keys()).map(function (x) { return x + start; });\r\n}\r\nfunction solve(keyboard, word) {\r\n if (word.length <= 1) {\r\n return 0;\r\n }\r\n var keys = Array.from(keyboard);\r\n var keyIndexes = range(0, keyboard.length);\r\n var keyMap = new Map(keyIndexes.map(function (i) { return [keys[i], i]; }));\r\n var wordIndexes = Array.from(word).map(function (c) { return keyMap.get(c); });\r\n var distances = range(0, word.length - 1).map(function (i) {\r\n return Math.abs(wordIndexes[i] - wordIndexes[i + 1]);\r\n });\r\n var time = distances.reduce(function (x, y) { return x + y; }, 0);\r\n return time;\r\n}\r\n"}, {"source_code": "var readline = require(\"readline\");\r\n\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false,\r\n});\r\n\r\nvar lines = [];\r\n\r\nrl.on(\"line\", function (line) {\r\n lines.push(line);\r\n});\r\n\r\nrl.on(\"close\", function () {\r\n for (let i = 1; i < lines.length; i += 2) {\r\n let time = solve(lines[i], lines[i + 1]);\r\n console.log(time);\r\n }\r\n});\r\n\r\nfunction solve(keyboard, s) {\r\n if (s.length <= 1) {\r\n return 0;\r\n }\r\n\r\n let keyboardMap = new Map();\r\n for (let i = 0; i < keyboard.length; i++) {\r\n keyboardMap.set(keyboard[i], i);\r\n }\r\n\r\n letterPositions = [];\r\n\r\n for (let i = 0; i < s.length; i++) {\r\n letterPositions.push(keyboardMap.get(s[i]));\r\n }\r\n\r\n let time = 0;\r\n let handPosition = letterPositions[0];\r\n\r\n for (let i = 1; i < s.length; i++) {\r\n time += Math.abs(letterPositions[i] - handPosition);\r\n handPosition = letterPositions[i];\r\n }\r\n\r\n return time;\r\n}\r\n"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\nlet alpha;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2 === 1) {\n alpha = d;\n c++;\n return;\n }\n\n let ans = 0;\n const idxes = [];\n const word = d;\n\n for (let i = 0; i < word.length; i++) {\n const idx = alpha.indexOf(word[i]);\n idxes.push(idx);\n }\n\n for (let i = 1; i < idxes.length; i++) {\n ans += Math.abs(idxes[i - 1] - idxes[i]);\n }\n\n console.log(ans);\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "// cls; cat .\\input.txt | node .\\script.js\r\n// codium --diff file1.js file2.js\r\n'use strict';\r\nlet data = ''; // raw\r\nlet inputs = ''; // iterator\r\nfunction read() { return inputs.next().value.trim(); };\r\n\r\nasync function solve() {\r\n let t_1 = (await read()).split('')\r\n let t_2 = (await read()).split('')\r\n let keyMap = new Map(t_1.map((e, i) =>\r\n [e, i + 1]\r\n ))\r\n let reduced = t_2.reduce((a, e, i, o) => {\r\n if (i == 0) return a\r\n let current = keyMap.get(o[i])\r\n let previous = keyMap.get(o[i - 1])\r\n let diff = Math.abs(current - previous)\r\n return a + diff\r\n }, 0)\r\n console.log(reduced)\r\n}\r\n\r\nasync function main() {\r\n let tasks_amount = parseInt(await read())\r\n for (let i = 0; i < tasks_amount; i++) {\r\n await solve()\r\n }\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => data += input);\r\nprocess.stdin.on('end', async () => {\r\n let splitted = data.split('\\r\\n')\r\n inputs = await splitted.values();\r\n await main();\r\n});"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let j = 0; j < t; j++){\n\t\tlet a = nl.line().split('');\n\t\tlet b = nl.line().split('');\n\t\tlet al = {};\n\t\ta.forEach((e, i) => al[e] = i);\n\t\tlet cnt = 0;\n\t\tfor(let i = 1; i < b.length; i++) {\n\t\t\tcnt += Math.abs(al[b[i]] - al[b[i-1]]);\n\t\t}\n\t\tans.push(cnt);\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst k = rl();\r\n\t\tconst s = rl();\r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 1; i < s.length; i++) {\r\n\t\t\tans += Math.abs(k.indexOf(s[i]) - k.indexOf(s[i-1]));\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "/*\r\n** 1607a Linear Keyboard\r\n*/\r\n\r\n// Common Template Starts //\r\n//*\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Common Template Ends //\r\n\r\n\r\n// LIBRARY START //\r\n\r\nconst isOdd = (x) => { return x & 1 }\r\nconst isEven = (x) => { return !(x & 1) }\r\n\r\nconst reverseText = (s) => { return s.split('').reverse().join('') }\r\nconst hasDuplicates = (str) => (/([a-z])\\1/i).test(str)\r\n\r\nconst hasDuplicateChar = (str, char) => str.indexOf(char) !== str.lastIndexOf(char)\r\n\r\nconst isSorted = arr => arr.every((v, i, a) => !i || a[i - 1] <= v);\r\n\r\nconst findAllIndicesOfChar = (str, char) => {\r\n str = str.split('')\r\n let indices = [];\r\n for (let i = 0; i < str.length; i++) {\r\n if (str[i] === char) indices.push(i);\r\n }\r\n return indices\r\n}\r\n\r\nconst splitAt = index => x => [x.slice(0, index), x.slice(index)]\r\n\r\nconst isUpper = str => !/[a-z]/.test(str) && /[A-Z]/.test(str)\r\n\r\nconst escapeRegExp = (string) => string.replace(/[.*+\\-?^${}()|[\\]\\\\]/g, '\\\\$&')\r\n\r\nconst replaceAll = (str, find, replace) => str.replace(new RegExp(escapeRegExp(find), 'g'), replace)\r\n\r\nconst findUnique = (str) => {\r\n return [...str].reduce((acc, curr) => {\r\n return acc.includes(curr) ? acc : acc + curr;\r\n }, \"\")\r\n}\r\n\r\n// LIBRARY END\r\n\r\nconst tempPrintFunc = (keyboard, word) => {\r\n keyboard = keyboard.split('')\r\n word = word.split('')\r\n\r\n let val = 0\r\n let currChar = word[0]\r\n\r\n while (word.length > 0) {\r\n nextChar = word.shift()\r\n\r\n curr_pos = keyboard.indexOf(currChar)\r\n next_pos = keyboard.indexOf(nextChar)\r\n\r\n val += Math.abs(curr_pos - next_pos)\r\n\r\n currChar = nextChar\r\n }\r\n\r\n return val\r\n}\r\n\r\n//*\r\nfunction main() {\r\n let cases = readline()\r\n\r\n while (cases--) {\r\n let keyboard = readline()\r\n let word = readline()\r\n console.log(tempPrintFunc(keyboard, word))\r\n }\r\n}\r\n//*/\r\n\r\n\r\n\r\n// let keyboard = ''\r\n// let word = ''\r\n\r\n\r\n// keyboard = 'abcdefghijklmnopqrstuvwxyz'\r\n// word = 'hello'\r\n// console.log(tempPrintFunc(keyboard, word) == 13)\r\n\r\n// keyboard = 'abcdefghijklmnopqrstuvwxyz'\r\n// word = 'i'\r\n// console.log(tempPrintFunc(keyboard, word) == 0)\r\n\r\n// keyboard = 'abcdefghijklmnopqrstuvwxyz'\r\n// word = 'codeforces'\r\n// console.log(tempPrintFunc(keyboard, word) == 68)\r\n\r\n// keyboard = 'qwertyuiopasdfghjklzxcvbnm'\r\n// word = 'qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq'\r\n// console.log(tempPrintFunc(keyboard, word) == 0)\r\n\r\n// keyboard = 'qwertyuiopasdfghjklzxcvbnm'\r\n// word = 'abacaba'\r\n// console.log(tempPrintFunc(keyboard, word) == 74)"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let t = Number(readline())\r\n for (let j = 1; j <= t; j++) {\r\n let s=readline();\r\n let n=s.length;\r\n let x=readline();\r\n let ans=0;\r\n let mp=new Map();\r\n for(let i=0;i {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main(){\r\n let input = Number(readline());\r\n let output = [];\r\n for(let i=0; i (i += c));\r\nprocess.stdin.on(\"end\", () => {\r\n const { EOL } = require(\"os\");\r\n const input = i.split(EOL);\r\n const n = input[0];\r\n let alphabetIndex = 1;\r\n let wordIndex = 2;\r\n for (let i = 0; i < n; i++) {\r\n console.log(findSum (input, alphabetIndex, wordIndex));\r\n alphabetIndex += 2;\r\n wordIndex += 2;\r\n }\r\n \r\n \r\n})"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n main()\r\n process.exit(0)\r\n }\r\n }\r\n)\r\n\r\n\r\nfunction solve(keyboard, str) {\r\n str = str.split('')\r\n let res = 0\r\n for (let i = 0; i < str.length - 1; ++i) {\r\n res += Math.abs((keyboard.indexOf(str[i]) + 1) - (keyboard.indexOf(str[i + 1]) + 1))\r\n }\r\n console.log(res)\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b == 0)\r\n return a;\r\n return gcd(b, a % b);\r\n}\r\n// let a=readline().split(' ').map(Number)\r\n// a.sort((a,b)=>a-b)\r\n\r\nfunction main() {\r\n let t = Number(readline())\r\n for (let j = 1; j <= t; j++) {\r\n let s=readline();\r\n let n=s.length;\r\n let x=readline();\r\n let ans=0;\r\n let mp=new Map();\r\n for(let i=0;i stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n\n\n\n\n\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n\n\n\n\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n\n\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i].split('');\n a = new Map();\n for(j = 1; j <= n.length; j++){\n a.set(n[j - 1], j);\n }\n }else{\n var k = lines[i].split('');\n var ans = 0;\n var x = 0, y = 0;\n for(j = 1; j < k.length; j++){\n x = a.get(k[j]);\n y = a.get(k[j - 1]);\n ans += Math.floor(x - y);\n }\n console.log(ans);\n }\n }\n});\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var a = new Map();\n for(var j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n a = new Map();\n var keyboard = lines[j];\n for(var l = 1; l < 27; l++){\n a.set(keyboard[l], l);\n }\n }else{\n var word = lines[j];\n var answer = 0;\n var b = 0;\n var c = 0;\n for(var h = 1; h < word.length; h++){\n b = a.get(word[h]);\n c = a.get(word[h - 1]);\n answer += Math.abs(b - c);\n }\n if(isNaN(answer)){\n answer = 0;\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n console.log(typeof inputString)\r\n run(...inputString);\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nconst input = readline();\r\n\r\nfunction run(...args) {\r\n console.log(args[1])\r\n const findDistance = (keyboard, word) => {\r\n const keyboardMap = {};\r\n for (let i = 0; i <= keyboard.length; i++) {\r\n if (!keyboardMap[keyboard[i]]) {\r\n keyboardMap[keyboard[i]] = i + 1;\r\n }\r\n }\r\n\r\n let sum = 0;\r\n for (let i = 1; i < word.length - 1; i++) {\r\n let firstValue = keyboardMap[word[i]];\r\n let secondValue = keyboardMap[word[i + 1]];\r\n\r\n if (firstValue > secondValue) {\r\n sum += firstValue - secondValue;\r\n } else {\r\n sum += secondValue - firstValue;\r\n }\r\n }\r\n return sum;\r\n };\r\n\r\n for (let i = 0; i < args.length - 1; i+=2) {\r\n const r = findDistance(args[i], args[i + 1]);\r\n console.log(r)\r\n \r\n }\r\n \r\n}"}, {"source_code": "function run(t, ...args) {\r\n const findDistance = (keyboard, word) => {\r\n const keyboardMap = {};\r\n for (let i = 0; i <= keyboard.length; i++) {\r\n if (!keyboardMap[keyboard[i]]) {\r\n keyboardMap[keyboard[i]] = i + 1;\r\n }\r\n }\r\n\r\n let sum = 0;\r\n for (let i = 0; i < word.length - 1; i++) {\r\n let firstValue = keyboardMap[word[i]];\r\n let secondValue = keyboardMap[word[i + 1]];\r\n\r\n if (firstValue > secondValue) {\r\n sum += firstValue - secondValue;\r\n } else {\r\n sum += secondValue - firstValue;\r\n }\r\n }\r\n return sum;\r\n };\r\n const res = [];\r\n for (let i = 0; i < args.length - 1; i+=2) {\r\n const r = findDistance(args[i], args[i + 1]);\r\n console.log(r)\r\n res.push(r);\r\n }\r\n return res;\r\n}"}, {"source_code": "function run(t, ...args) {\r\n const findDistance = (keyboard, word) => {\r\n const keyboardMap = {};\r\n for (let i = 0; i <= keyboard.length; i++) {\r\n if (!keyboardMap[keyboard[i]]) {\r\n keyboardMap[keyboard[i]] = i + 1;\r\n }\r\n }\r\n\r\n let sum = 0;\r\n for (let i = 0; i < word.length - 1; i++) {\r\n let firstValue = keyboardMap[word[i]];\r\n let secondValue = keyboardMap[word[i + 1]];\r\n\r\n if (firstValue > secondValue) {\r\n sum += firstValue - secondValue;\r\n } else {\r\n sum += secondValue - firstValue;\r\n }\r\n }\r\n return sum;\r\n };\r\n const res = [];\r\n for (let i = 0; i < args.length - 1; i+=2) {\r\n const r = findDistance(args[i], args[i + 1]);\r\n console.log(r)\r\n res.push(r);\r\n }\r\n return res;\r\n}\r\n\r\nrun(5,\r\n 'abcdefghijklmnopqrstuvwxyz',\r\n 'hello',\r\n 'abcdefghijklmnopqrstuvwxyz',\r\n 'i',\r\n 'abcdefghijklmnopqrstuvwxyz',\r\n 'codeforces',\r\n 'qwertyuiopasdfghjklzxcvbnm',\r\n 'qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq',\r\n 'qwertyuiopasdfghjklzxcvbnm',\r\n 'abacaba');"}, {"source_code": "function run (t, ...args) {\r\n const findDistance = (keyboard, word) => {\r\n const keyboardMap = {};\r\n for (let i = 0; i <= keyboard.length; i++) {\r\n if (!keyboardMap[keyboard[i]]) {\r\n keyboardMap[keyboard[i]] = i+1;\r\n }\r\n }\r\n\r\n let sum = 0;\r\n for (let i =0; i < word.length -1; i++) {\r\n let firstValue = keyboardMap[word[i]];\r\n let secondValue = keyboardMap[word[i+1]];\r\n \r\n if (firstValue > secondValue) {\r\n sum += firstValue -secondValue;\r\n } else {\r\n sum += secondValue -firstValue;\r\n }\r\n }\r\n return sum;\r\n }\r\n const res = [];\r\n for (let i = 0; i < args.length - 1; i++) {\r\n res.push(findDistance(args[i], args[i+1]));\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "function run (t, ...args) {\r\n const findDistance = (keyboard, word) => {\r\n const keyboardMap = {};\r\n for (let i = 0; i <= keyboard.length; i++) {\r\n if (!keyboardMap[keyboard[i]]) {\r\n keyboardMap[keyboard[i]] = i+1;\r\n }\r\n }\r\n\r\n let sum = 0;\r\n for (let i =0; i < word.length -1; i++) {\r\n let firstValue = keyboardMap[word[i]];\r\n let secondValue = keyboardMap[word[i+1]];\r\n \r\n if (firstValue > secondValue) {\r\n sum += firstValue -secondValue;\r\n } else {\r\n sum += secondValue -firstValue;\r\n }\r\n }\r\n return sum;\r\n }\r\n\r\n for (let i = 0; i < args.length - 1; i++) {\r\n console.log(findDistance(args[i], args[i+1]));\r\n }\r\n\r\n}"}, {"source_code": "const findDistance = (keyboard, word) => {\r\n const keyboardMap = {};\r\n for (let i = 0; i <= keyboard.length; i++) {\r\n if (!keyboardMap[keyboard[i]]) {\r\n keyboardMap[keyboard[i]] = i+1;\r\n }\r\n }\r\n let sum = 0;\r\n for (let i =0; i < word.length -1; i++) {\r\n let firstValue = keyboardMap[word[i]];\r\n let secondValue = keyboardMap[word[i+1]];\r\n\r\n if (firstValue > secondValue) {\r\n sum += firstValue -secondValue;\r\n } else {\r\n sum += secondValue -firstValue;\r\n }\r\n }\r\n return sum;\r\n}"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var a = new Map();\n for(var j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n a = new Map();\n var keyboard = lines[j];\n for(var l = 1; l < 27; l++){\n a.set(keyboard[l - 1], l);\n }\n }else{\n var word = lines[j];\n var answer = 0;\n var b = 0;\n var c = 0;\n for(var h = 1; h < word.length; h++){\n b = a.get(word[h]);\n c = a.get(word[h - 1]);\n answer += Math.abs(b - c);\n }\n console.log(answer - 1);\n }\n }\n});"}], "src_uid": "7f9853be7ac857bb3c4eb17e554ad3f1"} {"nl": {"description": "Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on n·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?", "input_spec": "The first input file line contains a number n (2 ≤ n ≤ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on n·(n - 1) / 2 lines. Each set starts with the number ki (2 ≤ ki ≤ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≤ aij ≤ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.", "output_spec": "Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.", "sample_inputs": ["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"], "sample_outputs": ["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n let M = ipt.split(EOL).slice(1, -1).map(l => l.split(' ').slice(1).map(v => parseInt(v)))\n\n if (M.length == 1) {\n console.log(`${M[0].length / 2 | 0} ${M[0].slice(0, M[0].length / 2 | 0).join(' ')}`)\n console.log(`${M[0].length - M[0].length / 2 | 0} ${M[0].slice(M[0].length / 2 | 0).join(' ')}`)\n return\n }\n\n let O = {}\n for (let i = 0; i < M.length; i++) {\n for (let j = 0; j < M[i].length; j++) {\n O[M[i][j]] = O[M[i][j]] || []\n O[M[i][j]].push(i)\n }\n }\n\n let I = {}\n for (const k in O) {\n let o = O[k]\n let ok = o.sort((a, b) => a - b).join(' ')\n I[ok] = I[ok] || []\n I[ok].push(k)\n }\n\n let R = []\n for (const k in I) {\n let i = I[k]\n console.log(`${i.length} ${i.join(' ')}`)\n }\n})"}], "negative_code": [{"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n let M = ipt.split(EOL).slice(1, -1).map(l => l.split(' ').slice(1).map(v => parseInt(v)))\n\n let O = {}\n for (let i = 0; i < M.length; i++) {\n for (let j = 0; j < M[i].length; j++) {\n O[M[i][j]] = O[M[i][j]] || []\n O[M[i][j]].push(i)\n }\n }\n\n let I = {}\n for (const k in O) {\n let o = O[k]\n let ok = o.sort((a, b) => a - b).join(' ')\n I[ok] = I[ok] || []\n I[ok].push(k)\n }\n\n let R = []\n for (const k in I) {\n let i = I[k]\n console.log(`${i.length} ${i.join(' ')}`)\n }\n})"}], "src_uid": "bde894dc01c65da67d32c716981926f6"} {"nl": {"description": "There are $$$n$$$ robbers at coordinates $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ and $$$m$$$ searchlight at coordinates $$$(c_1, d_1)$$$, $$$(c_2, d_2)$$$, ..., $$$(c_m, d_m)$$$. In one move you can move each robber to the right (increase $$$a_i$$$ of each robber by one) or move each robber up (increase $$$b_i$$$ of each robber by one). Note that you should either increase all $$$a_i$$$ or all $$$b_i$$$, you can't increase $$$a_i$$$ for some points and $$$b_i$$$ for some other points.Searchlight $$$j$$$ can see a robber $$$i$$$ if $$$a_i \\leq c_j$$$ and $$$b_i \\leq d_j$$$. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair $$$i,j$$$ such that searchlight $$$j$$$ can see a robber $$$i$$$).What is the minimum number of moves you need to perform to reach a safe configuration?", "input_spec": "The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 2000$$$): the number of robbers and the number of searchlight. Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$0 \\leq a_i, b_i \\leq 10^6$$$), coordinates of robbers. Each of the next $$$m$$$ lines contains two integers $$$c_i$$$, $$$d_i$$$ ($$$0 \\leq c_i, d_i \\leq 10^6$$$), coordinates of searchlights.", "output_spec": "Print one integer: the minimum number of moves you need to perform to reach a safe configuration.", "sample_inputs": ["1 1\n0 0\n2 3", "2 3\n1 6\n6 1\n10 1\n1 10\n7 7", "1 2\n0 0\n0 0\n0 0", "7 3\n0 8\n3 8\n2 7\n0 10\n5 5\n7 0\n3 5\n6 6\n3 11\n11 5"], "sample_outputs": ["3", "4", "1", "6"], "notes": "NoteIn the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates $$$(3, 0)$$$.The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates $$$(2, 3)$$$ and $$$3 > 2$$$.In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates $$$(3, 8)$$$, $$$(8, 3)$$$.It's easy the see that the configuration of the robbers is safe.It can be proved that you can't reach a safe configuration using no more than $$$3$$$ moves."}, "positive_code": [{"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn, init) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);\n if (b < a) return [];\n let arr = Array(b - a + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nlet MOD = 998244353\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + MOD) % MOD;\n}\n\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let [n, m] = $(2)\n let a = Arr(n, i => ({ x: $(), y: $() }))\n let b = Arr(m, i => ({ x: $(), y: $() }))\n let y = Array(1e6 + 2).fill(0)\n For(n, i => {\n For(m, j => {\n if (a[i].x > b[j].x) return;\n y[b[j].x - a[i].x] = max(y[b[j].x - a[i].x], b[j].y - a[i].y + 1);\n })\n })\n let res = 1e10\n ForR(1e6 + 1, i => {\n y[i] = max(y[i], y[i + 1]);\n res = min(res, i + y[i])\n })\n log(res)\n}\n"}], "negative_code": [], "src_uid": "9a7e6c494ff7d161c92632569a6ecbef"} {"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 — 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 — 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": "var ans = [];\nreadline().replace(/\\\"([^\"]*)\\\"|(\\S+)/g, function(_, a, b) {\n\tans.push('<' + (b || a) + '>');\n\treturn '';\n});\nprint(ans.join('\\n'));"}, {"source_code": ";(function () {\n\n\tprint(function (s, result) {\n\n\t\ts = s.trim().split('');\n\n\t\tvar word = '', isQuote = false;\n\n\t\tfor (var i = 0, _i = s.length; i < _i; i++) {\n\t\t\tif (s[i] === '\"') {\n\t\t\t\tif (isQuote) {\n\t\t\t\t\tresult.push(['<', word, '>'].join(''));\n\t\t\t\t\tword = '';\n\t\t\t\t}\n\n\t\t\t\tisQuote = !isQuote;\n\t\t\t} else if (isQuote === false && s[i] === ' ') {\n\t\t\t\tword = word.trim();\n\t\t\t\tif (word.length) {\n\t\t\t\t\tresult.push(['<', word, '>'].join(''));\n\t\t\t\t}\n\t\t\t\tword = '';\n\t\t\t} else {\n\t\t\t\tword += s[i];\n\t\t\t}\n\t\t}\n\n\t\tif (word.length) {\n\t\t\tresult.push(['<', word, '>'].join(''));\n\t\t}\n\n\t\treturn result.join('\\n');\n\n\t}(readline(), []));\n\n}.call(this));\n"}, {"source_code": "//var command = ' firstarg second \"\" '\nvar command = readline()\n , quoteOpen = false\n , spaceWas = false;\n//print('command: ' + command);\ncommand = ' ' + command;\nfor (var i = 0, lex = ''; i < command.length; i++) {\n if (command[i] === '\"') {\n if (quoteOpen) {\n print(\"<\"+lex+\">\");\n quoteOpen = false;\n spaceWas = false;\n lex = '';\n } else {\n quoteOpen = true;\n spaceWas = false;\n lex = '';\n }\n } else if (command[i] === ' ') {\n if (!quoteOpen) {\n if (!spaceWas) {\n spaceWas = true;\n } else if (command[i-1] !== ' '){\n print(\"<\"+lex+\">\");\n lex = '';\n }\n } else {\n lex += command[i];\n }\n } else {\n lex += command[i];\n }\n}\nif (lex) print(\"<\"+lex+\">\");"}, {"source_code": "function main()\n{\n var s = readline();\n var ans = \"\";\n var flag = false,\n quote = false;\n for ( var i = 0; i < s.length; i++ )\n {\n if ( s[i] == \"\\\"\" )\n {\n if ( quote )\n {\n print(\"<\"+ans+\">\");\n ans = \"\";\n }\n quote = !quote;\n }\n else if ( !quote && s[i] == \" \" )\n {\n if ( ans.length )\n {\n print(\"<\"+ans+\">\");\n ans = \"\";\n }\n }\n else\n {\n ans += s[i];\n }\n }\n if ( ans != \"\" )\n print(\"<\"+ans+\">\");\n}\n\nmain();\n"}, {"source_code": "function main()\n{\n var s = readline();\n var ans = \"\";\n var flag = false,\n quote = false;\n for ( var i = 0; i < s.length; i++ )\n {\n if ( !flag )\n {\n if ( s[i] == \"\\\"\" )\n {\n flag = true;\n quote = true;\n }\n else if ( s[i] != \" \" )\n {\n ans += s[i];\n flag = true;\n }\n }\n else\n {\n if ( quote == true )\n {\n if ( s[i] == \"\\\"\" )\n {\n print(\"<\"+ans+\">\");\n ans = \"\";\n flag = false;\n quote = false;\n }\n else\n {\n ans += s[i];\n }\n }\n else\n {\n if ( s[i] == \" \" )\n {\n print(\"<\"+ans+\">\");\n ans = \"\";\n flag = false;\n quote = false;\n }\n else\n {\n ans += s[i];\n }\n }\n }\n }\n if ( ans != \"\" )\n print(\"<\"+ans+\">\");\n}\n\nmain();\n"}, {"source_code": "function main(){\n var s = readline();\n var ans = \"\";\n var flag = false,\n quote = false;\n for ( var i = 0; i < s.length; i++ ){\n if ( s[i] == \"\\\"\" ){\n if ( quote ){\n print(\"<\"+ans+\">\");\n ans = \"\";\n }\n quote = !quote;\n }\n else if ( !quote && s[i] == \" \" ){\n if ( ans.length ){\n print(\"<\"+ans+\">\");\n ans = \"\";\n }\n }\n else{\n ans += s[i];\n }\n }\n if ( ans != \"\" )\n print(\"<\"+ans+\">\");\n}\n\nmain();\n"}], "negative_code": [{"source_code": ";(function () {\n\n\tprint(function (s, result) {\n\n\t\ts = s.trim().split('');\n\n\t\tvar word = '', isQuote = false;\n\n\t\tfor (var i = 0, _i = s.length; i < _i; i++) {\n\t\t\tif (s[i] === '\"') {\n\t\t\t\tif (isQuote) {\n\t\t\t\t\tisQuote = false;\n\t\t\t\t\tresult.push(['<', word, '>'].join(''));\n\t\t\t\t\tword = '';\n\t\t\t\t} else {\n\t\t\t\t\tisQuote = true;\n\t\t\t\t}\n\t\t\t} else if (isQuote === false && s[i] === ' ') {\n\t\t\t\tword = word.trim();\n\t\t\t\tif (word.length) result.push(['<', word, '>'].join(''));\n\t\t\t\tword = '';\n\t\t\t} else {\n\t\t\t\tword += s[i];\n\t\t\t}\n\t\t}\n\n\t\treturn result.join('\\n');\n\n\t}(readline(), []));\n\n}.call(this));\n"}, {"source_code": "//var command = ' firstarg second \"\" '\nvar command = readline()\n , quoteOpen = false\n , spaceWas = false;\n\nfor (var i = 0, lex = ''; i < command.length; i++) {\n if (command[i] === '\"') {\n if (quoteOpen) {\n print(\"<\"+lex+\">\");\n quoteOpen = false;\n spaceWas = false;\n lex = '';\n } else {\n quoteOpen = true;\n spaceWas = false;\n lex = '';\n }\n } else if (command[i] === ' ') {\n if (!quoteOpen) {\n if (!spaceWas) {\n spaceWas = true;\n lex = '';\n } else if (command[i-1] !== ' '){\n print(\"<\"+lex+\">\");\n lex = '';\n }\n } else {\n lex += command[i];\n }\n } else {\n lex += command[i];\n }\n}\n"}, {"source_code": "//var command = ' firstarg second \"\" '\nvar command = readline()\n , quoteOpen = false\n , spaceWas = false;\n//print('command: ' + command);\nfor (var i = 0, lex = ''; i < command.length; i++) {\n if (command[i] === '\"') {\n if (quoteOpen) {\n print(\"<\"+lex+\">\");\n quoteOpen = false;\n spaceWas = false;\n lex = '';\n } else {\n quoteOpen = true;\n spaceWas = false;\n lex = '';\n }\n } else if (command[i] === ' ') {\n if (!quoteOpen) {\n if (!spaceWas) {\n spaceWas = true;\n lex = '';\n } else if (command[i-1] !== ' '){\n print(\"<\"+lex+\">\");\n lex = '';\n }\n } else {\n lex += command[i];\n }\n } else {\n lex += command[i];\n }\n}\nif (lex) print(\"<\"+lex+\">\");"}, {"source_code": "//var command = ' firstarg second \"\" '\nvar command = readline()\n , quoteOpen = false\n , spaceWas = false;\n//print('command' + command);\nfor (var i = 0, lex = ''; i < command.length; i++) {\n if (command[i] === '\"') {\n if (quoteOpen) {\n print(\"<\"+lex+\">\");\n quoteOpen = false;\n spaceWas = false;\n lex = '';\n } else {\n quoteOpen = true;\n spaceWas = false;\n lex = '';\n }\n } else if (command[i] === ' ') {\n if (!quoteOpen) {\n if (!spaceWas) {\n spaceWas = true;\n lex = '';\n } else if (command[i-1] !== ' '){\n print(\"<\"+lex+\">\");\n lex = '';\n }\n } else {\n lex += command[i];\n }\n } else {\n lex += command[i];\n }\n}\nif (lex) print(\"<\"+lex+\">\");"}, {"source_code": "//var command = ' firstarg second \"\" '\nvar command = readline()\n , quoteOpen = false\n , spaceWas = false;\nprint('command: ' + command);\nfor (var i = 0, lex = ''; i < command.length; i++) {\n if (command[i] === '\"') {\n if (quoteOpen) {\n print(\"<\"+lex+\">\");\n quoteOpen = false;\n spaceWas = false;\n lex = '';\n } else {\n quoteOpen = true;\n spaceWas = false;\n lex = '';\n }\n } else if (command[i] === ' ') {\n if (!quoteOpen) {\n if (!spaceWas) {\n spaceWas = true;\n } else if (command[i-1] !== ' '){\n print(\"<\"+lex+\">\");\n lex = '';\n }\n } else {\n lex += command[i];\n }\n } else {\n lex += command[i];\n }\n}\nif (lex) print(\"<\"+lex+\">\");"}, {"source_code": "//var command = ' firstarg second \"\" '\nvar command = readline()\n , quoteOpen = false\n , spaceWas = false;\n//print('command: ' + command);\nfor (var i = 0, lex = ''; i < command.length; i++) {\n if (command[i] === '\"') {\n if (quoteOpen) {\n print(\"<\"+lex+\">\");\n quoteOpen = false;\n spaceWas = false;\n lex = '';\n } else {\n quoteOpen = true;\n spaceWas = false;\n lex = '';\n }\n } else if (command[i] === ' ') {\n if (!quoteOpen) {\n if (!spaceWas) {\n spaceWas = true;\n } else if (command[i-1] !== ' '){\n print(\"<\"+lex+\">\");\n lex = '';\n }\n } else {\n lex += command[i];\n }\n } else {\n lex += command[i];\n }\n}\nif (lex) print(\"<\"+lex+\">\");"}, {"source_code": "function main()\n{\n var s = readline();\n var ans = \"\";\n var flag = false,\n quote = false;\n for ( var i = 0; i < s.length; i++ )\n {\n if ( !flag )\n {\n if ( s[i] == \"\\\"\" )\n {\n flag = true;\n quote = true;\n }\n else if ( s[i] != \" \" )\n {\n ans += s[i];\n flag = true;\n }\n }\n else\n {\n if ( quote == true )\n {\n if ( s[i] == \"\\\"\" )\n {\n print(\"<\"+ans+\">\");\n ans = \"\";\n flag = false;\n quote = false;\n }\n else\n {\n ans += s[i];\n }\n }\n else\n {\n if ( s[i] == \" \" )\n {\n print(\"<\"+ans+\">\");\n ans = \"\";\n flag = false;\n quote = false;\n }\n else\n {\n ans += s[i];\n }\n }\n }\n }\n}\n\nmain();\n"}], "src_uid": "6c7858731c57e1b24c7a299a8eeab373"} {"nl": {"description": "Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session.The game involves $$$n$$$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session.Find the minimum possible amount of balls that were involved in the game.", "input_spec": "There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 5 \\cdot 10^4$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 10^5$$$) — the number of players. The second line of the test case contains a sequence of integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 10^9$$$), where $$$a_i$$$ is the number of passes delivered by the $$$i$$$-th player. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print a single integer — the answer to the problem.", "sample_inputs": ["4\n4\n2 3 3 2\n3\n1 5 2\n2\n0 0\n4\n1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["1\n2\n0\n1"], "notes": "NoteIn the first test case, with the only ball, the game can go like this:$$$2 \\rightarrow 1 \\rightarrow 3 \\rightarrow 4 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4 \\rightarrow 2 \\rightarrow 3 \\rightarrow 2$$$.In the second test case, there is no possible way to play the game with only one ball. One possible way to play with two balls:$$$2 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 2 \\rightarrow 1$$$.$$$2 \\rightarrow 3 \\rightarrow 2 \\rightarrow 1$$$In the third example, there were no passes, so $$$0$$$ balls are possible."}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n let max = 0,\r\n sum = 0;\r\n for (let i = 0; i < n; i++) {\r\n max = Math.max(max, arr[i]);\r\n sum += arr[i];\r\n }\r\n if (sum === 0) console.log(0);\r\n else {\r\n sum = sum - max;\r\n if (sum >= max - 1) console.log(1);\r\n else console.log(1 + (max - sum - 1));\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value;\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet mx = Math.max(...a);\r\n\r\n\t\tlet sum = 0;\r\n\t\tfor (let i = 0; i < n; i++) sum += a[i];\r\n\t\tsum -= mx;\r\n\r\n\t\tlet ans;\r\n\t\tif (mx == 0) ans = 0;\r\n\t\telse if (sum >= mx) ans = 1;\r\n\t\telse ans = mx - sum;\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value;\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\ta.sort((x, y) => x - y);\r\n\r\n\t\tlet sum = 0;\r\n\t\tfor (let i = 0; i < n - 1; i++) sum += a[i];\r\n\r\n\t\tlet ans = 0;\r\n\t\tif (sum + a[n-1]) \r\n\t\t\tans = 1 + Math.max(a[n-1] - sum - 1, 0);\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar map = {};\r\n\t\tvar max = 0;\r\n\t\tvar K = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tK += list[i];\r\n\t\t\tmax = Math.max(max, list[i]);\r\n\t\t}\r\n\t\tif(K == 0){\r\n\t\t\tmyout(0);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tvar output = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\toutput = Math.max(output, max - 1 - (K - list[i]));\r\n\t\t}\r\n\t\tmyout(output + 1);\r\n\t}\r\n}\r\n"}, {"source_code": "function solve() {\r\n const n = Number(read());\r\n const arr = readArray(BigInt);\r\n let maxNum = 0n;\r\n let sumNum = 0n;\r\n for (const x of arr) {\r\n sumNum += x;\r\n if (x > maxNum) {\r\n maxNum = x;\r\n }\r\n }\r\n if (sumNum === 0n) {\r\n write(0);\r\n return;\r\n }\r\n sumNum -= maxNum;\r\n if (maxNum <= sumNum + 1n) {\r\n write(1);\r\n return;\r\n }\r\n write(maxNum - sumNum);\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction pDivCount(n) {\r\n let ans = 0;\r\n let i = 1;\r\n while(n > 1) {\r\n i++;\r\n while(n % i === 0) {\r\n ans++;\r\n n = Math.floor(n / i);\r\n }\r\n }\r\n return ans;\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (a === 0) {\r\n return b;\r\n }\r\n return gcd(b % a, a);\r\n}\r\n\r\nfunction lcm(a, b) {\r\n return Math.floor(a / gcd(a, b)) * b;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n}\r\ninit();\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const testCases = readline();\n\n for (let i = 0; i < testCases; i++) {\n let size = readline();\n let arr = readline().split(\" \").map(Number);\n\n let max = -1;\n let sum = 0;\n for (let j = 0; j < arr.length; j++) {\n if (arr[j] > max) max = arr[j];\n sum += arr[j];\n }\n let sumMinusMax = sum - max;\n // console.log(sum, max);\n if (sum === 0) {\n console.log(0);\n } else if (sumMinusMax >= max) {\n console.log(1);\n } else {\n console.log(max - sumMinusMax);\n }\n }\n}\n"}, {"source_code": "\nfunction readLineNums () {\n return readline().split(' ').map(x => parseInt(x));\n}\n\n// ***** PROBLEM SOLUTION *****\n\nvar n = readLineNums();\n\nwhile (n--) {\n readLineNums();\n var passes = readLineNums();\n\n if ( !passes.some(pass => pass !== 0) ) {\n print(0);\n continue;\n }\n var max = passes.reduce((max, num) => (num > max) ? num : max, -1);\n var sum = passes.reduce((sum, num) => (num + sum), 0);\n\n var remaining = sum - max;\n\n if (remaining >= max) {\n print(1);\n } else {\n print(2 * max - sum);\n }\n}\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n arr.sort((a, b) => b - a);\r\n if (arr[0] === 0) {\r\n console.log(0);\r\n continue;\r\n }\r\n let ans = 0;\r\n for (let i = 1; i < n; i++) {\r\n let dif = Math.abs(arr[i] - arr[i - 1]);\r\n if (dif <= 0) arr[i] = 1;\r\n else arr[i] = dif;\r\n }\r\n if (arr[n - 1] <= 1) console.log(1);\r\n else console.log(arr[n - 1]);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n arr.sort((a, b) => b - a);\r\n if (arr[0] === 0) {\r\n console.log(0);\r\n continue;\r\n }\r\n let ans = 0;\r\n for (let i = 1; i < n; i++) {\r\n let dif = Math.abs(arr[i] - arr[i - 1]);\r\n if (dif <= 0) arr[i] = 0;\r\n else arr[i] = dif;\r\n }\r\n if (arr[n - 1] <= 1) console.log(1);\r\n else console.log(arr[n - 1]);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n arr.sort((a, b) => b - a);\r\n if (arr[n - 1] === 0) {\r\n console.log(0);\r\n continue;\r\n }\r\n let ans = 0;\r\n for (let i = 1; i < n; i++) {\r\n let dif = Math.abs(arr[i] - arr[i - 1]);\r\n if (dif <= 0) arr[i] = 0;\r\n else arr[i] = dif;\r\n }\r\n if (arr[n - 1] <= 1) console.log(1);\r\n else console.log(arr[n - 1]);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value;\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\ta.sort((x, y) => x - y);\r\n\r\n\t\tlet sum = 0;\r\n\t\tfor (let i = 0; i < n - 1; i++) sum += a[i];\r\n\r\n\t\tlet ans = 0;\r\n\t\tif (sum) \r\n\t\t\tans = 1 + Math.max(a[n-1] - sum - 1, 0);\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "98d9c44e460e141f062fcd6c345a4a1d"} {"nl": {"description": "Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.", "input_spec": "The first line contains an integer n (1 ≤ n ≤ 100) — the number of leaves Alyona has found. The next n lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.", "output_spec": "Output the single number — the number of Alyona's leaves.", "sample_inputs": ["5\nbirch yellow\nmaple red\nbirch yellow\nmaple yellow\nmaple green", "3\noak yellow\noak yellow\noak yellow"], "sample_outputs": ["4", "1"], "notes": null}, "positive_code": [{"source_code": "var readline=require('readline');\nvar rl=readline.createInterface(process.stdin,process.stdout);\nvar n=-1;\nvar checker=0;\nvar mySet=new Set();\nrl.on('line', lineInput => {\n if(n==-1){\n n=parseInt(lineInput);\n }\n else{\n mySet.add(lineInput);\n checker++;\n if(checker==n){\n console.log(mySet.size);\n rl.close();\n }\n }\n\n});\n\n\n\n/* inputs.push(lineInput);\nconst n=parseInt(lineInput);\nfor(let i=0; i [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = RTI((u, p) => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n const inside = () => {\r\n let res = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n res.push([v, u]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n return res;\r\n };\r\n const after = () => {\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n if (p !== -1) low[p] = Math.min(low[p], low[u]);\r\n };\r\n return [inside, after];\r\n });\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i, -1);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\nfunction RTI(fn) {\r\n let res;\r\n const createNode = args => {\r\n return {\r\n args,\r\n result: [],\r\n curIndex: 0\r\n };\r\n };\r\n const dfs = (...args) => {\r\n const root = createNode([args]);\r\n root.cb = result => res = result;\r\n const callStack = [root];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (curCall && curCall.args.length === curCall.curIndex) {\r\n var _curCall$cb, _curCall;\r\n const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall) curCall.result[curCall.curIndex++] = res;\r\n }\r\n if (!curCall) break;\r\n const {\r\n args,\r\n curIndex\r\n } = curCall;\r\n {\r\n const res = fn(...args[curIndex]);\r\n const [inside, after] = res;\r\n let nextCall = inside();\r\n const node = createNode(nextCall);\r\n node.cb = after;\r\n callStack.push(node);\r\n }\r\n }\r\n return res;\r\n };\r\n return dfs;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = RTI((u, p) => {\r\n const before = () => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n };\r\n const inside = () => {\r\n let res = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n res.push([v, u]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n return res;\r\n };\r\n const after = () => {\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n if (p !== -1) low[p] = Math.min(low[p], low[u]);\r\n };\r\n return [before, inside, after];\r\n });\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i, -1);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\nfunction RTI(fn) {\r\n const done = () => {};\r\n const dfs = (...args) => {\r\n const callStack = [[done, args]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {\r\n var _curCall;\r\n const after = curCall.pop();\r\n after();\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall && curCall.length > 1) curCall.pop();\r\n }\r\n if (!curCall) break;\r\n const args = curCall[curCall.length - 1];\r\n const [before, inside, after] = fn(...args);\r\n before();\r\n let nextCall = inside();\r\n callStack.push([after, ...nextCall]);\r\n }\r\n };\r\n return dfs;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nasync function solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = async () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = RTI((u, p) => {\r\n const before = () => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n };\r\n const inside = () => {\r\n let res = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n res.push([v, u]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n return res;\r\n };\r\n const after = () => {\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n if (p !== -1) low[p] = Math.min(low[p], low[u]);\r\n };\r\n return [before, inside, after];\r\n });\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i, -1);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\nfunction RTI(fn) {\r\n const done = () => {};\r\n const dfs = (...args) => {\r\n const callStack = [[done, args]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {\r\n var _curCall;\r\n const after = curCall.pop();\r\n after();\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall && curCall.length > 1) curCall.pop();\r\n }\r\n if (!curCall) break;\r\n const args = curCall[curCall.length - 1];\r\n const [before, inside, after] = fn(...args);\r\n before();\r\n let nextCall = inside();\r\n callStack.push([after, ...nextCall]);\r\n }\r\n };\r\n return dfs;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(await solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = RTI((u, p) => {\r\n const before = () => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n };\r\n const inside = () => {\r\n let res = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n res.push([v, u]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n return res;\r\n };\r\n const after = () => {\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n if (p !== -1) low[p] = Math.min(low[p], low[u]);\r\n };\r\n return [before, inside, after];\r\n });\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i, -1);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\nfunction RTI(fn) {\r\n const done = () => {};\r\n const dfs = (...args) => {\r\n const callStack = [[done, args]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {\r\n var _curCall;\r\n const after = curCall.pop();\r\n after();\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall && curCall.length > 1) curCall.pop();\r\n }\r\n if (!curCall) break;\r\n const args = curCall[curCall.length - 1];\r\n const [before, inside, after] = fn(...args);\r\n before();\r\n let nextCall = inside(...args);\r\n callStack.push([after, ...nextCall]);\r\n }\r\n };\r\n return dfs;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map(),\r\n fa = [];\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n const callStack = [[u]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {\r\n var _curCall;\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (!curCall) continue;\r\n const v = curCall.pop();\r\n if (dfn[v] === low[v]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === v) break;\r\n }\r\n idx++;\r\n }\r\n const u = fa[v];\r\n low[u] = Math.min(low[u], low[v]);\r\n }\r\n if (!curCall) break;\r\n const u = curCall[curCall.length - 1];\r\n if (!dfn[u]) {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n let nextCall = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n fa[v] = u;\r\n nextCall.push(v);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n callStack.push(nextCall);\r\n continue;\r\n } else if (set.has(u)) {\r\n const f = fa[u];\r\n low[f] = Math.min(low[f], dfn[u]);\r\n }\r\n curCall.pop();\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n let ans = '';\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n ans += calc(T)+'\\n';\n } else\n pcalc();\n process.stdout.write(ans)\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n\nconst MOD = 1e9+7;\nconst calc = ()=>{\n // READING:\n let [n] = ra();\n let A = ra();\n let B = ra();\n let C = ra();\n LT({n, A, B});\n // PROCESSING:\n let posA = new Array(n+1).fill(-1);\n let posB = new Array(n+1).fill(-1);\n for (let i=0; i {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const sa = lines[l++].trim().split(' ').map(Number)\n const sb = lines[l++].trim().split(' ').map(Number)\n const sc = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, sa, sb, sc)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, sa, sb, sc) {\n const r = {}\n sa.forEach((x, i) => {\n r[x] = i\n })\n //\n const v = {}\n let ans = 1\n for (let i = 0; i < n; i++) {\n if (v[sa[i]]) continue\n v[sa[i]] = 1\n\n let j = i\n let f = 0\n let k = 1\n while (!v[sb[j]]) {\n // v[sa[j]] = 1\n v[sb[j]] = 1\n k++\n if (sc[j]) f = 1\n //\n j = r[sb[j]]\n // console.log('j', j)\n }\n if (sc[j]) f = 1\n // console.log(k)\n if (!f) {\n ans = mul(ans, k === 1 ? 1 : 2)\n }\n }\n // console.log('-')\n return ans\n}\n\nconst MOD = 1e9 + 7\nconst MOD_CUT = ((1 << 20) * (1 << 20)) % MOD\nfunction add(a, b) {\n return (a + b) % MOD\n}\nfunction minus(a, b) {\n return add(add(a, -b), MOD)\n}\nfunction mul(a, b) {\n let r = (a >> 20) * (b >> 20) * MOD_CUT\n + (a & 0xfff00000) * (b & 0xfffff)\n + (a & 0xfffff) * b\n return r % MOD\n}\nfunction pow(a, b) {\n let r = 1\n let base = a\n while (b) {\n if (b & 1) {\n r = mul(r, base)\n }\n b >>= 1\n base = mul(base, base)\n }\n return r\n}\n"}, {"source_code": "let inputs = '';\nprocess.stdin.on('data', c => inputs += c);\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = inputs.split(EOL);\n\n let T = parseInt(lines[0]);\n for (let i = 0; i < T; i++) {\n main1(lines.slice(i * 4 + 1, (i + 1) * 4 + 1));\n }\n});\n\nfunction main1(lines) {\n const N = lines[0];\n const A = lines[1].split(' ').map(u => parseInt(u));\n const B = lines[2].split(' ').map(u => parseInt(u));\n const C = lines[3].split(' ').map(u => parseInt(u));\n\n const arrow = {};\n for (let i = 0; i < N; i++) {\n arrow[A[i]] = B[i];\n }\n\n const cSet = {};\n for (let i = 0; i < N; i++) {\n cSet[C[i]] = true;\n }\n\n const taken = new Array(N + 1);\n for (let i = 0; i <= N; i++) {\n taken[i] = false;\n }\n\n const cycles = [];\n for (let i = 1; i <= N; i++) {\n if (!taken[i]) {\n const cycle = [];\n let j = i;\n while (!taken[j]) {\n taken[j] = 1;\n cycle.push(j);\n j = arrow[j];\n }\n\n cycles.push(cycle);\n }\n }\n\n let ans = 1;\n let MODD = 1000000007;\n for (const cycle of cycles) {\n let ok = true;\n for (const u of cycle) {\n if (cSet[u]) {\n ok = false;\n break;\n }\n }\n\n if (ok && cycle.length > 1) {\n ans = (ans * 2) % MODD;\n }\n }\n\n console.log(ans);\n}"}], "negative_code": [{"source_code": "\r\nconst {\r\n Worker, isMainThread, parentPort, workerData\r\n} = require('worker_threads');\r\n\r\nfunction parseJSAsync(script, workerData) {\r\n return new Promise((resolve, reject) => {\r\n const worker = new Worker(script, { eval: true, workerData });\r\n worker.on('message', resolve);\r\n worker.on('error', reject);\r\n worker.on('exit', (code) => {\r\n if (code !== 0)\r\n reject(new Error(`Worker stopped with exit code ${code}`));\r\n });\r\n });\r\n};\r\n\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n\r\n await parseJSAsync(`\r\n const {\r\n Worker, isMainThread, parentPort, workerData\r\n } = require('worker_threads');\r\nlet MaximumCallStateSize=0\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n MaximumCallStateSize++\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n dfs(v);\r\n low[u] = Math.min(low[u], low[v]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n MaximumCallStateSize=0\r\n if (!dfn[i] && g[i].size) dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nfunction main(read) {\r\n try {\r\n let t = Number(read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(read());\r\n const a = read().split(' ').map(Number);\r\n const b = read().split(' ').map(Number);\r\n const d = read().split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\\\n'));\r\n } catch (error) {\r\n console.log('error',MaximumCallStateSize,error)\r\n }\r\n}\r\n\r\n\r\nvoid function () {\r\n const inputs = workerData;\r\n let i = 0;\r\n function read() {\r\n return inputs[i++];\r\n }\r\n main(read);\r\n}();\r\n\r\n `, inputs)\r\n}();\r\n"}, {"source_code": "\r\nconst {\r\n Worker, isMainThread, parentPort, workerData\r\n} = require('worker_threads');\r\n\r\nfunction parseJSAsync(script, workerData) {\r\n return new Promise((resolve, reject) => {\r\n const worker = new Worker(script, { eval: true, workerData });\r\n worker.on('message', resolve);\r\n worker.on('error', reject);\r\n worker.on('exit', (code) => {\r\n if (code !== 0)\r\n reject(new Error(`Worker stopped with exit code ${code}`));\r\n });\r\n });\r\n};\r\n\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n\r\n await parseJSAsync(`\r\n const {\r\n Worker, isMainThread, parentPort, workerData\r\n } = require('worker_threads');\r\n\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n dfs(v);\r\n low[u] = Math.min(low[u], low[v]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nfunction main(read) {\r\n try {\r\n let t = Number(read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(read());\r\n const a = read().split(' ').map(Number);\r\n const b = read().split(' ').map(Number);\r\n const d = read().split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\\\n'));\r\n } catch (error) {\r\n console.log('error',error)\r\n }\r\n}\r\n\r\n\r\nvoid function () {\r\n const inputs = workerData;\r\n let i = 0;\r\n function read() {\r\n return inputs[i++];\r\n }\r\n main(read);\r\n}();\r\n\r\n `, inputs)\r\n}();\r\n"}, {"source_code": "\r\nconst {\r\n Worker, isMainThread, parentPort, workerData\r\n} = require('worker_threads');\r\n\r\nfunction parseJSAsync(script, workerData) {\r\n return new Promise((resolve, reject) => {\r\n const worker = new Worker(script, { eval: true, workerData });\r\n worker.on('message', resolve);\r\n worker.on('error', reject);\r\n worker.on('exit', (code) => {\r\n if (code !== 0)\r\n reject(new Error(`Worker stopped with exit code ${code}`));\r\n });\r\n });\r\n};\r\n\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n\r\n await parseJSAsync(`\r\n const {\r\n Worker, isMainThread, parentPort, workerData\r\n } = require('worker_threads');\r\n\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n dfs(v);\r\n low[u] = Math.min(low[u], low[v]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nfunction main(read) {\r\n let t = Number(read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(read());\r\n const a = read().split(' ').map(Number);\r\n const b = read().split(' ').map(Number);\r\n const d = read().split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\\\n'));\r\n}\r\n\r\n\r\nvoid function () {\r\n const inputs = workerData;\r\n let i = 0;\r\n function read() {\r\n return inputs[i++];\r\n }\r\n main(read);\r\n}();\r\n\r\n `, inputs)\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nasync function solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = async () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = async u => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n await dfs(v);\r\n low[u] = Math.min(low[u], low[v]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) await dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(await solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nasync function solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = async () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = async u => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n dfs(v);\r\n low[u] = Math.min(low[u], low[v]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) await dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(await solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map();\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n dfs(v);\r\n low[u] = Math.min(low[u], low[v]);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n if (dfn[u] === low[u]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === u) break;\r\n }\r\n idx++;\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b, d) {\r\n const MOD = BigInt(10 ** 9 + 7);\r\n const set = new Set();\r\n {\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => [0, 0]);\r\n for (let i = 0; i < n; i++) {\r\n g[a[i]][0] = i;\r\n g[b[i]][1] = i;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] !== 0) {\r\n const queue = [a[i], b[i]];\r\n for (let j of queue) {\r\n set.add(j);\r\n for (let k of [b[g[j][0]], a[g[j][1]]]) {\r\n if (set.has(k)) continue;\r\n queue.push(k);\r\n }\r\n }\r\n } else if (a[i] === b[i]) {\r\n set.add(a[i]);\r\n }\r\n }\r\n }\r\n const g = Array.from({\r\n length: n + 1\r\n }, () => new Set());\r\n for (let i = 0; i < n; i++) {\r\n if (d[i] === 0) {\r\n const u = a[i],\r\n v = b[i];\r\n if (set.has(u) || set.has(v)) continue;\r\n g[u].add(v);\r\n g[v].add(u);\r\n }\r\n }\r\n console.log(g);\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map(),\r\n fa = [];\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n const callStack = [[u]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {\r\n var _curCall;\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (!curCall) continue;\r\n const v = curCall.pop();\r\n if (dfn[v] === low[v]) {\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === v) break;\r\n }\r\n idx++;\r\n }\r\n const u = fa[v];\r\n low[u] = Math.min(low[u], low[v]);\r\n }\r\n if (!curCall) break;\r\n const u = curCall[curCall.length - 1];\r\n if (!dfn[u]) {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n let nextCall = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n fa[v] = u;\r\n nextCall.push(v);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n callStack.push(nextCall);\r\n continue;\r\n } else if (set.has(u)) {\r\n const f = fa[u];\r\n low[f] = Math.min(low[f], dfn[u]);\r\n }\r\n curCall.pop();\r\n }\r\n };\r\n for (let i = 1; i <= n; i++) {\r\n if (!dfn[i] && g[i].size) dfs(i);\r\n }\r\n return BigInt(2) ** BigInt(idx) % MOD;\r\n };\r\n return tarjan();\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n const d = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b, d));\r\n }\r\n console.log(res.map(num => num.toString()).join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const sa = lines[l++].trim().split(' ').map(Number)\n const sb = lines[l++].trim().split(' ').map(Number)\n const sc = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, sa, sb, sc)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, sa, sb, sc) {\n const r = {}\n sa.forEach((x, i) => {\n r[x] = i\n })\n //\n const v = {}\n let ans = 1\n for (let i = 0; i < n; i++) {\n if (v[sa[i]]) continue\n v[sa[i]] = 1\n\n let j = i\n let f = 0\n let k = 1\n while (!v[sb[j]]) {\n // v[sa[j]] = 1\n v[sb[j]] = 1\n k++\n if (sc[j]) f = 1\n //\n j = r[sb[j]]\n // console.log('j', j)\n }\n // console.log(k)\n if (!f) {\n ans = mul(ans, k === 1 ? 1 : 2)\n }\n }\n return ans\n}\n\nconst MOD = 1e9 + 7\nconst MOD_CUT = ((1 << 20) * (1 << 20)) % MOD\nfunction add(a, b) {\n return (a + b) % MOD\n}\nfunction minus(a, b) {\n return add(add(a, -b), MOD)\n}\nfunction mul(a, b) {\n let r = (a >> 20) * (b >> 20) * MOD_CUT\n + (a & 0xfff00000) * (b & 0xfffff)\n + (a & 0xfffff) * b\n return r % MOD\n}\nfunction pow(a, b) {\n let r = 1\n let base = a\n while (b) {\n if (b & 1) {\n r = mul(r, base)\n }\n b >>= 1\n base = mul(base, base)\n }\n return r\n}\n"}], "src_uid": "15823d23340c845e0c257974390cb69f"} {"nl": {"description": "Let's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty).You may perform the following operations until both a and s are empty: Take the first element of a, push it into s and remove it from a (if a is not empty); Take the top element from s, append it to the end of array b and remove it from s (if s is not empty). You can perform these operations in arbitrary order.If there exists a way to perform the operations such that array b is sorted in non-descending order in the end, then array a is called stack-sortable.For example, [3, 1, 2] is stack-sortable, because b will be sorted if we perform the following operations: Remove 3 from a and push it into s; Remove 1 from a and push it into s; Remove 1 from s and append it to the end of b; Remove 2 from a and push it into s; Remove 2 from s and append it to the end of b; Remove 3 from s and append it to the end of b. After all these operations b = [1, 2, 3], so [3, 1, 2] is stack-sortable. [2, 3, 1] is not stack-sortable.You are given k first elements of some permutation p of size n (recall that a permutation of size n is an array of size n where each integer from 1 to n occurs exactly once). You have to restore the remaining n - k elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that p is lexicographically maximal (an array q is lexicographically greater than an array p iff there exists some integer k such that for every i < k qi = pi, and qk > pk). You may not swap or change any of first k elements of the permutation.Print the lexicographically maximal permutation p you can obtain.If there exists no answer then output -1.", "input_spec": "The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k < n) — the size of a desired permutation, and the number of elements you are given, respectively. The second line contains k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the first k elements of p. These integers are pairwise distinct.", "output_spec": "If it is possible to restore a stack-sortable permutation p of size n such that the first k elements of p are equal to elements given in the input, print lexicographically maximal such permutation. Otherwise print -1.", "sample_inputs": ["5 3\n3 2 1", "5 3\n2 3 1", "5 1\n3", "5 2\n3 4"], "sample_outputs": ["3 2 1 5 4", "-1", "3 2 1 5 4", "-1"], "notes": null}, "positive_code": [{"source_code": "var Segment = function Segment(start, end) {\n this.start = start;\n this.end = end;\n};\n\nvar main = function main() {\n var input = readline()\n .split(\" \")\n .map(function (i) {\n return Number(i);\n });\n\n var N = input[0];\n var K = input[1];\n\n var nums = readline()\n .split(\" \")\n .map(function (i) {\n return Number(i);\n });\n\n var stack = [];\n\n for (var i = 0; i < K; i++) {\n var currSegment = stack.pop() || new Segment(1, N);\n\n if (nums[i] < currSegment.start || nums[i] > currSegment.end) {\n return -1;\n }\n\n if (nums[i] < currSegment.end) {\n stack.push(new Segment(nums[i] + 1, currSegment.end));\n }\n\n if (nums[i] > currSegment.start) {\n stack.push(new Segment(currSegment.start, nums[i] - 1));\n }\n }\n\n while (stack.length) {\n var currSegment = stack.pop();\n\n for (var i = currSegment.end; i >= currSegment.start; i--) {\n nums.push(i);\n }\n }\n\n return nums.join(\" \");\n};\n\nprint(main());"}], "negative_code": [{"source_code": "var Segment = function Segment(start, end) {\n this.start = start;\n this.end = end;\n};\n\nvar main = function main() {\n var input = readline()\n .split(\" \")\n .map(function (i) {\n return Number(i);\n });\n var N = input[0];\n var K = input[1];\n var nums = readline()\n .split(\" \")\n .map(function (i) {\n return Number(i);\n });\n var stack = [new Segment(nums[0] + 1, N), new Segment(1, nums[0] - 1)];\n\n for (var i = 1; i < K; i++) {\n var currSegment = stack.pop();\n\n if (nums[i] < currSegment.start || nums[i] > currSegment.end) {\n return -1;\n }\n\n if (nums[i] < currSegment.end) {\n stack.push(new Segment(nums[i] + 1, currSegment.end));\n }\n\n if (nums[i] > currSegment.start) {\n stack.push(new Segment(currSegment.start, nums[i] - 1));\n }\n }\n\n while (stack.length) {\n var currSegment = stack.pop();\n\n for (var i = currSegment.end; i >= currSegment.start; i--) {\n nums.push(i);\n }\n }\n\n return nums.join(\" \");\n};\n\nprint(main());"}, {"source_code": "var Segment = function Segment(start, end) {\n this.start = start;\n this.end = end;\n};\n\nvar main = function main() {\n var input = readline()\n .split(\" \")\n .map(function (i) {\n return Number(i);\n });\n var N = input[0];\n var K = input[1];\n var nums = readline()\n .split(\" \")\n .map(function (i) {\n return Number(i);\n });\n var stack = [new Segment(nums[0] + 1, N), new Segment(1, nums[0] - 1)];\n\n for (var i = 1; i < K; i++) {\n var currSegment = stack.pop();\n\n if (nums[i] < currSegment.start || nums[i] > currSegment.end) {\n return -1;\n }\n\n if (nums[i] < currSegment.end) {\n stack.push(new Segment(nums[i] + 1, currSegment.end));\n }\n\n if (nums[i] > currSegment.start) {\n stack.push(new Segment(currSegment.start, nums[i] - 1));\n }\n }\n\n while (stack.length) {\n var currSegment = stack.pop();\n\n for (var i = currSegment.start; i <= currSegment.end; i++) {\n nums.push(i);\n }\n }\n\n return nums.join(\" \");\n};\n\nprint(main());\n"}], "src_uid": "848e81bc0aeaec7dbe3ec8e68d7b07ef"} {"nl": {"description": "It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $$$a$$$. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices $$$x, y, z, w$$$ such that $$$a_x + a_y = a_z + a_w$$$.Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery?", "input_spec": "The first line contains the single integer $$$n$$$ ($$$4 \\leq n \\leq 200\\,000$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 2.5 \\cdot 10^6$$$).", "output_spec": "Print \"YES\" if there are such four indices, and \"NO\" otherwise. If such indices exist, print these indices $$$x$$$, $$$y$$$, $$$z$$$ and $$$w$$$ ($$$1 \\le x, y, z, w \\le n$$$). If there are multiple answers, print any of them.", "sample_inputs": ["6\n2 1 5 2 7 4", "5\n1 3 1 9 20"], "sample_outputs": ["YES\n2 3 1 6", "NO"], "notes": "NoteIn the first example $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Note that there are other answer, for example, 2 3 4 6.In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3$$$"}, "positive_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n // const x = readline();\r\n //\r\n // Array(parseInt(x)).fill(1).map((t, iii) => {\r\n var n = parseInt(readline())\r\n\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n var map = {}\r\n var sum = 0\r\n var x = 0\r\n var y = 0\r\n for (let i = 0; i < n; i++) {\r\n for (let j = i + 1; j < n; j++) {\r\n sum = a[i] + a[j]\r\n if (!map[sum]) map[sum] = `${i}:${j}`\r\n else {\r\n [x, y] = map[sum].split(':').map(x => parseInt(x))\r\n if (x !== i && x !== j && y !== i && y !== j) {\r\n console.log('YES')\r\n console.log(i + 1, j + 1, x + 1, y + 1)\r\n return\r\n }\r\n }\r\n }\r\n }\r\n console.log('NO')\r\n\r\n\r\n // if(n>=1) ans-=a[n-1]\r\n // console.log(a)\r\n\r\n // })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "704297bc97528ec27cce5f9388019e29"} {"nl": {"description": "Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word \"helllo\" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words \"helloo\" and \"wwaatt\" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.", "input_spec": "The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.", "output_spec": "Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.", "sample_inputs": ["helloo", "woooooow"], "sample_outputs": ["hello", "woow"], "notes": "NoteThe second valid answer to the test from the statement is \"heloo\"."}, "positive_code": [{"source_code": "var s = readline()\ns = s.replace(/(.)\\1+/g, '$1$1');\ns = s.replace(/(.)\\1(.)\\2/g, '$1$1$2');\nprint(s);"}, {"source_code": "var s = readline()\ns = s.replace(/(.)\\1+/g, '$1$1');\ns = s.replace(/(.)\\1(.)\\2/g, '$1$1$2');\nprint(s);"}, {"source_code": "print(readline().replace(/(\\w)(?=(\\1{2,}))\\2/g, \"$1$1\").replace(/((\\w)(?=(\\2))\\3)((\\w)(?=(\\5))\\6)/g,\"$2$2$5\"));"}], "negative_code": [{"source_code": "print(readline().replace(/(.)\\1+/g, '$1$1').replace(/^(.)\\1+/, '$1').replace(/(.)\\1+$/, '$1'));"}], "src_uid": "31d803d886c47fe681bdcfbe6c74f090"} {"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$$$) — 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$$$) — 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": "\r\nvar t=+ readline();\r\nwhile(t--){\r\n var input= readline();\r\n var arr= input.split(\" \").map(x=>+x);\r\n var r=arr[0];\r\n var b=arr[1];\r\n var d=arr[2];\r\n if(r>b){\r\n var temp=r;\r\n r=b;\r\n b=temp;\r\n }\r\n var res=r*(d+1);\r\n if(res>=b)print(\"YES\")\r\n else print(\"NO\");\r\n}"}, {"source_code": "const readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nfunction candyShop(inp){\r\n let parsedInput = inp.split(' ')\r\n .map(el=>Number( el)); // el.replace(/[^0-9]/g, '') \r\n if( parsedInput.length === 1 ) return null\r\n\r\n let [redAmount, blueAmount, maxDif] = [...parsedInput];\r\n if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';\r\n\r\n let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)],\r\n minDif = Math.ceil(max / min)-1;\r\n\r\n if(minDif > maxDif) return 'no'\r\n return 'yes'\r\n}\r\n\r\nrl.on('line', (input) => {\r\n let i = candyShop(input);\r\n if(i != null ){ console.log(i) }\r\n});"}, {"source_code": "const readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nfunction candyShop(inp){\r\n let parsedInput = inp.split(' ')\r\n .map(el=>Number( el)); // el.replace(/[^0-9]/g, '') \r\n if( parsedInput.length === 1 ) return null\r\n\r\n let [redAmount, blueAmount, maxDif] = [...parsedInput];\r\n // if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';\r\n\r\n let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)],\r\n minDif = Math.ceil(max / min)-1;\r\n\r\n if(minDif > maxDif) return 'no'\r\n return 'yes'\r\n}\r\n\r\nrl.on('line', (input) => {\r\n let i = candyShop(input);\r\n if(i != null ){ console.log(i) }\r\n});"}, {"source_code": "const readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nfunction candyShop(inp){\r\n let parsedInput = inp.split(' ')\r\n .map( el => Number( el.replace(/[^0-9]/g, '') ) ); // el.replace(/[^0-9]/g, '') \r\n if( parsedInput.length === 1 ) return null\r\n\r\n let [redAmount, blueAmount, maxDif] = [...parsedInput];\r\n if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';\r\n\r\n let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)],\r\n minDif = Math.ceil(max / min)-1;\r\n\r\n if(minDif > maxDif) return 'no'\r\n return 'yes'\r\n}\r\n\r\nrl.on('line', (input) => {\r\n let i = candyShop(input);\r\n if(i != null ){ console.log(i) }\r\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); \n for(j = 1; j <= lines[0]; j ++){\n var l = lines[j].split(' ')\n var r = l[0]\n var b = l[1]\n var d = l[2]\n if(Math.abs(r - b) <= d*(Math.min(r, b))){\n console.log('YES')\n }else{\n console.log('NO')\n }\n }\n});\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); \n var n = lines[0];\n for(var j = 1; j <= n; j++){\n var l = lines[j].split(' ');\n var r = l[0];\n var b = l[1];\n var d = l[2];\n if(Math.abs(r - b) <= d * Math.min(r, b)){\n console.log('YES');\n }else{\n console.log('NO');\n }\n }\n});\n"}, {"source_code": "/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\nvar __webpack_exports__ = {};\n\n;// CONCATENATED MODULE: ./src/io.js\nvar interact = function interact(main) {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n var inputString = '';\n var currentLine = 0;\n\n var readline = function readline() {\n return inputString[currentLine++];\n };\n\n var print = function print() {\n for (var _len = arguments.length, any = new Array(_len), _key = 0; _key < _len; _key++) {\n any[_key] = arguments[_key];\n }\n\n process.stdout.write(any.join(' '));\n };\n\n var println = function println() {\n for (var _len2 = arguments.length, any = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n any[_key2] = arguments[_key2];\n }\n\n any.length > 0 && print(any);\n print('\\n');\n };\n\n var obj = {\n print: print,\n println: println,\n readline: readline\n };\n process.stdin.on('data', function (inputStdin) {\n inputString += inputStdin;\n });\n process.stdin.on('end', function () {\n inputString = inputString.trim().split('\\n').map(function (string) {\n return string.trim();\n });\n main(obj);\n });\n};\n\n/* harmony default export */ const io = (interact);\n;// CONCATENATED MODULE: ./src/index.js\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _iterableToArrayLimit(arr, i) { if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\n\n\nvar main = function main(io) {\n var tc = Number.parseInt(io.readline());\n\n while (tc--) {\n var _io$readline$split$ma = io.readline().split(' ').map(function (x) {\n return Number.parseInt(x);\n }),\n _io$readline$split$ma2 = _slicedToArray(_io$readline$split$ma, 3),\n r = _io$readline$split$ma2[0],\n b = _io$readline$split$ma2[1],\n d = _io$readline$split$ma2[2];\n\n if (r > b) {\n var temp = r;\n r = b;\n b = temp;\n } // assert r <= b\n\n\n var sat = b <= r * (1 + d);\n io.println(sat ? 'YES' : 'NO');\n }\n};\n\nio(main);\n/******/ })()\n;"}, {"source_code": "\r\n'use-strict'\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n \r\nlet data = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n \r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n \r\n let testCases = parseInt(readLine());\r\n \r\n while(testCases--)\r\n {\r\n const [r,b,d] = get_ints();\r\n (Math.min(r,b) * (d + 1)) >= Math.max(r,b) ? print('YES') : print('NO')\r\n \r\n }\r\n});\r\n \r\nfunction print(c){\r\n return console.log(c);\r\n}\r\n \r\nfunction get_ints() { \r\n return readLine().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet currentLine = 0;\r\nlet inputString = \"\";\r\n\r\nprocess.stdin.on(\"data\", (raw_data) => {\r\n inputString += raw_data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((line) => {\r\n return line.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n/******** Main function *************/\r\n\r\nfunction main() {\r\n const t = +input();\r\n\r\n for (var i = 0; i < t; i++) {\r\n const [r, b, d] = input().split(\" \").map(Number);\r\n\r\n const min = Math.min(r, b);\r\n const max = Math.max(r, b);\r\n\r\n const y = Math.ceil(max / min);\r\n\r\n if (d === 0) {\r\n if (r === b) {\r\n console.log(\"YES\");\r\n } else {\r\n console.log(\"NO\");\r\n }\r\n } else if (Math.abs(y - 1) > d) {\r\n console.log(\"NO\");\r\n } else {\r\n console.log(\"YES\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); \n var n = lines[0];\n for(var j = 1; j <= n; j++){\n var l = lines[j].split(' ');\n var r = l[0];\n var b = l[1];\n var d = l[2];\n if(Math.abs(r - b) <= d*Math.min(r, b)){\n console.log('YES');\n }else{\n console.log('NO');\n }\n }\n});"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction main() {\r\n const test= readline();\r\n \r\n for(let i=0;i=Math.max(r[0],r[1])?\"Yes\":\"No\" ;\r\n return result;\r\n }\r\n \r\n "}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar R = nextInt();\r\n\t\tvar B = nextInt();\r\n\t\tvar D = nextInt();\r\n\t\tif(R > B){\r\n\t\t\tvar tmp = R;\r\n\t\t\tR = B;\r\n\t\t\tB = tmp;\r\n\t\t}\r\n\t\tvar diff = B - R;\r\n\t\tvar single = Math.ceil(diff / R);\r\n\t\tif(single <= D){\r\n\t\t\tmyout(\"YES\");\r\n\t\t}else{\r\n\t\t\tmyout(\"NO\");\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ 747:\n/***/ ((module) => {\n\nmodule.exports = require(\"fs\");;\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tvar cachedModule = __webpack_module_cache__[moduleId];\n/******/ \t\tif (cachedModule !== undefined) {\n/******/ \t\t\treturn cachedModule.exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/compat get default export */\n/******/ \t(() => {\n/******/ \t\t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t\t__webpack_require__.n = (module) => {\n/******/ \t\t\tvar getter = module && module.__esModule ?\n/******/ \t\t\t\t() => (module['default']) :\n/******/ \t\t\t\t() => (module);\n/******/ \t\t\t__webpack_require__.d(getter, { a: getter });\n/******/ \t\t\treturn getter;\n/******/ \t\t};\n/******/ \t})();\n/******/ \t\n/******/ \t/* webpack/runtime/define property getters */\n/******/ \t(() => {\n/******/ \t\t// define getter functions for harmony exports\n/******/ \t\t__webpack_require__.d = (exports, definition) => {\n/******/ \t\t\tfor(var key in definition) {\n/******/ \t\t\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n/******/ \t\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n/******/ \t\t\t\t}\n/******/ \t\t\t}\n/******/ \t\t};\n/******/ \t})();\n/******/ \t\n/******/ \t/* webpack/runtime/hasOwnProperty shorthand */\n/******/ \t(() => {\n/******/ \t\t__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))\n/******/ \t})();\n/******/ \t\n/************************************************************************/\nvar __webpack_exports__ = {};\n// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.\n(() => {\n\n// EXTERNAL MODULE: external \"fs\"\nvar external_fs_ = __webpack_require__(747);\nvar external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);\n;// CONCATENATED MODULE: external \"readline\"\nconst external_readline_namespaceObject = require(\"readline\");;\n;// CONCATENATED MODULE: ./src/lib/io.ts\n\n\nclass InteractiveIO {\n constructor() {\n this.rl = void 0;\n this.lines = [];\n this.rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n this.rl.on('line', line => {\n this.lines.push(line);\n });\n }\n\n nextLine() {\n return new Promise((resolve, reject) => {\n if (this.lines.length) {\n resolve(this.lines.shift());\n return;\n }\n\n let waitId = null;\n let timeoutId = null;\n waitId = setInterval(() => {\n if (this.lines.length) {\n resolve(this.lines.shift());\n clearTimeout(timeoutId);\n clearInterval(waitId);\n return;\n }\n }, 1);\n timeoutId = setTimeout(() => {\n clearInterval(waitId);\n reject(new Error('timeout')); // resolve(null);\n }, 500);\n });\n }\n\n close() {\n this.rl.close();\n }\n\n}\nclass IO {\n constructor() {\n this.i = 0;\n this.text = '';\n this.out = '';\n this.readInput();\n }\n\n readInput() {\n this.text = __webpack_require__(747).readFileSync(0, 'utf8');\n }\n\n nextToken() {\n let ret = '';\n\n while (this.text[this.i].charCodeAt(0) <= 32) {\n this.i++;\n }\n\n while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {\n ret += this.text[this.i];\n this.i++;\n }\n\n return ret;\n }\n\n nextNum() {\n return Number(this.nextToken());\n }\n\n nextBigInt() {\n return BigInt(this.nextToken());\n }\n\n nextNumArray(n) {\n let ret = [];\n\n while (n--) {\n ret.push(this.nextNum());\n }\n\n return ret;\n }\n\n _write(x) {\n this.out += x;\n }\n\n write(x) {\n this._write(x + ' ');\n }\n\n writeLine(x) {\n this._write(x + '\\n');\n }\n\n flush() {\n external_fs_default().writeFileSync(1, this.out);\n this.out = '';\n }\n\n}\n;// CONCATENATED MODULE: ./src/cf-1519/1519-a.ts\n\nconst io = new IO();\n\nfunction solve(r, b, d) {\n let min = Math.min(r, b);\n let max = Math.max(r, b);\n let rem = max - min;\n\n if (rem <= min * d) {\n io.writeLine('YES');\n } else {\n io.writeLine('NO');\n }\n}\n\nfunction main() {\n try {\n let t = io.nextNum();\n\n while (t--) {\n let r = io.nextNum();\n let b = io.nextNum();\n let d = io.nextNum();\n solve(r, b, d);\n }\n\n io.flush();\n } catch (e) {\n console.log(e.stack);\n }\n}\n\nmain();\n\n})();\n\n/******/ })()\n;"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve([a, b, d]) {\r\n const s = Math.min(a, b);\r\n (Math.abs(a - b) / s <= d) ? console.log('YES') : console.log('NO')\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])\r\n}"}], "negative_code": [{"source_code": "const readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nfunction candyShop(inp){\r\n let parsedInput = inp.split(' ')\r\n .map( el => Number( el.replace(/[^0-9]/g, '') ) );\r\n\r\n if( parsedInput.length === 1 ) return null\r\n\r\n let [redAmount, blueAmount, maxDif] = [...parsedInput];\r\n if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';\r\n let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)];\r\n if( Math.floor(max/min) <= maxDif ){ return 'yes'}\r\n else return 'no'\r\n}\r\n\r\nrl.on('line', (input) => {\r\n let i = candyShop(input);\r\n if(i != null ){ console.log(i) }\r\n});\r\n"}, {"source_code": "const readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nfunction candyShop(inp){\r\n let parsedInput = inp.split(' ')\r\n .map( el => Number( el.replace(/[^0-9]/g, '') ) );\r\n\r\n if( parsedInput.length === 1 ) return 'no'\r\n\r\n let [redAmount, blueAmount, maxDif] = [...parsedInput];\r\n if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';\r\n let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)];\r\n if( Math.floor(max/min) <= maxDif ){ return 'yes'}\r\n else return 'no'\r\n}\r\n\r\nrl.on('line', (input) => {\r\n console.log( candyShop(input) )\r\n});\r\n"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nfunction candyShop(redAmount, blueAmount, maxDif){\r\n if(maxDif===0) return redAmount===blueAmount ? console.log('yes') : console.log('no');\r\n if(Math.abs(redAmount-blueAmount)>maxDif) return console.log('no');\r\n if(redAmount<1 || blueAmount<1) return console.log('no');\r\n return console.log('yes')\r\n}\r\n \r\nrl.on('line', (input) => {\r\n if(input.length>1){ candyShop(input) }\r\n});"}, {"source_code": "/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\nvar __webpack_exports__ = {};\n\n;// CONCATENATED MODULE: ./src/io.js\nvar interact = function interact(main) {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n var inputString = '';\n var currentLine = 0;\n\n var readline = function readline() {\n return inputString[currentLine++];\n };\n\n var print = function print() {\n for (var _len = arguments.length, any = new Array(_len), _key = 0; _key < _len; _key++) {\n any[_key] = arguments[_key];\n }\n\n process.stdout.write(any.join(' '));\n };\n\n var println = function println() {\n for (var _len2 = arguments.length, any = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n any[_key2] = arguments[_key2];\n }\n\n any.length > 0 && print(any);\n print('\\n');\n };\n\n var obj = {\n print: print,\n println: println,\n readline: readline\n };\n process.stdin.on('data', function (inputStdin) {\n inputString += inputStdin;\n });\n process.stdin.on('end', function () {\n inputString = inputString.trim().split('\\n').map(function (string) {\n return string.trim();\n });\n main(obj);\n });\n};\n\n/* harmony default export */ const io = (interact);\n;// CONCATENATED MODULE: ./src/index.js\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _iterableToArrayLimit(arr, i) { if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\n\n\nvar main = function main(io) {\n var tc = Number.parseInt(io.readline());\n\n while (tc--) {\n var _io$readline$split$ma = io.readline().split(' ').map(function (x) {\n return Number.parseInt(x);\n }),\n _io$readline$split$ma2 = _slicedToArray(_io$readline$split$ma, 3),\n r = _io$readline$split$ma2[0],\n b = _io$readline$split$ma2[1],\n d = _io$readline$split$ma2[2];\n\n if (r > d) {\n var temp = r;\n r = b;\n b = temp;\n } // assert r <= b\n\n\n var sat = b <= r * (1 + d);\n io.println(sat ? 'YES' : 'NO');\n }\n};\n\nio(main);\n/******/ })()\n;"}, {"source_code": "\r\n'use-strict'\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n \r\nlet data = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n \r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n \r\n let testCases = parseInt(readLine());\r\n \r\n while(testCases--)\r\n {\r\n const [r,b,d] = get_ints();\r\n \r\n if(r === b)\r\n {\r\n print('YES');\r\n continue;\r\n }\r\n const min = Math.min(r,b);\r\n const max = Math.max(r,b);\r\n Math.ceil(max/min) > d ? print('NO') : print('YES')\r\n \r\n }\r\n});\r\n \r\nfunction print(c){\r\n return console.log(c);\r\n}\r\n \r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet currentLine = 0;\r\nlet inputString = \"\";\r\n\r\nprocess.stdin.on(\"data\", (raw_data) => {\r\n inputString += raw_data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((line) => {\r\n return line.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n/******** Main function *************/\r\n\r\nfunction main() {\r\n const t = +input();\r\n\r\n for (var i = 0; i < t; i++) {\r\n const [r, b, d] = input().split(\" \").map(Number);\r\n\r\n const min = Math.min(r, b);\r\n const max = Math.max(r, b);\r\n\r\n const x = Math.floor(max / min);\r\n const y = Math.ceil(max / min);\r\n\r\n if (d === 0) {\r\n if (r === b) {\r\n console.log(\"YES\");\r\n } else {\r\n console.log(\"NO\");\r\n }\r\n } else if (d === 1) {\r\n if (Math.abs(max - min) > d) {\r\n console.log(\"NO\");\r\n } else {\r\n console.log(\"YES\");\r\n }\r\n } else if (min === 1) {\r\n if (max > d) {\r\n console.log(\"NO\");\r\n } else {\r\n console.log(\"YES\");\r\n }\r\n } else {\r\n if (Math.abs(x - y) > d) {\r\n console.log(\"NO\");\r\n } else {\r\n console.log(\"YES\");\r\n }\r\n }\r\n }\r\n}\r\n"}], "src_uid": "c0ad2a6d14b0c9e09af2221d88a34d52"} {"nl": {"description": "There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $$$b$$$ buns, $$$p$$$ beef patties and $$$f$$$ chicken cutlets in your restaurant. You can sell one hamburger for $$$h$$$ dollars and one chicken burger for $$$c$$$ dollars. Calculate the maximum profit you can achieve.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) – the number of queries. The first line of each query contains three integers $$$b$$$, $$$p$$$ and $$$f$$$ ($$$1 \\le b, ~p, ~f \\le 100$$$) — the number of buns, beef patties and chicken cutlets in your restaurant. The second line of each query contains two integers $$$h$$$ and $$$c$$$ ($$$1 \\le h, ~c \\le 100$$$) — the hamburger and chicken burger prices in your restaurant.", "output_spec": "For each query print one integer — the maximum profit you can achieve.", "sample_inputs": ["3\n15 2 3\n5 10\n7 5 2\n10 12\n1 100 100\n100 100"], "sample_outputs": ["40\n34\n0"], "notes": "NoteIn first query you have to sell two hamburgers and three chicken burgers. Your income is $$$2 \\cdot 5 + 3 \\cdot 10 = 40$$$.In second query you have to ell one hamburgers and two chicken burgers. Your income is $$$1 \\cdot 10 + 2 \\cdot 12 = 34$$$.In third query you can not create any type of burgers because because you have only one bun. So your income is zero."}, "positive_code": [{"source_code": "var queries = readline();\nfor(var i = 0; i < queries; i++){\n var quantities = readline().split(' ');\n var b = parseInt(quantities[0]);\n var p = parseInt(quantities[1]);\n var f = parseInt(quantities[2]);\n\n var prices = readline().split(' ');\n var h = parseInt(prices[0]);\n var c = parseInt(prices[1]);\n\n var possibleBurgers = ~~(b / 2);\n //print(\"Burgers possible: \" + possibleBurgers);\n\n if(h <= c){\n //print(\"Value of h and c: \" + h + c);\n if(f >= possibleBurgers){\n print(possibleBurgers * c);\n }\n else{\n var h_bur_profit;\n var c_bur_profit = f * c;\n var remaining_possible_burgers = possibleBurgers - f;\n if(p <= remaining_possible_burgers){\n h_bur_profit = p * h;\n }\n else{\n h_bur_profit = remaining_possible_burgers * h;\n }\n print(h_bur_profit + c_bur_profit);\n }\n }\n else if(h > c){\n //print(\"Value of p and possible burgers: \" + p + possibleBurgers);\n if(p >= possibleBurgers){\n print(possibleBurgers * h);\n }\n else{\n var h_bur_profit = p * h;\n var c_bur_profit;\n var remaining_possible_burgers = possibleBurgers - p;\n if(f <= remaining_possible_burgers){\n c_bur_profit = f * c;\n }\n else{\n c_bur_profit = remaining_possible_burgers * c;\n }\n print(h_bur_profit + c_bur_profit);\n }\n }\n else{\n print(\"0\");\n }\n}"}, {"source_code": "(function() {\nvar INPUT = ``;\nvar OUTPUT = ``;\n \nvar main = function() {\"use strict\";\n // TODO\n var t = rdN();\n while (t --> 0) {\n var input = rdArN();\n var b = input[0];\n var p = input[1];\n var f = input[2];\n var input = rdArN();\n var h = input[0];\n var c = input[1];\n \n if (h < c) {\n var buf = p;\n p = f;\n f = buf;\n var buf = h;\n h = c;\n c = buf;\n }\n var stack = crAr(p, h).concat(crAr(f, c)).reverse();\n var res = 0;\n while (b >= 2 && stack.length) {\n res += stack.pop();\n b -= 2;\n }\n pr(res);\n }\n};\n \nif(INPUT){INPUT=INPUT.split('\\n').reverse();\nreadline=()=>INPUT.pop();\nwrite=(...s)=>{OUTPUT+=[...s].join(' ')};\nprint=(...s)=>{write(...s);OUTPUT+='\\n'};}\nconst\nrdS=readline,\nrdN=()=>+rdS(),\nrdArS=()=>rdS().split(' '),\nrdArN=()=>rdArS().map(v=>+v),\nwr=write,\npr=print,\nprAr=(a)=>pr(...a),\nprOb=(o)=>pr(JSON.stringify(o,null,4)),\ncrAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},\ngetPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},\ndefineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});\ndefineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});\ndefineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});\n \nmain();\nreturn OUTPUT;\n})();"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet count = 0;\nlet b, p, f;\nlet h, c;\n\nconst solve = () => {\n let ans = 0;\n const arr1 = new Array(p).fill(h);\n const arr2 = new Array(f).fill(c);\n\n for (let i = 1; i < b; i += 2) {\n if (h >= c) {\n ans += arr1.length ? arr1.pop() : arr2.pop() || 0;\n }\n else {\n ans += arr2.length ? arr2.pop() : arr1.pop() || 0;\n }\n }\n\n console.log(ans);\n}\n\nrl.on('line', (d) => {\n if (count === 0) {\n count++;\n return;\n }\n\n if (count % 2 === 1) {\n [b, p, f] = d.split(' ').map(Number);\n }\n else {\n [h, c] = d.split(' ').map(Number);\n\n solve();\n }\n\n count++;\n});\n"}, {"source_code": "'use strict';\n\nlet inputStr = '';\nlet lines = [];\n\n\nprocess.stdin.on('data', line => {\n inputStr += line;\n});\n\nprocess.stdin.on('end', () => {\n lines = inputStr.split('\\n');\n lines.pop();\n main();\n});\n\nfunction main() {\n let b,p,f,h,c;\n for (let i = 1; i < lines.length; i += 2) {\n let curr = lines[i].split(' ');\n let total = 0;\n b = Math.floor(parseInt(curr[0], 10) / 2);\n p = parseInt(curr[1], 10);\n f = parseInt(curr[2], 10);\n curr = lines[i+1].split(' ');\n h = parseInt(curr[0], 10);\n c = parseInt(curr[1], 10);\n\n if (h > c) {\n while (b > 0 && p-- > 0) {\n total += h;\n b--;\n }\n while (b > 0 && f-- > 0) {\n total += c;\n b--;\n }\n } else {\n while (b > 0 && f-- > 0) {\n total += c;\n b--;\n }\n while (b > 0 && p-- > 0) {\n total += h;\n b--;\n }\n }\n\n console.log(total);\n }\n}\n"}], "negative_code": [{"source_code": "var queries = readline();\nfor(var i = 0; i < queries; i++){\n var quantities = readline().split(' ');\n var b = quantities[0];\n var p = quantities[1];\n var f = quantities[2];\n\n var prices = readline().split(' ');\n var h = prices[0];\n var c = prices[1];\n\n var possibleBurgers = ~~(b / 2);\n //print(\"Burgers possible: \" + possibleBurgers);\n\n if(possibleBurgers != 0 && h < c){\n if(f >= possibleBurgers){\n print(possibleBurgers * c);\n }\n else{\n var h_bur_profit;\n var c_bur_profit = f * c;\n var remaining_possible_burgers = possibleBurgers - f;\n if(p <= remaining_possible_burgers){\n h_bur_profit = p * h;\n }\n else{\n h_bur_profit = remaining_possible_burgers * h;\n }\n print(h_bur_profit + c_bur_profit);\n }\n }\n else if(possibleBurgers != 0 && h > c){\n if(p >= possibleBurgers){\n print(possibleBurgers * h);\n }\n else{\n var h_bur_profit = p * h;\n var c_bur_profit;\n var remaining_possible_burgers = possibleBurgers - p;\n if(f <= remaining_possible_burgers){\n c_bur_profit = f * c;\n }\n else{\n c_bur_profit = remaining_possible_burgers * c;\n }\n print(h_bur_profit + c_bur_profit);\n }\n }\n else{\n print(\"0\");\n }\n}"}], "src_uid": "92bf30e66f4d5ddebb697d2fa4fa0689"} {"nl": {"description": " William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.A valid nested list is any list which can be created from a list with one item \"1\" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items $$$a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\,\\cdots\\, \\,.\\,a_k$$$ and can be one of two types: Add an item $$$a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\cdots \\,.\\, a_k \\,.\\, 1$$$ (starting a list of a deeper level), or Add an item $$$a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\cdots \\,.\\, (a_k + 1)$$$ (continuing the current level). Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the \"Notes\" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the \"Ctrl-S\" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.William wants you to help him restore a fitting original nested list.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^3$$$), which is the number of lines in the list. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$1 \\le a_i \\le n$$$), which is what remains of William's nested list. It is guaranteed that in each test case at least one fitting list exists. It is guaranteed that the sum of values $$$n$$$ across all test cases does not exceed $$$10^3$$$.", "output_spec": "For each test case output $$$n$$$ lines which represent a valid nested list, which could become the data provided to you by William. If there are multiple answers, print any.", "sample_inputs": ["2\n4\n1\n1\n2\n3\n9\n1\n1\n1\n2\n2\n1\n2\n1\n2"], "sample_outputs": ["1\n1.1\n1.2\n1.3\n1\n1.1\n1.1.1\n1.1.2\n1.2\n1.2.1\n2\n2.1\n2.2"], "notes": "NoteIn the second example test case one example of a fitting list is:11.1 1.1.11.1.21.21.2.122.12.2This list can be produced by using the sequence of operations shown below: Original list with a single item $$$1$$$. Insert item $$$2$$$ by using the insertion operation of the second type after item $$$1$$$. Insert item $$$1.1$$$ by using the insertion operation of the first type after item $$$1$$$. Insert item $$$1.2$$$ by using the insertion operation of the second type after item $$$1.1$$$. Insert item $$$1.1.1$$$ by using the insertion operation of the first type after item $$$1.1$$$. Insert item $$$1.1.2$$$ by using the insertion operation of the second type after item $$$1.1.1$$$. Insert item $$$1.2.1$$$ by using the insertion operation of the first type after item $$$1.2$$$. Insert item $$$2.1$$$ by using the insertion operation of the first type after item $$$2$$$. Insert item $$$2.2$$$ by using the insertion operation of the second type after item $$$2.1$$$. "}, "positive_code": [{"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction findAllStr(json, map, mapRev, index) {\r\n mapRev[index] = json;\r\n if (Array.isArray(json)) {\r\n for (var i = typeof json[0] === 'string' ? 1 : 0; i < json.length; i++) {\r\n findAllStr(json[i], map, mapRev, index + '_' + i);\r\n }\r\n return;\r\n }\r\n if (json && typeof json === 'string') {\r\n if (map[json]) {\r\n map[json].push(index);\r\n } else {\r\n map[json] = [index];\r\n }\r\n }\r\n return;\r\n}\r\n\r\nfunction solve() {\r\n var n = Number(read());\r\n var ans = [[1]];\r\n read();\r\n for (var i = 1; i < n; i++) {\r\n var a = Number(read());\r\n ans[i] = ans[i - 1].slice();\r\n if (a === 1) {\r\n ans[i].push(1);\r\n continue; \r\n }\r\n var b = ans[i].pop();\r\n while(b + 1 !== a) {\r\n b = ans[i].pop();\r\n }\r\n ans[i].push(a);\r\n }\r\n write(ans.map((str) => str.join('.')).join('\\n'));\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst a = rn();\r\n\r\n\t\t\tif (a == 1) {\r\n\t\t\t\tans.push(1);\r\n\t\t\t} else {\r\n\t\t\t\twhile (ans[ans.length-1] != a-1) ans.pop();\r\n\t\t\t\tans[ans.length-1] += 1;\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(ans.join('.'));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction findAllStr(json, map, mapRev, index) {\r\n mapRev[index] = json;\r\n if (Array.isArray(json)) {\r\n for (var i = typeof json[0] === 'string' ? 1 : 0; i < json.length; i++) {\r\n findAllStr(json[i], map, mapRev, index + '_' + i);\r\n }\r\n return;\r\n }\r\n if (json && typeof json === 'string') {\r\n if (map[json]) {\r\n map[json].push(index);\r\n } else {\r\n map[json] = [index];\r\n }\r\n }\r\n return;\r\n}\r\n\r\nfunction addToStore(store, address, value) {\r\n if (!store[address]) {\r\n store[address] = [];\r\n }\r\n store[address].push(value);\r\n}\r\n\r\nfunction getFromStore(store, address) {\r\n return store[address].pop();\r\n}\r\n\r\nfunction solve() {\r\n var n = Number(read());\r\n var ans = [[1]];\r\n var store = [];\r\n addToStore(store, 2, 0);\r\n read();\r\n for (var i = 1; i < n; i++) {\r\n var a = Number(read());\r\n if (a === 1) {\r\n ans[i] = ans[i - 1].slice();\r\n ans[i].push(1);\r\n addToStore(store, 2, i);\r\n continue; \r\n }\r\n var j = getFromStore(store, a);\r\n ans[i] = ans[j].slice();\r\n ans[i][ans[i].length - 1] = a;\r\n addToStore(store, a + 1, i);\r\n }\r\n write(ans.map((str) => str.join('.')).join('\\n'));\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction findAllStr(json, map, mapRev, index) {\r\n mapRev[index] = json;\r\n if (Array.isArray(json)) {\r\n for (var i = typeof json[0] === 'string' ? 1 : 0; i < json.length; i++) {\r\n findAllStr(json[i], map, mapRev, index + '_' + i);\r\n }\r\n return;\r\n }\r\n if (json && typeof json === 'string') {\r\n if (map[json]) {\r\n map[json].push(index);\r\n } else {\r\n map[json] = [index];\r\n }\r\n }\r\n return;\r\n}\r\n\r\nfunction solve() {\r\n var n = Number(read());\r\n var ans = '0'.repeat(n).split('');\r\n ans[0] = [1];\r\n read();\r\n for (var i = 1; i < n; i++) {\r\n var a = Number(read());\r\n if (a === 1) {\r\n ans[i] = ans[i - 1].slice();\r\n ans[i].push(1);\r\n continue; \r\n }\r\n var j = i - 1;\r\n while (ans[j][ans[j].length - 1] + 1 !== a) {\r\n j--;\r\n }\r\n ans[i] = ans[j].slice();\r\n ans[i][ans[i].length - 1] ++;\r\n }\r\n write(ans.map((str) => str.join('.')).join('\\n'));\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}], "src_uid": "c1bf6c8a9a20f377cf2a5dbea2267c88"} {"nl": {"description": "The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, \"101101\" is a palindrome, while \"0101\" is not.Alice and Bob are playing a game on a string $$$s$$$ (which is initially a palindrome in this version) of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations: Choose any $$$i$$$ ($$$1 \\le i \\le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, \"01001\" becomes \"10010\" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^3$$$). The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of the characters '0' and '1'. It is guaranteed that the string $$$s$$$ is a palindrome and contains at least one '0'. Note that there is no limit on the sum of $$$n$$$ over test cases.", "output_spec": "For each test case print a single word in a new line: \"ALICE\", if Alice will win the game, \"BOB\", if Bob will win the game, \"DRAW\", if the game ends in a draw. ", "sample_inputs": ["2\n4\n1001\n1\n0"], "sample_outputs": ["BOB\nBOB"], "notes": "NoteIn the first test case of the example, in the $$$1$$$-st move Alice has to perform the $$$1$$$-st operation, since the string is currently a palindrome. in the $$$2$$$-nd move Bob reverses the string. in the $$$3$$$-rd move Alice again has to perform the $$$1$$$-st operation. All characters of the string are '1', game over. Alice spends $$$2$$$ dollars while Bob spends $$$0$$$ dollars. Hence, Bob always wins."}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n console.log(\"BOB\");\r\n continue;\r\n }\r\n let cnt = 0;\r\n for (let i = 0; i < n; i++) if (str[i] === \"0\") cnt++;\r\n if(cnt===1) console.log(\"BOB\");\r\n else if (cnt % 2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "var readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n console.log(solve(lines[l++]));\n }\n});\n\nfunction solve(str) {\n const mid = Math.ceil(str.length / 2)\n\n let zero = 0\n for (let i = mid - 1; i >= 0; i--) {\n if (str[i] === '0') zero++\n }\n if ((str.length & 1) && str[mid - 1] === '0') {\n // alice change the middle 0 first\n // then convert to 0x0\n return zero === 1 ? 'BOB' : 'ALICE'\n }\n // 00x00 -> 10x00 -> 10x01, same with 0x0\n return 'BOB'\n}\n"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n// 05/20/21 afternoon\r\n\r\nconst solve = (n, s) => {\r\n let cnt = 0;\r\n for (const c of s) cnt += (c == '0');\r\n // pr(cnt);\r\n if (n & 1 && s[n >>> 1] == '0' && cnt > 1) {\r\n pr(\"ALICE\")\r\n } else {\r\n pr(\"BOB\");\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line);\r\n });\r\n rl.on('close', () => {\r\n let t = Number(input[0]);\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "\r\nconst palindromeDist = (line) => {\r\n\tlet count = 0;\r\n\tfor (let i=0; i<(line.length/2); i++) {\r\n\t\tif (line[i] !== line[line.length-1-i]) {\r\n\t\t\tcount++;\r\n\t\t}\r\n\t}\r\n\r\n\treturn count;\r\n}\r\n\r\nconst solve = (line) => {\r\n\tconst emptyCells = line.split('')\r\n\t\t.reduce((acc, item) => (acc += (item === '0' ? 1 : 0)), 0);\r\n\r\n\tif (emptyCells === 1) {\r\n\t\treturn 'BOB';\r\n\t}\r\n\r\n\tconst canDoPalindrome = line.length%2 === 1 && line[Math.floor(line.length/2)] === '0';\r\n\r\n\treturn canDoPalindrome ? 'ALICE' : 'BOB';\r\n}\r\n\r\nlet input = '';\r\nprocess.stdin.on('data', str => input += str)\r\nprocess.stdin.on('end', () => {\r\n\tconst [n, ...lines] = input.trim().split('\\n')\r\n\t\t.map(l => l.trim());\r\n\r\n\tfor (let i=0; i {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n console.log(\"BOB\");\r\n continue;\r\n }\r\n let cnt = 0;\r\n for (let i = 0; i < n; i++) if (str[i] === \"0\") cnt++;\r\n if (cnt % 2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) console.log(\"BOB\");\r\n let cnt = 0;\r\n for (let i = 0; i < n; i++) if (str[i] === \"0\") cnt++;\r\n if (cnt % 2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n if (str[0] === \"0\") console.log(\"BOB\");\r\n else console.log(\"DRAW\");\r\n continue;\r\n }\r\n let flag = true;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] !== str[n - 1 - i]) {\r\n flag = false;\r\n break;\r\n }\r\n }\r\n let cnt = 0,\r\n cnt1 = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] === \"0\") cnt++;\r\n }\r\n let i = 0,\r\n j = n - 1;\r\n while (i <= j) {\r\n if (str[i] !== str[j]) cnt1++;\r\n i++;\r\n j--;\r\n }\r\n if (cnt === 0) {\r\n console.log(\"DRAW\");\r\n } else if (cnt1 === 0) {\r\n if (cnt % 2) {\r\n console.log(\"ALICE\");\r\n } else console.log(\"BOB\");\r\n } else {\r\n let p2 = cnt1;\r\n cnt -= cnt1;\r\n if (cnt === 0) console.log(\"DRAW\");\r\n else {\r\n if (cnt % 2 === 0) {\r\n p1 += Math.floor(n / 2);\r\n p2 += Math.floor(n / 2);\r\n } else {\r\n if (cnt === 1) p1 = 1;\r\n else if (cnt === 3) {\r\n p1 = 1;\r\n p2 += 2;\r\n } else {\r\n p2 += Math.floor(n / 2);\r\n p1 += cnt - Math.floor(n / 2);\r\n }\r\n }\r\n if (p1 === p2) console.log(\"DRAW\");\r\n if (p1 < p2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n if (str[0] === \"0\") console.log(\"BOB\");\r\n else console.log(\"DRAW\");\r\n continue;\r\n }\r\n let flag = true;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] !== str[n - 1 - i]) {\r\n flag = false;\r\n break;\r\n }\r\n }\r\n let cnt = 0,\r\n cnt1 = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] === \"0\") cnt++;\r\n }\r\n let i = 0,\r\n j = n - 1;\r\n while (i <= j) {\r\n if (str[i] !== str[j]) cnt1++;\r\n i++;\r\n j--;\r\n }\r\n if (cnt === 0) {\r\n console.log(\"DRAW\");\r\n } else if (cnt1 === 0) {\r\n if (cnt % 2) {\r\n if (cnt === 3) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n } else console.log(\"BOB\");\r\n } else {\r\n let p2 = cnt1;\r\n cnt -= cnt1;\r\n if (cnt === 0) console.log(\"DRAW\");\r\n else {\r\n if (cnt % 2 === 0) {\r\n p1 += Math.floor(n / 2);\r\n p2 += Math.floor(n / 2);\r\n } else {\r\n if (cnt === 1) p1 = 1;\r\n else if (cnt === 3) {\r\n p1 = 1;\r\n p2 += 2;\r\n } else {\r\n p2 += Math.floor(n / 2);\r\n p1 += cnt - Math.floor(n / 2);\r\n }\r\n }\r\n if (p1 === p2) console.log(\"DRAW\");\r\n if (p1 < p2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n if (str[0] === \"0\") console.log(\"BOB\");\r\n else console.log(\"DRAW\");\r\n continue;\r\n }\r\n let flag = true;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] !== str[n - 1 - i]) {\r\n flag = false;\r\n break;\r\n }\r\n }\r\n let cnt = 0,\r\n cnt1 = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] === \"0\") cnt++;\r\n }\r\n let i = 0,\r\n j = n - 1;\r\n while (i <= j) {\r\n if (str[i] !== str[j]) cnt1++;\r\n i++;\r\n j--;\r\n }\r\n if (cnt === 0) {\r\n console.log(\"DRAW\");\r\n } else if (cnt1 === 0) {\r\n if (cnt % 2) {\r\n cnt = Math.floor(cnt / 2) > cnt - Math.floor(cnt / 2) ? 0 : 1;\r\n if (cnt) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n } else console.log(\"BOB\");\r\n } else {\r\n let p2 = cnt1;\r\n cnt -= cnt1;\r\n if (cnt === 0) console.log(\"DRAW\");\r\n else {\r\n if (cnt % 2 === 0) {\r\n p1 += Math.floor(n / 2);\r\n p2 += Math.floor(n / 2);\r\n } else {\r\n if (cnt === 1) p1 = 1;\r\n else if (cnt === 3) {\r\n p1 = 1;\r\n p2 += 2;\r\n } else {\r\n p2 += Math.floor(n / 2);\r\n p1 += cnt - Math.floor(n / 2);\r\n }\r\n }\r\n if (p1 === p2) console.log(\"DRAW\");\r\n if (p1 < p2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n if (str[0] === \"0\") console.log(\"BOB\");\r\n else console.log(\"DRAW\");\r\n continue;\r\n }\r\n let flag = true;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] !== str[n - 1 - i]) {\r\n flag = false;\r\n break;\r\n }\r\n }\r\n let cnt = 0,\r\n cnt1 = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] === \"0\") cnt++;\r\n }\r\n let i = 0,\r\n j = n - 1;\r\n while (i <= j) {\r\n if (str[i] !== str[j]) cnt1++;\r\n i++;\r\n j--;\r\n }\r\n if (cnt === 0) {\r\n console.log(\"DRAW\");\r\n } else if (cnt1 === 0) {\r\n if (cnt % 2) {\r\n cnt = Math.floor(cnt / 2) > cnt - Math.floor(cnt / 2) ? 0 : 1;\r\n if (cnt) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n } else console.log(\"BOB\");\r\n } else {\r\n let p2 = cnt1,\r\n p1 = 0;\r\n let r = cnt - cnt1;\r\n if (r === 2) p1 += r;\r\n else {\r\n p2 += Math.floor(r / 2);\r\n p1 += r - Math.floor(r / 2);\r\n }\r\n if (p1 === p2) console.log(\"DRAW\");\r\n else if (p1 < p2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n if (str[0] === \"0\") console.log(\"BOB\");\r\n else console.log(\"DRAW\");\r\n continue;\r\n }\r\n let flag = true;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] !== str[n - 1 - i]) {\r\n flag = false;\r\n break;\r\n }\r\n }\r\n let cnt = 0,\r\n cnt1 = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] === \"0\") cnt++;\r\n }\r\n let i = 0,\r\n j = n - 1;\r\n while (i <= j) {\r\n if (str[i] !== str[j]) cnt1++;\r\n i++;\r\n j--;\r\n }\r\n if (cnt === 0) {\r\n console.log(\"DRAW\");\r\n } else if (cnt1 === 0) {\r\n if (cnt % 2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n } else {\r\n let p2 = cnt1,\r\n p1 = 0;\r\n let r = cnt - cnt1;\r\n if (r === 2) p1 += r;\r\n else {\r\n p2 += Math.floor(r / 2);\r\n p1 += r - Math.floor(r / 2);\r\n }\r\n if (p1 === p2) console.log(\"DRAW\");\r\n else if (p1 < p2) console.log(\"ALICE\");\r\n else console.log(\"BOB\");\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let str = readline().trim();\r\n if (n === 1) {\r\n if (str[0] === \"0\") console.log(\"BOB\");\r\n else console.log(\"DRAW\");\r\n continue;\r\n }\r\n let flag = true;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] !== str[n - 1 - i]) {\r\n flag = false;\r\n break;\r\n }\r\n }\r\n if (flag) {\r\n let ans = true;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] === \"0\") {\r\n ans = false;\r\n break;\r\n }\r\n }\r\n if (ans) console.log(\"DRAW\");\r\n else console.log(\"BOB\");\r\n } else {\r\n let cnt = 0,\r\n cnt1 = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (str[i] === \"0\") cnt++;\r\n }\r\n let i = 0,\r\n j = n - 1;\r\n while (i <= j) {\r\n if (str[i] !== str[j]) cnt1++;\r\n i++;\r\n j--;\r\n }\r\n if (cnt % cnt1 === 0) console.log(\"DRAW\");\r\n else console.log(\"ALICE\");\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "var readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n console.log(solve(lines[l++]));\n }\n});\n\nfunction solve(str) {\n const mid = Math.ceil(str.length / 2)\n\n let zero = 0\n for (let i = mid - 1; i >= 0; i--) {\n if (str[i] === '0') zero++\n }\n if ((str.length & 1) && str[mid - 1] === '0') {\n // alice change the middle 0 first\n // then convert to 0x0\n return str.length === 1 ? 'BOB' : 'ALICE'\n }\n // 00x00 -> 10x00 -> 10x01, same with 0x0\n return 'BOB'\n}\n"}, {"source_code": "var readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n console.log(solve(lines[l++]));\n }\n});\n\nfunction solve(str) {\n const mid = Math.ceil(str.length / 2)\n\n let zero = 0\n for (let i = mid - 1; i >= 0; i--) {\n if (str[i] === '0') zero++\n }\n if ((str.length & 1) && str[mid - 1] === '0') {\n // alice change the middle 0 first\n // then convert to 0x0\n return 'ALICE'\n }\n // 00x00 -> 10x00 -> 10x01, same with 0x0\n return 'BOB'\n}\n"}, {"source_code": "var readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n console.log(solve(lines[l++]));\n }\n});\n\nfunction solve(str) {\n const mid = Math.ceil(str.length / 2) \n let zero = 0\n for (let i = mid - 1; i >= 0; i--) {\n if (str[i] === '0') zero++\n }\n return (zero & 1) ? 'BOB' : 'DRAW'\n}\n"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/20/21 morning\r\n * https://codeforces.com/contest/1527/problem/B1\r\n */\r\n\r\nconst solve = (n, s) => {\r\n let se = new Set();\r\n for (let i = 0; i < n; i++) {\r\n if (s[i] == '0') se.add(i);\r\n }\r\n let a = s.split(\"\");\r\n let Alice = Bob = 0;\r\n // replace '0' to '1' make s still palidrome in first priority\r\n let isP = true;\r\n let round = 1;\r\n let pre;\r\n // pr(a, se);\r\n // for (let i = 0; i <= 10; i++) {\r\n while (se.size) {\r\n if (isP == false && pre != 'rv') {\r\n // pr(\"reverse\")\r\n a.reverse();\r\n pre = 'rv';\r\n } else {\r\n let did = false;\r\n for (const i of se) {\r\n if (i == n - 1 - i || a[n - 1 - i] == '1') {\r\n a[i] = '1';\r\n did = true; // still keep palidrome\r\n // pr(\"111\")\r\n se.delete(i);\r\n break;\r\n }\r\n }\r\n // pr(did)\r\n if (!did) {\r\n let first = se.values().next().value;\r\n // pr(\"2222\", first, se)\r\n a[first] = '1';\r\n se.delete(first);\r\n isP = false;\r\n }\r\n round & 1 ? Alice++ : Bob++;\r\n pre = 'rp';\r\n }\r\n round++;\r\n // pr(\"next\", a, se, isP, pre, Alice, Bob);\r\n }\r\n // pr(Alice, Bob);\r\n if (Alice > Bob) {\r\n pr(\"BOB\");\r\n } else if (Alice < Bob) {\r\n pr(\"Alice\");\r\n } else {\r\n pr(\"DRAW\")\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line);\r\n });\r\n rl.on('close', () => {\r\n let t = Number(input[0]);\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/20/21 morning\r\n * https://codeforces.com/contest/1527/problem/B1\r\n */\r\n\r\nconst solve = (n, s) => {\r\n let se = new Set();\r\n for (let i = 0; i < n; i++) {\r\n if (s[i] == '0') se.add(i);\r\n }\r\n let a = s.split(\"\");\r\n let Alice = Bob = 0;\r\n // replace '0' to '1' make s still palidrome in first priority\r\n let isP = true;\r\n let round = 1;\r\n let pre;\r\n // pr(a, se);\r\n // for (let i = 0; i <= 10; i++) {\r\n while (se.size) {\r\n if (isP == false && pre != 'rv') {\r\n // pr(\"reverse\")\r\n a.reverse();\r\n pre = 'rv';\r\n } else {\r\n let did = false;\r\n for (const i of se) {\r\n if (a[n - 1 - i] == '1') {\r\n a[i] = '1';\r\n did = true; // still keep palidrome\r\n // pr(\"111\")\r\n se.delete(i);\r\n break;\r\n }\r\n }\r\n // pr(did)\r\n if (!did) {\r\n let first = se.values().next().value;\r\n // pr(\"2222\", first, se)\r\n a[first] = '1';\r\n se.delete(first);\r\n isP = false;\r\n }\r\n round & 1 ? Alice++ : Bob++;\r\n pre = 'rp';\r\n }\r\n round++;\r\n // pr(\"next\", a, se, isP, pre, Alice, Bob);\r\n }\r\n // pr(Alice, Bob);\r\n if (Alice > Bob) {\r\n pr(\"BOB\");\r\n } else if (Alice < Bob) {\r\n pr(\"Alice\");\r\n } else {\r\n pr(\"DRAW\")\r\n }\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line);\r\n });\r\n rl.on('close', () => {\r\n let t = Number(input[0]);\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "var e=readline();\r\nfor(var iq=0;iq {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\n\nfunction main() {\n const len = +readLine();\n const arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n let [maxLen, count, max] = [0, 0, Math.max(...arr)];\n\n for (let i = 0; i < len; i++) {\n if (arr[i] === max) {\n count++;\n } else {\n count = 0;\n }\n\n maxLen = Math.max(maxLen, count);\n }\n\n console.log(maxLen);\n}\n"}, {"source_code": "(function() {\n var read = {\n number: function() {\n return +readline();\n },\n arr: function(divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function(divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var a = read.arrNumber(' ');\n\n \n var max = a[0];\n for(var i = 1; i < n; i++) {\n if(max < a[i]) max = a[i];\n }\n \n \n var count = [1];\n var countIndex = 0;\n for(var i = 1; i < n; i++) {\n if(a[i] === max) {\n if(a[i] === a[i - 1]) {\n count[countIndex] += 1;\n }\n else {\n countIndex++;\n count[countIndex] = 1;\n }\n } \n }\n \n max = count[0];\n for(var i = 1; i < n; i++) {\n if(max < count[i]) max = count[i];\n }\n print(max);\n \n}());\n"}, {"source_code": "readline();\nvar inp = readline().split(' ').map(x => parseInt(x));\n\nvar max = Math.max(...inp);\nvar l_when_max = 0;\n\nvar indexes = [], i = -1;\nwhile ((i = inp.indexOf(max, i+1)) != -1){\n indexes.push(i);\n}\n\nfor(var j = 0 in indexes)\n{\n var k = parseInt(j);\n var l = 1;\n while(k < indexes.length - 1 && indexes[k + 1] - indexes[k] === 1)\n {\n l++;\n k++;\n }\n \n if (l > l_when_max)\n {\n l_when_max = l;\n }\n if(l_when_max > indexes.length / 2)\n {\n break;\n }\n}\n\nprint(l_when_max);"}, {"source_code": "write((readline().split(\" \").map(function(x) { return parseInt(x); })[0]*0 + readline().split(\" \").reduce(function(acc, item) { var val = parseInt(item); if (val > acc.mx) { acc.mx = val; acc.mx_cnt = 1; acc.ans = 1;} else if (val === acc.mx)\tacc.mx_cnt++; else acc.mx_cnt = 0; acc.ans = Math.max(acc.ans, acc.mx_cnt); return acc;}, {mx: -1, mx_cnt: 0, ans: 1}).ans) + \"\\n\");"}, {"source_code": "function calc(arr) {\n // find max\n var max = 0;\n for (var i = 0; i< arr.length; i++) {\n max = max > arr[i] ? max : arr[i];\n }\n \n // find max count\n var count = 0;\n var countMax = 1;\n for (var i = 0; i< arr.length; i++) {\n if (arr[i] === max) {\n count++;\n } else {\n count = 0;\n }\n \n countMax = countMax > count ? countMax : count;\n }\n \n return countMax;\n}\n\nvar n = parseInt(readline());\nvar arr = readline().split(\" \").map(el => parseInt(el));\n\nprint(calc(arr));"}, {"source_code": "var n = parseInt(readline(), 10),\n a = readline().split(' ').map(el => parseInt(el, 10)),\n max_mean = 0, \n max_len = 0,\n local_len = 0,\n local_mean = 0,\n local_sum = 0;\n\nfor(var i=0; i max_mean) {\n local_len = 1;\n local_sum = a[i];\n local_mean = local_sum / local_len;\n } else {\n local_len++;\n local_sum += a[i];\n local_mean = local_sum / local_len;\n }\n \n if(local_mean > max_mean) {\n max_mean = local_mean;\n max_len = local_len;\n \n } else if(local_mean === max_mean) {\n if(local_len > max_len) max_len = local_len;\n } else {\n local_len = 1;\n local_sum = a[i];\n local_mean = local_sum / local_len;\n \n if(local_mean > max_mean) {\n max_mean = local_mean;\n max_len = local_len;\n \n } else if(local_mean === max_mean) {\n if(local_len > max_len) max_len = local_len;\n }\n }\n}\n\nprint(max_len);"}], "negative_code": [{"source_code": "readline();\nvar inp = readline().split(' ').map(x => parseInt(x));\n\nvar max = Math.max(...inp);\nvar l_when_max = 0;\n\nvar indexes = [], i = -1;\nwhile ((i = inp.indexOf(max, i+1)) != -1){\n indexes.push(i);\n}\n\nprint(indexes);\n\nfor(var j = 0 in indexes)\n{\n var k = parseInt(j);\n var l = 1;\n while(k < indexes.length - 1 && indexes[k + 1] - indexes[k] === 1)\n {\n l++;\n k++;\n }\n \n if (l > l_when_max)\n {\n l_when_max = l;\n }\n}\n\nprint(l_when_max);"}, {"source_code": "write((readline().split(\" \").map(function(x) { return parseInt(x); })[0]*0 + readline().split(\" \").reduce(function(acc, item) { var val = parseInt(item); if (val > acc.mx) { acc.mx = val; acc.mx_cnt = 1; } else if (val === acc.mx)\tacc.mx_cnt++; else acc.mx_cnt = 0; acc.ans = Math.max(acc.ans, acc.mx_cnt); return acc;}, {mx: -1, mx_cnt: 0, ans: 1}).ans) + \"\\n\");"}], "src_uid": "5db2ae5b2c91b29e4fe4a45ab864e3f1"} {"nl": {"description": "Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \\ne j$$$; $$$1 \\leq i,j \\leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.", "input_spec": "The first line contains a single positive integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 100$$$) — the sequence $$$a$$$.", "output_spec": "For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.", "sample_inputs": ["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"], "sample_outputs": ["4\n3\n2"], "notes": "NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 < a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$."}, "positive_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nconst main = () => {\r\n let tc = parseInt(readline());\r\n while(tc--){\r\n const n = parseInt(readline());\r\n const a = readline().split(' ').map(Number);\r\n let zero = 0;\r\n for(let i = 0; i < n; i++){\r\n if(!a[i]) zero++;\r\n }\r\n if(zero){\r\n console.log(n-zero);\r\n }\r\n else{\r\n let same = false;\r\n for(let i = 0; i < n; i++){\r\n for(let j = i+1; j < n; j++){\r\n if(a[i] === a[j]) same = true;\r\n }\r\n }\r\n if(same){\r\n console.log(n);\r\n }\r\n else{\r\n console.log(n+1);\r\n }\r\n }\r\n }\r\n};"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n let arr = readline().split(' ').map(Number);\r\n\r\n let zero = arr.findIndex(x => x === 0) > -1;\r\n let nonZero = arr.filter(x => x !== 0).length;\r\n\r\n let hash = {};\r\n\r\n let duplicate = false;\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] !== 0) {\r\n if (hash[arr[i]]) {\r\n duplicate = true;\r\n } else {\r\n hash[arr[i]] = 1;\r\n }\r\n }\r\n }\r\n\r\n output((zero || duplicate) ? nonZero : nonZero + 1);\r\n }\r\n}\r\n"}, {"source_code": "let readline = require(\"readline\");\nlet rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet lines = 0;\nconst hasUniqueElements = (arr) => {\n const cache = {};\n for (let index = 0; index < arr.length; index++) {\n const element = arr[index];\n if (!cache[element]) {\n cache[element] = true;\n } else {\n return false;\n }\n }\n return true;\n};\n\nconst countAllZeros = (arr) => {\n zeros = 0;\n for (let index = 0; index < arr.length; index++) {\n const element = arr[index];\n if (element === 0) zeros++;\n }\n return zeros;\n};\n\nrl.on(\"line\", function (line) {\n if (lines !== 0 && lines % 2 === 0) {\n let input = line.split(\" \").map(Number);\n const zeros = countAllZeros(input);\n if (zeros > 0) {\n console.log(input.length - zeros);\n } else if (hasUniqueElements(input)) {\n console.log(input.length + 1);\n } else {\n console.log(input.length);\n }\n }\n lines++;\n});\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n console.log(solve());\r\n }\r\n}\r\nfunction solve() {\r\n readLine();\r\n let arr = readLine().split(\" \").map(i => parseInt(i)).sort((a, b) => a - b);\r\n let dup = false;\r\n let noofzeros = 0;\r\n let cnt = 0;\r\n if (arr[0] === 0) noofzeros = 1;\r\n for (let i = 1; i < arr.length; i++) {\r\n if ((arr[i] === arr[i - 1]) && !dup) dup = true;\r\n if (arr[i] === 0) noofzeros++;\r\n }\r\n cnt = arr.length - noofzeros;\r\n if (noofzeros == 0 && !dup) return cnt + 1;\r\n if (noofzeros == 0 && dup) return cnt;\r\n else return cnt;\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const map = {}\n let zero = 0\n let hasDup = 0\n arr.forEach(x => {\n if (!x) zero++\n if (map[x]) hasDup = 1\n map[x] = 1\n })\n if (zero) {\n return n - zero\n } else if (hasDup) {\n return n\n } else {\n return 1 + n\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar nzero = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tif(list[i] != 0){\r\n\t\t\t\tnzero++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(nzero < N){\r\n\t\t\tmyout(nzero);\r\n\t\t}else{\r\n\t\t\tvar map = getCountMap(list);\r\n\t\t\tvar key = Object.keys(map);\r\n\t\t\tif(key.length != N){\r\n\t\t\t\tmyout(nzero);\r\n\t\t\t}else{\r\n\t\t\t\tmyout(nzero + 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n let zero = 0,\r\n repeat = 0,\r\n set = new Set();\r\n for (let num of a) {\r\n if (num === 0) {\r\n zero++;\r\n } else if (set.has(num)) {\r\n repeat = 1;\r\n }\r\n set.add(num);\r\n }\r\n if (zero > 0) {\r\n return n - zero;\r\n } else if (repeat > 0) {\r\n return n;\r\n } else {\r\n return n + 1;\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\n/*---------------------------------------------------*/\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst cnk = (n, k) => {\n let res = 1;\n for (let i = 1; i <= k; i++)\n res = res * (n - k + i) / i;\n return Math.round(res + 0.01);\n}\n\nconst sumab = (a, b) => {\n let x = (b - a + 1);\n let y = a + b;\n if (x % 2 === 0) {\n x = Math.round(x / 2);\n } else {\n y = Math.round(y / 2);\n }\n return BigInt(x) * BigInt(y);\n}\n\n/*---------------------------------------------------*/\n\nconst calc = (n, a)=>{\n let zero = 0;\n let equal = false;\n\n a.sort((x, y) => x - y);\n\n let i = 0;\n while (i < n && a[i] === 0) {\n zero++;\n i++;\n }\n\n for (; i < n; i++) {\n if (i > 0 && a[i] === a[i - 1]) {\n equal = true;\n break;\n }\n }\n\n if (zero > 0) {\n return n - zero;\n } else {\n return equal ? n : n + 1;\n }\n};\n\nfunction main() {\n let T = +readline();\n // let out = [];\n for (let t = 1; t <= T; t++){\n let n = +readline();\n // let s = readline();\n let a = ra();\n // out.push(calc(n, s, a));\n process.stdout.write(`${calc(n, a)}\\n`);\n }\n // process.stdout.write(out.join('\\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"}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n \nconst calc = ()=>{\n // READING:\n let [n] = ra();\n let A = ra();\n LT({n, A});\n\n // PROCESSING:\n let ans = 0;\n let left = 0;\n let cnt = {};\n let max = 0;\n for (let i=0; i0)\n left++;\n cnt[a] = (cnt[a]||0)+1;\n max = Math.max(max, cnt[a])\n }\n if (left1){\n return n;\n }\n return n+1;\n};\n "}, {"source_code": "//import { readline, print } from '@ip-algorithmics/codeforces-io';\r\nvar t = +readline();\r\nroot: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {\r\n var i = _a[_i];\r\n var n = +readline();\r\n var a = readline().split(' ').map(function (v) { return +v; }).sort();\r\n if (a[0] === 0) {\r\n for (var j = 1; j < n; j++) {\r\n if (a[j] !== 0) {\r\n print(n - j);\r\n continue root;\r\n }\r\n }\r\n print(0);\r\n continue;\r\n }\r\n for (var i_1 = 1; i_1 < n; i_1++) {\r\n if (a[i_1] === a[i_1 - 1]) {\r\n print(n);\r\n continue root;\r\n }\r\n }\r\n print(n + 1);\r\n}\r\n"}], "negative_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet inputData = [];\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString = String(inputStdin);\r\n});\r\n\r\nprocess.stdin.on('end', () => {\r\n inputData = inputString.trim().split('\\n').map(s => s.trim());\r\n main();\r\n});\r\n\r\nconst input = (() => {\r\n let line = 0;\r\n return () => inputData[line++];\r\n})();\r\n\r\nconst main = () => {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n const n = parseInt(input());\r\n const a = input().split(' ').map(Number);\r\n let zero = 0;\r\n for(let i = 0; i < n; i++){\r\n if(!a[i]) zero++;\r\n }\r\n if(zero){\r\n console.log(n-zero);\r\n }\r\n else{\r\n let same = false;\r\n for(let i = 0; i < n; i++){\r\n for(let j = i+1; j < n; j++){\r\n if(a[i] === a[j]) same = true;\r\n }\r\n }\r\n if(same){\r\n console.log(n);\r\n }\r\n else{\r\n console.log(n+1);\r\n }\r\n }\r\n }\r\n};"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet inputData = [];\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString = String(inputStdin);\r\n});\r\n\r\nprocess.stdin.on('end', () => {\r\n inputData = inputString.trim().split('\\n').map(s => s.trim());\r\n main();\r\n});\r\n\r\nconst input = (() => {\r\n let line = 0;\r\n return () => inputData[line++];\r\n})();\r\n\r\nconst main = () => {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n const n = parseInt(input());\r\n const a = input().split(' ').map(Number);\r\n let zero = 0;\r\n for(let i = 0; i < n; i++){\r\n if(!a[i]) zero++;\r\n }\r\n if(zero){\r\n console.log(n-zero);\r\n }\r\n else{\r\n let same = false;\r\n for(let i = 0; i < n; i++){\r\n for(let j = 0; j < n; j++){\r\n if(i === j) continue;\r\n if(a[i] === a[j]) same = true;\r\n }\r\n }\r\n if(same){\r\n console.log(n);\r\n }\r\n else{\r\n console.log(n+1);\r\n }\r\n }\r\n }\r\n};"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet inputData = [];\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString = String(inputStdin);\r\n});\r\n\r\nprocess.stdin.on('end', () => {\r\n inputData = inputString.trim().split('\\n').map(s => s.trim());\r\n main();\r\n});\r\n\r\nconst input = (() => {\r\n let line = 0;\r\n return () => inputData[line++];\r\n})();\r\n\r\nconst main = () => {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n let n = parseInt(input());\r\n const a = input().split(' ').map(Number);\r\n let zero = 0;\r\n for(let i = 0; i < n; i++){\r\n if(!a[i]) zero++;\r\n }\r\n if(zero){\r\n console.log(n-zero);\r\n }\r\n else{\r\n let same = false;\r\n for(let i = 0; i < n-1; i++){\r\n if(a[i] === a[i+1]) same = true;\r\n }\r\n if(same){\r\n console.log(n);\r\n }\r\n else{\r\n console.log(n+1);\r\n }\r\n }\r\n }\r\n};"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n readline();\r\n let arr = readline().split(' ').map(Number).filter(a => a !== 0);\r\n\r\n const freq = {};\r\n let equalPairs = 0;\r\n\r\n for (let i = 0; i < arr.length; i++) {\r\n if (freq[arr[i]]) {\r\n freq[arr[i]]++;\r\n if (freq[arr[i]] % 2 === 0) {\r\n freq[arr[i]] = 0;\r\n equalPairs++;\r\n }\r\n } else {\r\n freq[arr[i]] = 1;\r\n }\r\n }\r\n\r\n const remainingPairs = Math.ceil((arr.length - equalPairs * 2) / 2);\r\n\r\n output(equalPairs + remainingPairs * 2);\r\n }\r\n}"}, {"source_code": "let readline = require(\"readline\");\nlet rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet lines = 0;\nconst hasUniqueElements = (arr) => {\n const cache = {};\n for (let index = 0; index < arr.length; index++) {\n const element = arr[index];\n if (!cache[element]) {\n cache[element] = true;\n } else {\n return false;\n }\n }\n return true;\n};\n\nrl.on(\"line\", function (line) {\n if (lines !== 0 && lines % 2 === 0) {\n let input = line.split(\" \").map(Number);\n if (input.indexOf(0) !== -1) {\n console.log(input.length - 1);\n } else if (hasUniqueElements(input)) {\n console.log(input.length + 1);\n } else {\n console.log(input.length);\n }\n }\n lines++;\n});\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n console.log(solve());\r\n }\r\n}\r\nfunction solve() {\r\n readLine();\r\n let arr = readLine().split(\" \").map(i => parseInt(i));\r\n let hasZero = false;\r\n let dup = false;\r\n for (let i = 1; i < arr.length; i++) {\r\n if ((arr[i] === arr[i - 1]) && !dup) dup = true;\r\n if ((arr[i] == 0 || arr[i - 1] == 0) && !hasZero) hasZero = true;\r\n }\r\n if (hasZero) return arr.length - 1;\r\n else if (dup) return arr.length;\r\n else return arr.length + 1;\r\n}\r\n"}, {"source_code": "//import { readline, print } from '@ip-algorithmics/codeforces-io';\r\nvar t = +readline();\r\nroot: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {\r\n var i = _a[_i];\r\n var n = +readline();\r\n var a = readline().split(' ').map(function (v) { return +v; }).sort();\r\n if (a[0] === 0) {\r\n print(n - 1);\r\n continue;\r\n }\r\n for (var i_1 = 1; i_1 < n; i_1++) {\r\n if (a[i_1] === a[i_1 - 1]) {\r\n print(n);\r\n continue root;\r\n }\r\n }\r\n print(n + 1);\r\n}\r\n"}], "src_uid": "ad242f98f1c8eb8d30789ec672fc95a0"} {"nl": {"description": "You are given a string $$$s$$$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string \"abddea\", you should get the string \"aeddba\". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 200\\,000$$$) — the length of $$$s$$$. The second line contains $$$s$$$ — a string consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "Print one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string.", "sample_inputs": ["5\naaaza", "6\ncbaabc", "9\nicpcsguru"], "sample_outputs": ["2", "0", "30"], "notes": "NoteIn the first example, you have to swap the third and the fourth elements, so the string becomes \"aazaa\". Then you have to swap the second and the third elements, so the string becomes \"azaaa\". So, it is possible to reverse the string in two swaps.Since the string in the second example is a palindrome, you don't have to do anything to reverse it."}, "positive_code": [{"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i - a] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n a = a || 0;\n b = b || (this.length - 1);\n let prev = a;\n for (let i = a; i <= b; i++) {\n if (i == b || fn(this[i], this[i + 1], i, this)) {\n arr.push(this.slice(prev, i + 1));\n prev = i + 1;\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nfunction inv(b, m) {\n for (var a = m, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + m) % m;\n}\n\n// let MOD = 1e9 + 7\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n// alpha = \"abcdefghijklmnopqrstuvwxyz\"\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nasync function main() {\n let inp = input.split(/\\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math,\n bi = BigInt, rand = n => Math.random() * n | 0;\n\n let n = +$(), s = [...$()], sr = [...s].reverse(), a = Arr(n, i => 0)\n let m = {}, id = {}\n let alpha = [...\"abcdefghijklmnopqrstuvwxyz\"];\n alpha.forEach(c => {\n m[c] = [];\n id[c] = 0;\n })\n For(n, i => {\n m[sr[i]].push(i)\n })\n // log(m)\n For(n, i => {\n a[i] = m[s[i]][id[s[i]]++]\n })\n // log(a)\n let res = 0;\n let bit = Arr(n + 1, i => 0)\n let set = i => {\n for (; i <= n; i += i & -i) bit[i]++;\n }\n let cal = i => {\n let ans = 0;\n for (; i; i -= i & -i) ans += bit[i];\n return ans;\n }\n ForR(n, i => {\n res += cal(a[i]);\n set(a[i] + 1)\n })\n log(res)\n}\n"}], "negative_code": [], "src_uid": "c1f50da1fbe797e7c9b982583a3b02d5"} {"nl": {"description": "You are given $$$k$$$ sequences of integers. The length of the $$$i$$$-th sequence equals to $$$n_i$$$.You have to choose exactly two sequences $$$i$$$ and $$$j$$$ ($$$i \\ne j$$$) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence $$$i$$$ (its length will be equal to $$$n_i - 1$$$) equals to the sum of the changed sequence $$$j$$$ (its length will be equal to $$$n_j - 1$$$).Note that it's required to remove exactly one element in each of the two chosen sequences.Assume that the sum of the empty (of the length equals $$$0$$$) sequence is $$$0$$$.", "input_spec": "The first line contains an integer $$$k$$$ ($$$2 \\le k \\le 2 \\cdot 10^5$$$) — the number of sequences. Then $$$k$$$ pairs of lines follow, each pair containing a sequence. The first line in the $$$i$$$-th pair contains one integer $$$n_i$$$ ($$$1 \\le n_i < 2 \\cdot 10^5$$$) — the length of the $$$i$$$-th sequence. The second line of the $$$i$$$-th pair contains a sequence of $$$n_i$$$ integers $$$a_{i, 1}, a_{i, 2}, \\dots, a_{i, n_i}$$$. The elements of sequences are integer numbers from $$$-10^4$$$ to $$$10^4$$$. The sum of lengths of all given sequences don't exceed $$$2 \\cdot 10^5$$$, i.e. $$$n_1 + n_2 + \\dots + n_k \\le 2 \\cdot 10^5$$$.", "output_spec": "If it is impossible to choose two sequences such that they satisfy given conditions, print \"NO\" (without quotes). Otherwise in the first line print \"YES\" (without quotes), in the second line — two integers $$$i$$$, $$$x$$$ ($$$1 \\le i \\le k, 1 \\le x \\le n_i$$$), in the third line — two integers $$$j$$$, $$$y$$$ ($$$1 \\le j \\le k, 1 \\le y \\le n_j$$$). It means that the sum of the elements of the $$$i$$$-th sequence without the element with index $$$x$$$ equals to the sum of the elements of the $$$j$$$-th sequence without the element with index $$$y$$$. Two chosen sequences must be distinct, i.e. $$$i \\ne j$$$. You can print them in any order. If there are multiple possible answers, print any of them.", "sample_inputs": ["2\n5\n2 3 1 3 2\n6\n1 1 2 2 2 1", "3\n1\n5\n5\n1 1 1 1 1\n2\n2 3", "4\n6\n2 2 2 2 2 2\n5\n2 2 2 2 2\n3\n2 2 2\n5\n2 2 2 2 2"], "sample_outputs": ["YES\n2 6\n1 2", "NO", "YES\n2 2\n4 1"], "notes": "NoteIn the first example there are two sequences $$$[2, 3, 1, 3, 2]$$$ and $$$[1, 1, 2, 2, 2, 1]$$$. You can remove the second element from the first sequence to get $$$[2, 1, 3, 2]$$$ and you can remove the sixth element from the second sequence to get $$$[1, 1, 2, 2, 2]$$$. The sums of the both resulting sequences equal to $$$8$$$, i.e. the sums are equal."}, "positive_code": [{"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString='';\nlet currentLine=0;\nprocess.stdin.on('data',inputStdin=>{\n inputString+=inputStdin;\n});\nprocess.stdin.on('end',_=>{\n inputString=inputString.trim().split(\"\\n\").map(string=>{\n return string.trim();\n });\n main();\n});\nfunction readLine()\n{\n return inputString[currentLine++]; \n}\nfunction main()\n{\n const k=parseInt(readLine());\n let mp=new Map();\n for(let t=0;t{return +(x.trim());});\n let sum=arr.reduce((a,b)=>a+b);\n for(let i=0;i{\n inputString+=inputStdin;\n});\nprocess.stdin.on('end',_=>{\n inputString=inputString.trim().split(\"\\n\").map(string=>{\n return string.trim();\n });\n main();\n});\nfunction readLine()\n{\n return inputString[currentLine++]; \n}\n\nfunction main()\n{\n const K=parseInt(readLine());\n\n var seqSums = [];\n var seqs = []\n\n var map = new Map(); // key: sum - num, value: [\"seqNo,removeItem\", \"seqNo,removeItem\"]\n\n for (var i = 0; i < K; i++) {\n var len = parseInt(readLine());\n var seq=readLine().trim().split(' ').map(x=>{return +(x.trim());});\n var seqSum = 0;\n\n for (var j = 0; j < len; j++) {\n seqSum += seq[j];\n }\n\n for (var j = 0; j < len; j++) {\n if (map.get(seqSum - seq[j]) != undefined) {\n var tmp = map.get(seqSum - seq[j]);\n\n console.log(\"YES\");\n tmp.forEach(function(item) {\n console.log(item.split(',')[0] + \" \" + item.split(',')[1]);\n console.log((i + 1) + \" \" + (j + 1));\n });\n\n map.set(seqSum - seq[j], tmp.push(i + \",\" + seq[j]));\n return;\n }\n }\n\n for (var j = 0; j < len; j++) {\n var tmp = [(i + 1) + \",\" + (j + 1)];\n map.set(seqSum - seq[j], tmp);\n }\n }\n console.log(\"NO\");\n}"}], "negative_code": [{"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString='';\nlet currentLine=0;\nprocess.stdin.on('data',inputStdin=>{\n inputString+=inputStdin;\n});\nprocess.stdin.on('end',_=>{\n inputString=inputString.trim().split(\"\\n\").map(string=>{\n return string.trim();\n });\n main();\n});\nfunction readLine()\n{\n return inputString[currentLine++]; \n}\n\nfunction main()\n{\n const K=parseInt(readLine());\n\n var seqSums = [];\n var seqs = []\n\n var map = new Map(); // key: sum - num, value: [\"seqNo,removeItem\", \"seqNo,removeItem\"]\n\n for (var i = 0; i < K; i++) {\n var len = parseInt(readLine());\n var seq=readLine().trim().split(' ').map(x=>{return +(x.trim());});\n var seqSum = 0;\n\n for (var j = 0; j < len; j++) {\n seqSum += seq[j];\n }\n\n for (var j = 0; j < len; j++) {\n if (map.get(seqSum - seq[j]) != undefined) {\n var tmp = map.get(seqSum - seq[j]);\n\n console.log(\"YES\");\n tmp.forEach(function(item) {\n console.log((parseInt(item.split(',')[0]) + 1) + \" \" + item.split(',')[1]);\n console.log((i + 1) + \" \" + seq[j]);\n });\n\n map.set(seqSum - seq[j], tmp.push(i + \",\" + seq[j]));\n return;\n }\n }\n\n for (var j = 0; j < len; j++) {\n var tmp = [i + \",\" + seq[j]];\n map.set(seqSum - seq[j], tmp);\n }\n }\n console.log(\"NO\");\n}"}], "src_uid": "7561bca5fa2200ce9ae7e30e7076c6ab"} {"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 — 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, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).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, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≤ p ≤ max(x1, x2), min(y1, y2) ≤ q ≤ max(y1, y2).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 ≤ n, m ≤ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) 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 — 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, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1). "}, "positive_code": [{"source_code": "print(function(n, m) {\n\n\tvar a = [];\n\tfor (var i = 0; i < n; i++)\n\t\ta.push(readline().split(' ').map(Number));\n\n\tfor (var i = 0; i < n; i++)\n\t\tfor (var j = 0; j < m; j++)\n\t\t\tif ((i === 0 || i === n - 1 || j === 0 || j === m - 1) && a[i][j] === 1) return 2;\n\n\treturn 4;\n\n} .apply(0, readline().split(' ').map(Number)));"}, {"source_code": ";(function () {\n\tprint(function () {\n\t\tvar l = readline().split(' ').map(Number), n = l[0], m = l[1];\n\n\t\tif (readline().split(' ').indexOf('1') !== -1) return 2;\n\t\telse n -= 2;\n\n\t\twhile (n--) {\n\t\t\tl = readline().split(' ');\n\t\t\tif (l.indexOf('1') === 0 || l.lastIndexOf('1') === m - 1) return 2;\n\t\t}\n\n\t\treturn readline().split(' ').indexOf('1') !== -1 ? 2 : 4;\n\t}());\n}).call(this);\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar integers = tokenizeIntegers(readline());\n\tvar rowNum = integers[0], colNum = integers[1];\n\tfor (var r = 0; r < rowNum; ++r) {\n\t\tvar row = tokenizeIntegers(readline());\n\t\tfor (var c = 0; c < colNum; ++c) {\n\t\t\tif (row[c] == 1) {\n\t\t\t\tif (r == 0 || r == rowNum-1 || c == 0 || c == colNum-1) {\n\t\t\t\t\tprint(2);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprint(4);\n}\n\nmain();\n"}], "negative_code": [{"source_code": ";(function () {\n\tprint(function () {\n\t\tvar l = readline().split(' ').map(Number), n = l[0], m = l[1];\n\n\t\tl = readline().split(' ');\n\t\tif (l.indexOf('1') !== -1) return 2;\n\t\telse n -= 2;\n\n\t\twhile (n--) {\n\t\t\tvar i = readline().split(' ').indexOf('1');\n\t\t\tif (i === 0 || i === m - 1) return 2;\n\t\t}\n\n\t\treturn readline().split(' ').indexOf('1') !== -1 ? 2 : 4;\n\t}());\n}).call(this);\n"}], "src_uid": "0d2fd9b58142c4f5282507c916690244"} {"nl": {"description": "A permutation is a sequence of $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ are permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ are not.Polycarp was given four integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \\le l \\le r \\le n)$$$ and $$$s$$$ ($$$1 \\le s \\le \\frac{n (n+1)}{2}$$$) and asked to find a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$ that satisfies the following condition: $$$s = p_l + p_{l+1} + \\ldots + p_r$$$. For example, for $$$n=5$$$, $$$l=3$$$, $$$r=5$$$, and $$$s=8$$$, the following permutations are suitable (not all options are listed): $$$p = [3, 4, 5, 2, 1]$$$; $$$p = [5, 2, 4, 3, 1]$$$; $$$p = [5, 2, 1, 3, 4]$$$. But, for example, there is no permutation suitable for the condition above for $$$n=4$$$, $$$l=1$$$, $$$r=1$$$, and $$$s=5$$$.Help Polycarp, for the given $$$n$$$, $$$l$$$, $$$r$$$, and $$$s$$$, find a permutation of numbers from $$$1$$$ to $$$n$$$ that fits the condition above. If there are several suitable permutations, print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$). Then $$$t$$$ test cases follow. Each test case consist of one line with four integers $$$n$$$ ($$$1 \\le n \\le 500$$$), $$$l$$$ ($$$1 \\le l \\le n$$$), $$$r$$$ ($$$l \\le r \\le n$$$), $$$s$$$ ($$$1 \\le s \\le \\frac{n (n+1)}{2}$$$). It is guaranteed that the sum of $$$n$$$ for all input data sets does not exceed $$$500$$$.", "output_spec": "For each test case, output on a separate line: $$$n$$$ integers — a permutation of length $$$n$$$ that fits the condition above if such a permutation exists; -1, otherwise. If there are several suitable permutations, print any of them.", "sample_inputs": ["5\n5 2 3 5\n5 3 4 1\n3 1 2 4\n2 2 2 2\n2 1 1 3"], "sample_outputs": ["1 2 3 4 5 \n-1\n1 3 2 \n1 2 \n-1"], "notes": null}, "positive_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, l, r, s] = rna();\r\n\r\n\t\tconst d = r - l + 1;\r\n\r\n\t\tlet need = s;\r\n\t\tconst ar = [];\r\n\t\tfor (let i = 1; i <= d; i++) {\r\n\t\t\tar.push(i);\r\n\t\t\tneed -= i;\r\n\t\t}\r\n\r\n\t\tfor (let i = d - 1; need > 0 && i >= 0; i--) {\r\n\t\t\tconst chng = Math.min(n - d, need);\r\n\t\t\tar[i] += chng;\r\n\t\t\tneed -= chng;\r\n\t\t}\r\n\r\n\t\tconst ss = new Set(ar);\r\n\t\tconst ans = need == 0 && [];\r\n\t\tfor (let i = 1; ans && i <= n; i++) {\r\n\t\t\tif (ans.length == l - 1) ans.push(...ar);\r\n\t\t\tif (!ss.has(i)) ans.push(i);\r\n\t\t}\r\n\t\tif (ans.length < n) ans.push(...ar);\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, l, r, s] = rna();\r\n\r\n\t\tconst d = r - l + 1;\r\n\t\tconst ar = Array.from(Array(d), (_, i) => i + 1);\r\n\r\n\t\tlet need = s - d*(d+1)/2;\r\n\t\tfor (let i = d - 1; need > 0 && i >= 0; i--) {\r\n\t\t\tconst mvs = Math.min(n - d, need);\r\n\t\t\tar[i] += mvs;\r\n\t\t\tneed -= mvs;\r\n\t\t}\r\n\r\n\t\tfor (let i = 0, next = 1; ar.length < n; next++) {\r\n\t\t\tif (next != ar[i]) {\r\n\t\t\t\tar.push(next);\r\n\t\t\t} else {\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst ans = need == 0 && [...ar.slice(n - l + 1), ...ar].slice(0, n);\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nfunction reverse(a, i, j) {\r\n while (i < j) {\r\n let t = a[i];\r\n a[i] = a[j];\r\n a[j] = t;\r\n i++;\r\n j--;\r\n }\r\n}\r\nconst INIT = -1;\r\nlet n;\r\nlet l;\r\nlet r;\r\nlet s;\r\nfunction solve() {\r\n let m = r - l + 1;\r\n let mn = m * (m + 1) / 2;\r\n let hi = n - m;\r\n let mx = hi * m + mn;\r\n // printf(\"n %d m %d mn %d mx %d s %d l %d r %d\\n\", n, m, mn, mx, s, l, r);\r\n if (s < mn || s > mx) {\r\n return false;\r\n }\r\n let used = af(n + 1).fill(0);\r\n let a = [];\r\n m--;\r\n for (let x = n; x >= 1; x--) {\r\n mn = Math.trunc(m * (m + 1) / 2);\r\n if (mn + x > s) {\r\n continue;\r\n }\r\n m--;\r\n s -= x;\r\n used[x] = 1;\r\n a.push(x);\r\n }\r\n // printf(\"a: %j\\n\", a);\r\n for (let x = 1; x <= n; x++) {\r\n if (used[x] == 0) {\r\n a.push(x);\r\n }\r\n }\r\n reverse(a, 0, n - l);\r\n reverse(a, n - l + 1, n - 1);\r\n reverse(a, 0, n - 1);\r\n // printf(\"a: %j\\n\", a);\r\n for (let i = 0; i < n; i++) {\r\n printf(\"%d \", a[i]);\r\n }\r\n printf(\"\\n\");\r\n return true;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n l = nextInt();\r\n r = nextInt();\r\n s = nextInt();\r\n if (!solve()) {\r\n printf(\"%d\\n\", INIT);\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nfunction reverse(a, i, j) {\r\n while (i < j) {\r\n let t = a[i];\r\n a[i] = a[j];\r\n a[j] = t;\r\n i++;\r\n j--;\r\n }\r\n}\r\nconst INIT = -1;\r\nlet n;\r\nlet l;\r\nlet r;\r\nlet s;\r\nfunction solve() {\r\n let m = r - l + 1;\r\n let mn = m * (m + 1) / 2;\r\n let hi = n - m;\r\n let mx = hi * m + mn;\r\n // printf(\"n %d m %d mn %d mx %d s %d l %d r %d\\n\", n, m, mn, mx, s, l, r);\r\n if (s < mn || s > mx) {\r\n return false;\r\n }\r\n let used = af(n + 1).fill(0);\r\n let a = [];\r\n while (s > 0) {\r\n m--;\r\n mn = m * (m + 1) / 2;\r\n let x = Math.min(n, s - mn);\r\n while (used[x]) {\r\n x--;\r\n }\r\n used[x] = 1;\r\n a.push(x);\r\n s -= x;\r\n }\r\n for (let x = 1; x <= n; x++) {\r\n if (used[x] == 0) {\r\n a.push(x);\r\n }\r\n }\r\n // printf(\"a: %j\\n\", a);\r\n reverse(a, 0, n - l);\r\n reverse(a, n - l + 1, n - 1);\r\n reverse(a, 0, n - 1);\r\n // printf(\"a: %j\\n\", a);\r\n for (let i = 0; i < n; i++) {\r\n printf(\"%d \", a[i]);\r\n }\r\n printf(\"\\n\");\r\n return true;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n l = nextInt();\r\n r = nextInt();\r\n s = nextInt();\r\n if (!solve()) {\r\n printf(\"%d\\n\", INIT);\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nvar maxN = 21\r\nvar mod = 1000000007\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n const xx = readline();\r\n\r\n Array(Number(xx)).fill(1).map((t, i) => {\r\n // var n = parseInt(readline());\r\n var [n, l, r, s] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n l--\r\n r--\r\n var length = r - l + 1\r\n var lower = n - length + 1\r\n var ans = new Array(n).fill(false)\r\n var min = (((r - l + 1) + 1) * (r - l + 1)) / 2\r\n var max = (lower - 1) * length + ((length + 1) * (r - l + 1)) / 2\r\n var used = new Array(n + 1).fill(false)\r\n if (s < min || s > max) return console.log(-1)\r\n\r\n var a = []\r\n for (let j = 0; j < length; j++) {\r\n a[j] = j + 1\r\n s=s-a[j]\r\n }\r\n\r\n for (let j = length-1; j >=0; j--) {\r\n while (s>0 && a[j] < n - (length -j-1)){\r\n s--\r\n a[j]++\r\n }\r\n }\r\n for (let j = l; j <=r; j++) {\r\n ans[j] = a[j-l]\r\n used[ans[j]] = true\r\n }\r\n // console.log(ans.join(' '))\r\n\r\n for (let j = 1; j <= n; j++) {\r\n if (!used[j])\r\n for (let i = 0; i < n; i++) {\r\n if (ans[i] === false) {\r\n ans[i] = j\r\n break\r\n }\r\n }\r\n }\r\n console.log(ans.join(' '))\r\n\r\n\r\n })\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, l, r, s] = rna();\r\n\r\n\t\tconst d = r - l + 1;\r\n\r\n\t\tlet need = s;\r\n\t\tconst ar = [];\r\n\t\tfor (let i = 1; i <= d; i++) {\r\n\t\t\tar.push(i);\r\n\t\t\tneed -= i;\r\n\t\t}\r\n\r\n\t\tfor (let i = d - 1; need > 0 && i >= 0; i--) {\r\n\t\t\tconst chng = Math.min(n - d, need);\r\n\t\t\tar[i] += chng;\r\n\t\t\tneed -= chng;\r\n\t\t}\r\n\r\n\t\tconst ss = new Set(ar);\r\n\t\tconst ans = need == 0 && [];\r\n\t\tfor (let i = 1; ans && i <= n; i++) {\r\n\t\t\tif (ans.length == l - 1) {\r\n\t\t\t\tans.push(...ar);\r\n\t\t\t}\r\n\t\t\tif (!ss.has(i)) {\r\n\t\t\t\tans.push(i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, l, r, s] = rna();\r\n\r\n\t\tconst d = r - l + 1;\r\n\r\n\t\tlet need = s;\r\n\t\tconst ar = [];\r\n\t\tfor (let i = 1; i <= d; i++) {\r\n\t\t\tar.push(i);\r\n\t\t\tneed -= i;\r\n\t\t}\r\n\r\n\t\tfor (let i = d - 1; need > 0 && i >= 0; i--) {\r\n\t\t\tconst chng = Math.min(n - d, need);\r\n\t\t\tar[i] += chng;\r\n\t\t\tneed -= chng;\r\n\t\t}\r\n\r\n\t\tconst ss = new Set(ar);\r\n\t\tconst ans = need == 0 && [];\r\n\t\tfor (let i = 1; ans && i <= n; i++) {\r\n\t\t\tif (!ss.has(i)) {\r\n\t\t\t\tans.push(i);\r\n\t\t\t}\r\n\t\t\tif (ans.length == l - 1) {\r\n\t\t\t\tans.push(...ar);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nfunction reverse(a, i, j) {\r\n while (i < j) {\r\n let t = a[i];\r\n a[i] = a[j];\r\n a[j] = t;\r\n i++;\r\n j--;\r\n }\r\n}\r\nconst INIT = -1;\r\nlet n;\r\nlet l;\r\nlet r;\r\nlet s;\r\nfunction solve() {\r\n let m = r - l + 1;\r\n let mn = m * (m + 1) / 2;\r\n let hi = n - m;\r\n let mx = hi * m + mn;\r\n // printf(\"m %d n %d mn %d mx %d\\n\", m, n, mn, mx);\r\n if (s < mn || s > mx) {\r\n return false;\r\n }\r\n let used = af(n + 1).fill(0);\r\n let a = [];\r\n while (s > 0) {\r\n m--;\r\n mn = m * (m + 1) / 2;\r\n let x = s - mn;\r\n used[x] = 1;\r\n a.push(x);\r\n s -= x;\r\n }\r\n for (let x = 1; x <= n; x++) {\r\n if (used[x] == 0) {\r\n a.push(x);\r\n }\r\n }\r\n // printf(\"a: %j\\n\", a);\r\n reverse(a, 0, n - l);\r\n reverse(a, n - l + 1, n - 1);\r\n reverse(a, 0, n - 1);\r\n // printf(\"a: %j\\n\", a);\r\n for (let i = 0; i < n; i++) {\r\n printf(\"%d \", a[i]);\r\n }\r\n printf(\"\\n\");\r\n return true;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n l = nextInt();\r\n r = nextInt();\r\n s = nextInt();\r\n if (!solve()) {\r\n printf(\"%d\\n\", INIT);\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nfunction reverse(a, i, j) {\r\n while (i < j) {\r\n let t = a[i];\r\n a[i] = a[j];\r\n a[j] = t;\r\n i++;\r\n j--;\r\n }\r\n}\r\nconst INIT = -1;\r\nlet n;\r\nlet l;\r\nlet r;\r\nlet s;\r\nfunction solve() {\r\n let m = r - l + 1;\r\n let mn = m * (m + 1) / 2;\r\n let hi = n - m;\r\n let mx = hi * m + mn;\r\n printf(\"m %d n %d mn %d mx %d\\n\", m, n, mn, mx);\r\n if (s < mn || s > mx) {\r\n return false;\r\n }\r\n let used = af(n + 1).fill(0);\r\n let a = [];\r\n while (s > 0) {\r\n m--;\r\n mn = m * (m + 1) / 2;\r\n let x = s - mn;\r\n used[x] = 1;\r\n a.push(x);\r\n s -= x;\r\n }\r\n for (let x = 1; x <= n; x++) {\r\n if (used[x] == 0) {\r\n a.push(x);\r\n }\r\n }\r\n // printf(\"a: %j\\n\", a);\r\n reverse(a, 0, n - l);\r\n reverse(a, n - l + 1, n - 1);\r\n reverse(a, 0, n - 1);\r\n // printf(\"a: %j\\n\", a);\r\n for (let i = 0; i < n; i++) {\r\n printf(\"%d \", a[i]);\r\n }\r\n printf(\"\\n\");\r\n return true;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n l = nextInt();\r\n r = nextInt();\r\n s = nextInt();\r\n if (!solve()) {\r\n printf(\"%d\\n\", INIT);\r\n }\r\n }\r\n}\r\n"}], "src_uid": "88c8376ad65c5c932c15dc09d6c4d75f"} {"nl": {"description": "Polycarp came up with a new programming language. There are only two types of statements in it: \"x := s\": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a variable. Between the variable name, the := operator and the string contains exactly one space each. \"x = a + b\": assign the variable named x the concatenation of values of two variables a and b. For example, if the program consists of three statements a := hello, b := world, c = a + b, then the variable c will contain the string helloworld. It is guaranteed that the program is correct and the variables a and b were previously defined. There is exactly one space between the variable names and the = and + operators. All variable names and strings only consist of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters.The result of the program is the number of occurrences of string haha in the string that was written to the variable in the last statement.Polycarp was very tired while inventing that language. He asks you to implement it. Your task is — for given program statements calculate the number of occurrences of string haha in the last assigned variable.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 50$$$) — the number of statements in the program. All variable names and strings are guaranteed to consist only of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters. This is followed by $$$n$$$ lines describing the statements in the format described above. It is guaranteed that the program is correct.", "output_spec": "For each set of input data, output the number of occurrences of the haha substring in the string that was written to the variable in the last statement.", "sample_inputs": ["4\n6\na := h\nb := aha\nc = a + b\nc = c + c\ne = c + c\nd = a + c\n15\nx := haha\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\nx = x + x\n1\nhaha := hah\n5\nhaahh := aaaha\nahhhh = haahh + haahh\nhaahh = haahh + haahh\nahhhh = ahhhh + haahh\nahhaa = haahh + ahhhh"], "sample_outputs": ["3\n32767\n0\n0"], "notes": "NoteIn the first test case the resulting value of d is hhahahaha."}, "positive_code": [{"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tif(values[1] == ':=') {\r\n\t\t\tvar v = values[2];\r\n\t\t\tvar c = 0;\r\n\t\t\tif(v.length === 4){\r\n\t\t\t\tif(v[0] + v[1] + v[2] + v[3] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t} else if (v.length === 5) {\r\n\t\t\t\tif(v[0] + v[1] + v[2] + v[3] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t} else if(v[1] + v[2] + v[3] + v[4] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tvalStart: values[2].substring(0, Math.min(3, values[2].length)),\r\n\t\t\t\tvalEnd: values[2].substring(Math.max(0, values[2].length - 3)),\r\n\t\t\t\tcount: c\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} \r\n\t\telse {\r\n\t\t\tvar a = objVars[values[2]].val;\r\n\t\t\tvar b = objVars[values[4]].val;\r\n\t\t\tvar c = objVars[values[2]].count + objVars[values[4]].count;\r\n\t\t\t\r\n\t\t\tvar mid = objVars[values[2]].valEnd + objVars[values[4]].valStart;\r\n\t\t\t\r\n\t\t\tfor(var j = 0; j + 3 < mid.length; j++) {\r\n\t\t\t\tif(mid.substring(j, j + 4) === 'haha'){\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tvalStart: objVars[values[2]].valStart.length < 3 ? mid.substring(0, Math.min(3, mid.length)) : objVars[values[2]].valStart,\r\n\t\t\t\tvalEnd: objVars[values[4]].valEnd.length < 3 ? mid.substring(Math.max(0, mid.length - 3)) : objVars[values[4]].valEnd,\r\n\t\t\t\tcount: c\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\tprint(objVars[values[0]].count);\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}], "negative_code": [{"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tif(values[1] == ':=') {\r\n\t\t\tvar v = values[2];\r\n\t\t\tvar c = 0;\r\n\t\t\tif(v.length === 4){\r\n\t\t\t\tif(v[0] + v[1] + v[2] + v[3] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t} else if (v.length === 5) {\r\n\t\t\t\tif(v[0] + v[1] + v[2] + v[3] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t} else if(v[1] + v[2] + v[3] + v[4] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tvalStart: values[2].substring(0, Math.min(3, values[2].length)),\r\n\t\t\t\tvalEnd: values[2].substring(Math.max(0, values[2].length - 3)),\r\n\t\t\t\tcount: c\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} \r\n\t\telse {\r\n\t\t\tvar a = objVars[values[2]].val;\r\n\t\t\tvar b = objVars[values[4]].val;\r\n\t\t\tvar c = objVars[values[2]].count + objVars[values[4]].count;\r\n\t\t\t\r\n\t\t\tvar mid = objVars[values[2]].valEnd + objVars[values[4]].valStart;\r\n\t\t\t\r\n\t\t\tfor(var j = 0; j + 3 < mid.length; j++) {\r\n\t\t\t\tif(mid.substring(j, j + 4) === 'haha'){\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tvalStart: objVars[values[2]].valStart.length < 3 ? mid.substring(0, Math.min(3, mid.length)) : objVars[values[2]].valStart,\r\n\t\t\t\tvalEnd: objVars[values[2]].valEnd.length < 3 ? mid.substring(Math.max(0, mid.length - 3)) : objVars[values[2]].valEnd,\r\n\t\t\t\tcount: c\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\tprint(objVars[values[0]].count);\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}, {"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tif(values[1] == ':=') {\r\n\t\t\tvar v = values[2];\r\n\t\t\tvar c = 0;\r\n\t\t\tif(v.length === 4){\r\n\t\t\t\tif(v[0] + v[1] + v[2] + v[3] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t} else if (v.length === 5) {\r\n\t\t\t\tif(v[0] + v[1] + v[2] + v[3] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t} else if(v[1] + v[2] + v[3] + v[4] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tvalStart: values[2].substring(0, Math.min(3, values[2].length)),\r\n\t\t\t\tvalEnd: values[2].substring(Math.max(0, values[2].length - 3)),\r\n\t\t\t\tcount: c\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} \r\n\t\telse {\r\n\t\t\tvar a = objVars[values[2]].val;\r\n\t\t\tvar b = objVars[values[4]].val;\r\n\t\t\tvar c = objVars[values[2]].count + objVars[values[4]].count;\r\n\t\t\t\r\n\t\t\tvar mid = objVars[values[2]].valEnd + objVars[values[4]].valStart;\r\n\t\t\t\r\n\t\t\tfor(var j = 0; j < mid.length; j++) {\r\n\t\t\t\tif(mid.substring(j, j + 4) === 'haha'){\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tvalStart: objVars[values[2]].valStart.length < 3 ? mid.substring(0, Math.min(3, mid.length)) : objVars[values[2]].valStart,\r\n\t\t\t\tvalEnd: objVars[values[2]].valEnd.length < 3 ? mid.substring(Math.max(0, mid.length - 3)) : objVars[values[2]].valEnd,\r\n\t\t\t\tcount: c\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\tprint(objVars[values[0]].count);\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}, {"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tif(values[1] == ':=') {\r\n\t\t\tvar v = values[2];\r\n\t\t\tvar c = 0;\r\n\t\t\tif(v.length === 4){\r\n\t\t\t\tif(v[0] + v[1] + v[2] + v[3] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t} else if (v.length === 5) {\r\n\t\t\t\tif(v[1] + v[2] + v[3] + v[4] === 'haha') {\r\n\t\t\t\t\tc++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tval : values[2],\r\n\t\t\t\tcount: c\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} else {\r\n\t\t\tvar v1 = objVars[values[2]].val;\r\n\t\t\tvar v2 = objVars[values[4]].val;\r\n\t\t\tvar c1 = objVars[values[2]].count;\r\n\t\t\tvar c2 = objVars[values[4]].count;\r\n\t\t\t\r\n\t\t\tvar vv = v1 + v2;\r\n\t\t\tvar cc = c1 + c2;\r\n\t\t\t\r\n\t\t\tvar lv1 = v1.length - 3;\r\n\t\t\tvar lvv = vv.length;\r\n\t\t\t\r\n\t\t\tvar index0 = lv1;\r\n\t\t\tvar index1 = lv1 + 3;\r\n\t\t\t\r\n\t\t\twhile(index0 < 0) {\r\n\t\t\t\tindex0++;\r\n\t\t\t\tindex1++;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(index1 <= lvv){\r\n\t\t\t\twhile(index1 < lv1 + 6){\r\n\t\t\t\t\tif(vv[index0] + vv[index0+1] + vv[index0+2] + vv[index0+3] === 'haha') {\r\n\t\t\t\t\t\tcc++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tindex1++;\r\n\t\t\t\t\tindex0++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tobjVars[values[0]] = {\r\n\t\t\t\tval: vv,\r\n\t\t\t\tcount: cc\r\n\t\t\t};\r\n\t\t}\r\n\t}\r\n\tprint(objVars[values[0]].count);\r\n\t\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}, {"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tprint(values[0])\r\n\t\tprint(values[1])\r\n\t\tprint(values[2])\r\n\t\tif(values.length === 4) {\r\n\t\t\tobjVars[values[0]] = values[2];\r\n\t\t} else {\r\n\t\t\tobjVars[values[0]] = objVars[values[2]] + objVars[values[4]];\r\n\t\t}\r\n\t}\r\n\t\r\n\tvar lastVal = objVars[values[0]];\r\n\tfor(var i = 0; i < lastVal.length - 3; i++){\r\n\t\tif(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){\r\n\t\t\tcount++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprint(count);\r\n\t\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}, {"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tprint(values)\r\n\t\tif(values.length === 4) {\r\n\t\t\tobjVars[values[0]] = values[2];\r\n\t\t} else {\r\n\t\t\tobjVars[values[0]] = objVars[values[2]] + objVars[values[4]];\r\n\t\t}\r\n\t}\r\n\t\r\n\tvar lastVal = objVars[values[0]];\r\n\tfor(var i = 0; i < lastVal.length - 3; i++){\r\n\t\tif(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){\r\n\t\t\tcount++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprint(count);\r\n\t\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}, {"source_code": "function readStringArray() {\r\n return readline().split(\" \");\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tif(values.length === 4) {\r\n\t\t\tobjVars[values[0]] = values[2];\r\n\t\t} else {\r\n\t\t\tobjVars[values[0]] = objVars[values[2]] + objVars[values[4]];\r\n\t\t}\r\n\t}\r\n\t\r\n\tvar lastVal = objVars[values[0]];\r\n\tfor(var i = 0; i < lastVal.length - 3; i++){\r\n\t\tif(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){\r\n\t\t\tcount++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprint(count);\r\n\t\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}, {"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tif(values.length === 4) {\r\n\t\t\tobjVars[values[0]] = values[2];\r\n\t\t} else {\r\n\t\t\tobjVars[values[0]] = objVars[values[2]] + objVars[values[4]];\r\n\t\t}\r\n\t}\r\n\t\r\n\tvar lastVal = objVars[values[0]];\r\n\tfor(var i = 0; i < lastVal.length - 3; i++){\r\n\t\tif(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){\r\n\t\t\tcount++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprint(count);\r\n\t\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}, {"source_code": "function readStringArray() {\r\n return readline().split(/\\s/);\r\n}\r\n\r\nfunction solve() {\r\n\tvar lines = parseInt(readline(), 10);\r\n\tvar objVars = {};\r\n\tvar count = 0;\r\n\t\t\r\n\tfor(var i = 0; i < lines; i++){\r\n\t\tvar values = readStringArray();\r\n\t\tif(values.length === 4) {\r\n\t\t\tobjVars[values[0]] = values[2];\r\n\t\t} else {\r\n\t\t\tobjVars[values[0]] = objVars[values[2]] + objVars[values[4]];\r\n\t\t}\r\n\t}\r\n\t\r\n\tvar lastVal = objVars[values[0]];\r\n\tfor(var i = 0; i < lastVal.length - 3; i++){\r\n\t\tif(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){\r\n\t\t\tcount++;\r\n\t\t}\r\n\t}\r\n\tprint(count++);\r\n\t\r\n}\r\n\r\nfunction main(){\r\n\tvar t = parseInt(readline(), 10);\r\n\tfor (var i = 0; i < t; i++) {\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nmain();"}], "src_uid": "356bd72aa9143681f1efd695969a8c8e"} {"nl": {"description": "In the Bus of Characters there are $$$n$$$ rows of seat, each having $$$2$$$ seats. The width of both seats in the $$$i$$$-th row is $$$w_i$$$ centimeters. All integers $$$w_i$$$ are distinct.Initially the bus is empty. On each of $$$2n$$$ stops one passenger enters the bus. There are two types of passengers: an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 200\\,000$$$) — the number of rows in the bus. The second line contains the sequence of integers $$$w_1, w_2, \\dots, w_n$$$ ($$$1 \\le w_i \\le 10^{9}$$$), where $$$w_i$$$ is the width of each of the seats in the $$$i$$$-th row. It is guaranteed that all $$$w_i$$$ are distinct. The third line contains a string of length $$$2n$$$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $$$j$$$-th character is '0', then the passenger that enters the bus on the $$$j$$$-th stop is an introvert. If the $$$j$$$-th character is '1', the the passenger that enters the bus on the $$$j$$$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $$$n$$$), and for each extrovert there always is a suitable row.", "output_spec": "Print $$$2n$$$ integers — the rows the passengers will take. The order of passengers should be the same as in input.", "sample_inputs": ["2\n3 1\n0011", "6\n10 8 9 11 13 5\n010010011101"], "sample_outputs": ["2 1 1 2", "6 6 2 3 3 1 4 4 1 2 5 5"], "notes": "NoteIn the first example the first passenger (introvert) chooses the row $$$2$$$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $$$1$$$, because it is the only empty row now. The third passenger (extrovert) chooses the row $$$1$$$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $$$2$$$, because it is the only row with an empty place."}, "positive_code": [{"source_code": " var n = parseInt(readline());\n var r = readline().split(' ').map((x, i) => [parseInt(x), i + 1]);\n var od = readline().split('').map(x => parseInt(x));\n\n r = r.sort(function(a, b) { return b[0] - a[0]});\n\n var e = [];\n var res = [];\n for(var i = 0; i < 2 * n; i += 1) {\n if(od[i] === 0) {\n var w = r.pop();\n res.push(w[1]);\n e.push(w);\n } else {\n var w = e.pop();\n res.push(w[1]);\n }\n }\n print(res.join(' '));"}], "negative_code": [], "src_uid": "161009edb8e3d438cdd8c0d1e202f783"} {"nl": {"description": "Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \\dots, b_n$$$ is called nondecreasing if $$$b_i\\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.", "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 an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$) — the number of supports Omkar has. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \\leq a_{i} \\leq 10^9)$$$ — the heights of the supports. 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 a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.", "sample_inputs": ["3\n4\n5 3 2 5\n5\n1 2 3 5 3\n3\n1 1 1"], "sample_outputs": ["3\n2\n0"], "notes": "NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:$$$[5, 3, \\textbf{2}, 5] \\to [5, 3, \\textbf{3}, 5]$$$Second operation:$$$[5, \\textbf{3}, \\textbf{3}, 5] \\to [5, \\textbf{4}, \\textbf{4}, 5]$$$Third operation:$$$[5, \\textbf{4}, \\textbf{4}, 5] \\to [5, \\textbf{5}, \\textbf{5}, 5]$$$In the third test case, the array is already nondecreasing, so Omkar does $$$0$$$ operations."}, "positive_code": [{"source_code": "const getMinOperations = (nums) => {\n var count = 0;\n\n for (var i = nums.length - 1; i >= 1; i--) {\n count += Math.max(0, nums[i - 1] - nums[i]);\n }\n\n return count;\n};\n\nconst main = () => {\n const T = Number(readline());\n\n for (var _ = 0; _ < T; _++) {\n readline();\n var nums = readline()\n .split(\" \")\n .map((i) => Number(i));\n\n print(getMinOperations(nums));\n }\n};\n\nmain();"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n let arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n const store = [];\n\n for (let i = 0; i < len - 1; i++) {\n if (arr[i] - arr[i + 1] > 0) store.push(arr[i] - arr[i + 1]);\n }\n\n if (store.length) {\n const sum = store.reduce((total, n) => total + n, 0);\n console.log(sum);\n } else {\n console.log(0);\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const t = Number(readLine())\n for (let _ = 0; _ < t; _++) {\n\tconst n = Number(readLine())\n const as = readLine().split(/\\s/).map(Number)\n let result = 0\n for (let i = 1; i < n; i++) {\n result += Math.max(0, as[i - 1] - as[i])\n }\n console.log(result)\n }\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\n\t\tlet d = [];\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\td.push(arr[i] - arr[i - 1]);\n\t\t}\n\n\t\tlet s = d.reduce((a, c) => (c < 0 ? a + c : a), 0);\n\t\tconsole.log(Math.abs(s));\n\t}\n}\n"}], "negative_code": [{"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\n\t\tlet v = 0,\n\t\t\tc = arr[0];\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tif (arr[i] < c) {\n\t\t\t\tv = Math.max(v, c - arr[i]);\n\t\t\t} else {\n\t\t\t\tc = arr[i];\n\t\t\t}\n\t\t}\n\t\tconsole.log(v);\n\t}\n}\n"}], "src_uid": "0bd06900e42db9f83cdd43c24da6686e"} {"nl": {"description": "Soroush and Keshi each have a labeled and rooted tree on $$$n$$$ vertices. Both of their trees are rooted from vertex $$$1$$$.Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on $$$n$$$ vertices.They add an edge between vertices $$$u$$$ and $$$v$$$ in the memorial graph if both of the following conditions hold: One of $$$u$$$ or $$$v$$$ is the ancestor of the other in Soroush's tree. Neither of $$$u$$$ or $$$v$$$ is the ancestor of the other in Keshi's tree. Here vertex $$$u$$$ is considered ancestor of vertex $$$v$$$, if $$$u$$$ lies on the path from $$$1$$$ (the root) to the $$$v$$$.Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big. Help Mashtali by finding the size of the maximum clique in the memorial graph.As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.", "input_spec": "The first line contains an integer $$$t$$$ $$$(1\\le t\\le 3 \\cdot 10^5)$$$ — 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 3 \\cdot 10^5)$$$. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \\ldots, a_n$$$ $$$(1 \\le a_i < i)$$$, $$$a_i$$$ being the parent of the vertex $$$i$$$ in Soroush's tree. The third line of each test case contains $$$n-1$$$ integers $$$b_2, \\ldots, b_n$$$ $$$(1 \\le b_i < i)$$$, $$$b_i$$$ being the parent of the vertex $$$i$$$ in Keshi's tree. It is guaranteed that the given graphs are trees. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case print a single integer — the size of the maximum clique in the memorial graph.", "sample_inputs": ["4\n4\n1 2 3\n1 2 3\n5\n1 2 3 4\n1 1 1 1\n6\n1 1 1 1 2\n1 2 1 2 2\n7\n1 1 3 4 4 5\n1 2 1 4 2 5"], "sample_outputs": ["1\n4\n1\n3"], "notes": "NoteIn the first and third test cases, you can pick any vertex.In the second test case, one of the maximum cliques is $$$\\{2, 3, 4, 5\\}$$$.In the fourth test case, one of the maximum cliques is $$$\\{3, 4, 6\\}$$$."}, "positive_code": [{"source_code": "const TreeMultiSet = (function () {\nvar{TreeMultiSet:t}=function(t){\n/*! *****************************************************************************\n Copyright (c) Microsoft Corporation.\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n PERFORMANCE OF THIS SOFTWARE.\n ***************************************************************************** */\nvar e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if(\"function\"!=typeof n&&null!==n)throw new TypeError(\"Class extends value \"+String(n)+\" is not a constructor or null\");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t){var e=\"function\"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&\"number\"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}function o(t,e){var n=\"function\"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o=1&&r[0]instanceof Array?(e=function(){var e=r[0];t.push.apply(t,i([],o(e),!1))},n=r.slice(1)):r.length>=2&&r[0].next instanceof Function&&r[1].next instanceof Function?(e=function(){var e=r[0],n=r[1];t.assign(e,n)},n=r.slice(2)):(e=null,n=r),{ramda:e,tail:n}}}(s||(s={}));var h=null;function p(){return null===y&&(null===h&&(h=\"object\"==typeof global&&\"object\"==typeof global.process&&\"object\"==typeof global.process.versions&&void 0!==global.process.versions.node),void 0===(y=h?global:self).__s_iUID&&(y.__s_iUID=0)),y}var f,y=null;function v(t){if(t instanceof Object){if(!1===t.hasOwnProperty(\"__get_m_iUID\")){var e=++p().__s_iUID;Object.defineProperty(t,\"__get_m_iUID\",{value:function(){return e}})}return t.__get_m_iUID()}return void 0===t?-1:0}function d(t,e){return t=t?t.valueOf():t,e=e?e.valueOf():e,t instanceof Object&&t.equals instanceof Function?t.equals(e):t===e}function g(t,e){return t=t.valueOf(),e=e.valueOf(),t instanceof Object?t.less instanceof Function?t.less(e):v(t)=1&&(c=l.tail[0])}n(c),null!==a&&a()},t.emplacable=function(t,e,n){var r=e.prev(),o=r.equals(t.end())||t.value_comp()(r.value,n);return o=o&&(e.equals(t.end())||t.value_comp()(n,e.value))}}(f||(f={}));var w,I=2166136261,k=16777619,q=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.equals=function(t){return d(this.first,t.first)&&d(this.second,t.second)},t.prototype.less=function(t){return!1===d(this.first,t.first)?g(this.first,t.first):g(this.second,t.second)},t.prototype.hashCode=function(){return function(){for(var t,e,n=[],o=0;o (index = \"+r+\").\")},t.excessive_index=function(t,n,r,o){return new S(\"Error on \"+e(t)+\".\"+n+\"(): parametric index is equal or greater than size -> (index = \"+r+\", size: \"+o+\").\")},t.not_my_iterator=function(t,n){return new F(\"Error on \"+e(t)+\".\"+n+\"(): parametric iterator is not this container's own.\")},t.erased_iterator=function(t,n){return new F(\"Error on \"+e(t)+\".\"+n+\"(): parametric iterator, it already has been erased.\")},t.negative_iterator=function(t,n,r){return new S(\"Error on \"+e(t)+\".\"+n+\"(): parametric iterator is directing negative position -> (index = \"+r+\").\")},t.iterator_end_value=function(t,n){void 0===n&&(n=\"end\");var r=e(t);return new S(\"Error on \"+r+\".Iterator.value: cannot access to the \"+r+\".\"+n+\"().value.\")},t.key_nout_found=function(t,n,r){throw new S(\"Error on \"+e(t)+\".\"+n+\"(): unable to find the matched key -> \"+r)}}(w||(w={}));var j=function(){function t(t,e,n){this.prev_=t,this.next_=e,this.value_=n}return t._Set_prev=function(t,e){t.prev_=e},t._Set_next=function(t,e){t.next_=e},t.prototype.prev=function(){return this.prev_},t.prototype.next=function(){return this.next_},Object.defineProperty(t.prototype,\"value\",{get:function(){return this._Try_value(),this.value_},enumerable:!1,configurable:!0}),t.prototype._Try_value=function(){if(void 0===this.value_&&!0===this.equals(this.source().end()))throw w.iterator_end_value(this.source())},t.prototype.equals=function(t){return this===t},t}(),z=function(){function t(t,e){this.index_=t,this.value_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,\"value\",{get:function(){return this.value_},enumerable:!1,configurable:!0}),t.prototype.next=function(){return++this.index_,this},t.prototype.equals=function(t){return this.index_===t.index_},t}();var R=function(t){function e(){var e=t.call(this)||this;return e.end_=e._Create_iterator(null,null),e.clear(),e}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(this.end(),t,e)},e.prototype.clear=function(){j._Set_prev(this.end_,this.end_),j._Set_next(this.end_,this.end_),this.begin_=this.end_,this.size_=0},e.prototype.resize=function(t){var e=t-this.size();e>0?this.insert(this.end(),e,void 0):e<0&&this.erase(function(t,e){if(0===e)return t;if(t.advance instanceof Function)return t.advance(e);var n;if(e<0){if(!(t.prev instanceof Function))throw new F(\"Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.\");n=function(t){return t.prev()},e=-e}else n=function(t){return t.next()};for(;e-- >0;)t=n(t);return t}(this.end(),-e),this.end())},e.prototype.begin=function(){return this.begin_},e.prototype.end=function(){return this.end_},e.prototype.size=function(){return this.size_},e.prototype.push_front=function(t){this.insert(this.begin_,t)},e.prototype.push_back=function(t){this.insert(this.end_,t)},e.prototype.pop_front=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,\"pop_front\");this.erase(this.begin_)},e.prototype.pop_back=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,\"pop_back\");this.erase(this.end_.prev())},e.prototype.push=function(){for(var t=[],e=0;e {\n adj1[p] = adj1[p] || []\n adj1[p].push(i + 2)\n })\n const adj2 = {}\n t2.forEach((p, i) => {\n adj2[p] = adj2[p] || []\n adj2[p].push(i + 2)\n })\n\n // dfs 2\n TIMER = 0\n L = []\n R = []\n dfs2(adj2, 1)\n\n // dfs 1\n SET = new TreeMultiSet((a, b) => L[a] < L[b]) // [[L[u], u]], means the dfs path\n ANS = 0\n try {\n dfs1(adj1, 1)\n } catch (e) {\n return e.stack\n }\n return ANS\n}\n\nfunction print() {\n let iter = SET.begin()\n const ans = []\n while (iter !== SET.end()) {\n ans.push(iter.value)\n iter = iter.next()\n }\n console.log(ans.join(' '))\n}\n\nfunction dfs1(adj, r) {\n const stack = [[r, 0, -1]]\n const befores = []\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n // lower bound, the first >= L[u]\n const iter = SET.lower_bound(u)\n const before = iter.prev()\n // exists someone after u\n const hasChild = iter !== SET.end() && isAncestor(u, iter.value)\n // exists someone before u, check\n // don't worry about the earier ones, they must be safe with each other\n const hasAncestor = iter !== SET.begin() && isAncestor(before.value, u)\n\n if (!hasChild) {\n // add self\n add(u)\n }\n if (hasAncestor) {\n // erease the ancestor\n erase(before.value)\n befores[u] = before\n }\n ANS = Math.max(ANS, SET.size());\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n stack.pop()\n\n const before = befores[u]\n // recover the path\n erase(u)\n if (before) {\n add(before.value)\n }\n }\n }\n}\nfunction dfs2(adj, r) {\n const stack = [[r, 0, -1]]\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n L[u] = TIMER++\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n stack.pop()\n R[u] = TIMER\n }\n }\n}\nfunction isAncestor(u, v) { // u is the ancestor of v\n return L[u] <= L[v] && R[v] <= R[u]\n}\n\nfunction add(u) {\n SET.insert(u)\n // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] < L[u])\n // SET.splice(idx + 1, 0, [L[u], u])\n}\nfunction erase(u) {\n SET.erase(u)\n // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] <= L[u])\n // SET.splice(idx, 1)\n}\nfunction binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}\n"}], "negative_code": [{"source_code": "const TreeMultiSet = (function () {\nvar{TreeMultiSet:t}=function(t){\n/*! *****************************************************************************\n Copyright (c) Microsoft Corporation.\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n PERFORMANCE OF THIS SOFTWARE.\n ***************************************************************************** */\nvar e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if(\"function\"!=typeof n&&null!==n)throw new TypeError(\"Class extends value \"+String(n)+\" is not a constructor or null\");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t){var e=\"function\"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&\"number\"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}function o(t,e){var n=\"function\"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o=1&&r[0]instanceof Array?(e=function(){var e=r[0];t.push.apply(t,i([],o(e),!1))},n=r.slice(1)):r.length>=2&&r[0].next instanceof Function&&r[1].next instanceof Function?(e=function(){var e=r[0],n=r[1];t.assign(e,n)},n=r.slice(2)):(e=null,n=r),{ramda:e,tail:n}}}(s||(s={}));var h=null;function p(){return null===y&&(null===h&&(h=\"object\"==typeof global&&\"object\"==typeof global.process&&\"object\"==typeof global.process.versions&&void 0!==global.process.versions.node),void 0===(y=h?global:self).__s_iUID&&(y.__s_iUID=0)),y}var f,y=null;function v(t){if(t instanceof Object){if(!1===t.hasOwnProperty(\"__get_m_iUID\")){var e=++p().__s_iUID;Object.defineProperty(t,\"__get_m_iUID\",{value:function(){return e}})}return t.__get_m_iUID()}return void 0===t?-1:0}function d(t,e){return t=t?t.valueOf():t,e=e?e.valueOf():e,t instanceof Object&&t.equals instanceof Function?t.equals(e):t===e}function g(t,e){return t=t.valueOf(),e=e.valueOf(),t instanceof Object?t.less instanceof Function?t.less(e):v(t)=1&&(c=l.tail[0])}n(c),null!==a&&a()},t.emplacable=function(t,e,n){var r=e.prev(),o=r.equals(t.end())||t.value_comp()(r.value,n);return o=o&&(e.equals(t.end())||t.value_comp()(n,e.value))}}(f||(f={}));var w,I=2166136261,k=16777619,q=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.equals=function(t){return d(this.first,t.first)&&d(this.second,t.second)},t.prototype.less=function(t){return!1===d(this.first,t.first)?g(this.first,t.first):g(this.second,t.second)},t.prototype.hashCode=function(){return function(){for(var t,e,n=[],o=0;o (index = \"+r+\").\")},t.excessive_index=function(t,n,r,o){return new S(\"Error on \"+e(t)+\".\"+n+\"(): parametric index is equal or greater than size -> (index = \"+r+\", size: \"+o+\").\")},t.not_my_iterator=function(t,n){return new F(\"Error on \"+e(t)+\".\"+n+\"(): parametric iterator is not this container's own.\")},t.erased_iterator=function(t,n){return new F(\"Error on \"+e(t)+\".\"+n+\"(): parametric iterator, it already has been erased.\")},t.negative_iterator=function(t,n,r){return new S(\"Error on \"+e(t)+\".\"+n+\"(): parametric iterator is directing negative position -> (index = \"+r+\").\")},t.iterator_end_value=function(t,n){void 0===n&&(n=\"end\");var r=e(t);return new S(\"Error on \"+r+\".Iterator.value: cannot access to the \"+r+\".\"+n+\"().value.\")},t.key_nout_found=function(t,n,r){throw new S(\"Error on \"+e(t)+\".\"+n+\"(): unable to find the matched key -> \"+r)}}(w||(w={}));var j=function(){function t(t,e,n){this.prev_=t,this.next_=e,this.value_=n}return t._Set_prev=function(t,e){t.prev_=e},t._Set_next=function(t,e){t.next_=e},t.prototype.prev=function(){return this.prev_},t.prototype.next=function(){return this.next_},Object.defineProperty(t.prototype,\"value\",{get:function(){return this._Try_value(),this.value_},enumerable:!1,configurable:!0}),t.prototype._Try_value=function(){if(void 0===this.value_&&!0===this.equals(this.source().end()))throw w.iterator_end_value(this.source())},t.prototype.equals=function(t){return this===t},t}(),z=function(){function t(t,e){this.index_=t,this.value_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,\"value\",{get:function(){return this.value_},enumerable:!1,configurable:!0}),t.prototype.next=function(){return++this.index_,this},t.prototype.equals=function(t){return this.index_===t.index_},t}();var R=function(t){function e(){var e=t.call(this)||this;return e.end_=e._Create_iterator(null,null),e.clear(),e}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(this.end(),t,e)},e.prototype.clear=function(){j._Set_prev(this.end_,this.end_),j._Set_next(this.end_,this.end_),this.begin_=this.end_,this.size_=0},e.prototype.resize=function(t){var e=t-this.size();e>0?this.insert(this.end(),e,void 0):e<0&&this.erase(function(t,e){if(0===e)return t;if(t.advance instanceof Function)return t.advance(e);var n;if(e<0){if(!(t.prev instanceof Function))throw new F(\"Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.\");n=function(t){return t.prev()},e=-e}else n=function(t){return t.next()};for(;e-- >0;)t=n(t);return t}(this.end(),-e),this.end())},e.prototype.begin=function(){return this.begin_},e.prototype.end=function(){return this.end_},e.prototype.size=function(){return this.size_},e.prototype.push_front=function(t){this.insert(this.begin_,t)},e.prototype.push_back=function(t){this.insert(this.end_,t)},e.prototype.pop_front=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,\"pop_front\");this.erase(this.begin_)},e.prototype.pop_back=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,\"pop_back\");this.erase(this.end_.prev())},e.prototype.push=function(){for(var t=[],e=0;e {\n adj1[p] = adj1[p] || []\n adj1[p].push(i + 2)\n })\n const adj2 = {}\n t2.forEach((p, i) => {\n adj2[p] = adj2[p] || []\n adj2[p].push(i + 2)\n })\n\n // dfs 2\n TIMER = 0\n L = []\n R = []\n dfs2(adj2, 1)\n\n // dfs 1\n SET = new TreeMultiSet((a, b) => L[a] < L[b]) // [[L[u], u]], means the dfs path\n ANS = 0\n try {\n dfs1(adj1, 1)\n } catch (e) {\n return e.stack\n }\n return ANS\n}\n\nfunction print() {\n let iter = SET.begin()\n const ans = []\n while (iter !== SET.end()) {\n ans.push(iter.value)\n iter = iter.next()\n }\n console.log(ans.join(' '))\n}\n\nfunction dfs1(adj, u) {\n // lower bound, the first >= L[u]\n // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] < L[u]) + 1\n // const before = SET[idx - 1]\n // const after = SET[idx]\n // console.log(SET.begin() === SET.end().prev(), SET.size())\n const iter = SET.lower_bound(u)\n const before = iter.prev()\n // const after = iter\n // exists someone after u\n const hasChild = iter !== SET.end() && isAncestor(u, iter.value)\n // const hasChild = idx !== SET.length && isAncestor(u, after[1])\n\n // exists someone before u, check\n // don't worry about the earier ones, they must be safe with each other\n const hasAncestor = iter !== SET.begin() && isAncestor(before.value, u)\n // const hasAncestor = idx > 0 && isAncestor(before[1], u)\n if (!hasChild) {\n // add self\n add(u)\n }\n if (hasAncestor) {\n // erease the ancestor\n erase(before.value)\n }\n ANS = Math.max(ANS, SET.size());\n\n // recursion\n (adj[u] || []).forEach(v => {\n dfs1(adj, v)\n })\n\n // recover the path\n erase(u)\n if (hasAncestor) {\n add(before.value)\n }\n}\nfunction dfs2(adj, u) {\n L[u] = TIMER++\n (adj[u] || []).forEach(v => {\n dfs2(adj, v)\n })\n R[u] = TIMER\n}\nfunction isAncestor(u, v) { // u is the ancestor of v\n return L[u] <= L[v] && R[v] <= R[u]\n}\n\nfunction add(u) {\n SET.insert(u)\n // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] < L[u])\n // SET.splice(idx + 1, 0, [L[u], u])\n}\nfunction erase(u) {\n SET.erase(u)\n // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] <= L[u])\n // SET.splice(idx, 1)\n}\nfunction binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}\n"}], "src_uid": "dc1a20d875572a3f45a9844030b0fcf4"} {"nl": {"description": "You have an axis-aligned rectangle room with width $$$W$$$ and height $$$H$$$, so the lower left corner is in point $$$(0, 0)$$$ and the upper right corner is in $$$(W, H)$$$.There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $$$(x_1, y_1)$$$, and the upper right corner in $$$(x_2, y_2)$$$.You want to place another rectangular table in this room with width $$$w$$$ and height $$$h$$$ with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room. Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?", "input_spec": "The first line contains the single integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) — the number of the test cases. The first line of each test case contains two integers $$$W$$$ and $$$H$$$ ($$$1 \\le W, H \\le 10^8$$$) — the width and the height of the room. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$0 \\le x_1 < x_2 \\le W$$$; $$$0 \\le y_1 < y_2 \\le H$$$) — the coordinates of the corners of the first table. The third line contains two integers $$$w$$$ and $$$h$$$ ($$$1 \\le w \\le W$$$; $$$1 \\le h \\le H$$$) — the width and the height of the second table.", "output_spec": "For each test case, print the minimum distance you should move the first table, or $$$-1$$$ if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.", "sample_inputs": ["5\n8 5\n2 1 7 4\n4 2\n5 4\n2 2 5 4\n3 3\n1 8\n0 3 1 6\n1 5\n8 1\n3 0 6 1\n5 1\n8 10\n4 5 7 8\n8 5"], "sample_outputs": ["1.000000000\n-1\n2.000000000\n2.000000000\n0.000000000"], "notes": "NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by $$$(0, -1)$$$, so the lower left corner will move from $$$(2, 1)$$$ to $$$(2, 0)$$$. Then you can place the second table at $$$(0, 3)-(4, 5)$$$.In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by $$$(0, 2)$$$, so the lower left corner will move from $$$(0, 3)$$$ to $$$(0, 5)$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst sqrt = (n) => {\r\n let low = 1n,\r\n high = n,\r\n ans;\r\n while (low <= high) {\r\n let mid = (low + high) / 2n;\r\n if (mid * mid <= n) {\r\n ans = mid;\r\n low = mid + 1n;\r\n } else high = mid - 1n;\r\n }\r\n return ans;\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [rw, rh] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseFloat(cur));\r\n let [x1, y1, x2, y2] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseFloat(cur));\r\n let u = rh - y2,\r\n r = rw - x2,\r\n l = x1,\r\n d = y1;\r\n let [tw, th] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseFloat(cur));\r\n let ans = Infinity;\r\n if (l >= tw) ans = 0;\r\n if (r >= tw - l && tw - l >= 0) ans = Math.min(ans, tw - l);\r\n if (r >= tw) ans = 0;\r\n if (l >= tw - r && tw - r >= 0) ans = Math.min(ans, tw - r);\r\n if (u >= th) ans = 0;\r\n if (d >= th - u && th - u >= 0) ans = Math.min(ans, th - u);\r\n if (d >= th) ans = 0;\r\n if (u >= th - d && th - d >= 0) ans = Math.min(ans, th - d);\r\n if (ans === Infinity) ans = -1;\r\n console.log(ans);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nlet INF = 2e8;\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet [W, H] = rna();\r\n\t\tlet [x1, y1, x2, y2] = rna();\r\n\t\tlet [w, h] = rna();\r\n\r\n\t\thmx = Math.max(H - y2, y1);\r\n\t\twmx = Math.max(x1, W - x2);\r\n\r\n\t\tif (w < wmx || h < hmx)\r\n\t\t\tconsole.log(0);\r\n\t\telse {\r\n\t\t\tlet ans1 = ans2 = INF;\r\n\t\t\tif (h + (y2 - y1) <= H) {\r\n\t\t\t\tans1 = h - hmx;\r\n\t\t\t}\r\n\r\n\t\t\tif (w + (x2 - x1) <= W) {\r\n\t\t\t\tans2 = w - wmx;\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log((ans1 & ans2) == INF ? -1 : Math.min(ans1, ans2));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var [W, H] = lines[l++].split(' ').map(Number)\n var [x1, y1, x2, y2] = lines[l++].split(' ').map(Number)\n var [w, h] = lines[l++].split(' ').map(Number)\n console.log(solve(W, H, x1, y1, x2, y2, w, h))\n }\n});\n\nfunction solve(W, H, x1, y1, x2, y2, w, h) {\n const l = x1\n const r = W - x2\n const t = H - y2\n const b = y1\n // console.log(l, r, t, b)\n let d1 = -1\n let d2 = -1\n if (l + r >= w) {\n d1 = h > H ? -1 : Math.max(0, w - Math.max(l, r))\n }\n if (t + b >= h) {\n d2 = w > W ? -1 : Math.max(0, h - Math.max(t, b))\n }\n\n if (d1 >= 0 && d2 >= 0) {\n return Math.min(d1, d2)\n } else if (d1 >= 0) {\n return d1\n } else if (d2 >= 0) {\n return d2\n }\n return -1\n}\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(e)\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(n => {\r\n stdin.on('data', n => e.push(n)),\r\n stdin.on('end', function () {\r\n const t = e.join('').split(os.EOL)\r\n n(t)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const n = new InputAndOutput()\r\n await n.init(), e(n)\r\n}\r\nfunction solve(e, n, t, i, s, r, u, d) {\r\n if (u > e || d > n) return -1\r\n if (u + (s - t) > e && d + (r - i) > n) return -1\r\n if (u <= t || u + s <= e) return 0\r\n if (d <= i || d + r <= n) return 0\r\n let o = Number.MAX_SAFE_INTEGER\r\n return (\r\n u + (s - t) <= e && (o = Math.min(o, u - t, u + s - e)),\r\n d + (r - i) <= n && (o = Math.min(o, d - i, d + r - n)),\r\n o\r\n )\r\n}\r\n__main__(function (e) {\r\n const n = Number(e.readLine())\r\n for (let t = 1; t <= n; ++t) {\r\n const [n, t] = e.readIntegersOfLine(),\r\n [i, s, r, u] = e.readIntegersOfLine(),\r\n [d, o] = e.readIntegersOfLine(),\r\n a = solve(n, t, i, s, r, u, d, o)\r\n e.print(a + '\\n')\r\n }\r\n})\r\n"}, {"source_code": "const setTable = (rWH, t1P, t2WH ) => {\r\n var rW = rWH[0];\r\n var rH = rWH[1];\r\n \r\n var t1X1 = t1P[0];\r\n var t1Y1 = t1P[1];\r\n var t1X2 = t1P[2];\r\n var t1Y2 = t1P[3];\r\n var t1W = t1X2 - t1X1;\r\n var t1H = t1Y2 - t1Y1;\r\n \r\n var t2W = t2WH[0];\r\n var t2H = t2WH[1];\r\n \r\n if((t1W + t2W > rW) && (t1H + t2H > rH)) {\r\n return -1;\r\n }\r\n \r\n var fSW = Math.max(t1X1, rW - t1X2);\r\n var fSH = Math.max(t1Y1, rH - t1Y2);\r\n \r\n var shift = Math.min(\r\n t1W + t2W > rW ? Infinity : t2W - fSW, \r\n t1H + t2H > rH ? Infinity : t2H - fSH\r\n );\r\n \r\n return shift >= 0 ? shift : 0;\r\n};\r\n\r\nconst n = +readline();\r\n\r\nvar roomWH;\r\nvar table1Points;\r\nvar table2WH;\r\n\r\nfor(var i = 0; i < n; i++) {\r\n roomWH = readline().split(\" \").map(i => +i);\r\n table1Points = readline().split(\" \").map(i => +i);\r\n table2WH = readline().split(\" \").map(i => +i);\r\n print(setTable(roomWH, table1Points, table2WH));\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst sqrt = (n) => {\r\n let low = 1n,\r\n high = n,\r\n ans;\r\n while (low <= high) {\r\n let mid = (low + high) / 2n;\r\n if (mid * mid <= n) {\r\n ans = mid;\r\n low = mid + 1n;\r\n } else high = mid - 1n;\r\n }\r\n return ans;\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [rw, rh] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseFloat(cur));\r\n let [x1, y1, x2, y2] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseFloat(cur));\r\n let u = rh - y2,\r\n r = rw - x2,\r\n l = x1,\r\n d = y1;\r\n let [tw, th] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseFloat(cur));\r\n let ans = Infinity;\r\n if (l >= tw) ans = 0;\r\n if (r >= tw - l) ans = Math.min(ans, tw - l);\r\n if (r >= tw) ans = 0;\r\n if (l >= tw - r) ans = Math.min(ans, tw - r);\r\n if (u >= th) ans = 0;\r\n if (d >= th - u) ans = Math.min(ans, th - u);\r\n if (d >= th) ans = 0;\r\n if (u >= th - d) ans = Math.min(ans, th - d);\r\n if (ans === Infinity) ans = -1;\r\n console.log(ans);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var [W, H] = lines[l++].split(' ').map(Number)\n var [x1, y1, x2, y2] = lines[l++].split(' ').map(Number)\n var [w, h] = lines[l++].split(' ').map(Number)\n console.log(solve(W, H, x1, y1, x2, y2, w, h))\n }\n});\n\nfunction solve(W, H, x1, y1, x2, y2, w, h) {\n const l = x1\n const r = W - x2\n const t = H - y2\n const b = y1\n // console.log(l, r, t, b)\n if (l + r >= w) {\n return h > H ? -1 : Math.max(0, w - Math.max(l, r))\n }\n if (t + b >= h) {\n return w > W ? -1 : Math.max(0, h - Math.max(t, b))\n }\n return -1\n}\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(e)\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(n => {\r\n stdin.on('data', n => e.push(n)),\r\n stdin.on('end', function () {\r\n const t = e.join('').split(os.EOL)\r\n n(t)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const n = new InputAndOutput()\r\n await n.init(), e(n)\r\n}\r\nconst MAX_N = 100010,\r\n sum1 = new Array(MAX_N)\r\nfunction solve(e, n, t) {\r\n if (e <= 1) return 0\r\n sum1[0] = n[0]\r\n for (let t = 1; t < e; ++t) sum1[t] = sum1[t - 1] + n[t]\r\n const s = e - 1\r\n let i = sum1[s] - n[0]\r\n for (let n = 1, r = t[0]; n < e; ++n) {\r\n const e = Math.max(sum1[s] - sum1[n], r)\r\n ;(r += t[n]), i > e && (i = e)\r\n }\r\n return i\r\n}\r\n__main__(function (e) {\r\n const n = Number(e.readLine())\r\n for (let t = 1; t <= n; ++t) {\r\n const n = solve(\r\n Number(e.readLine()),\r\n e.readIntegersOfLine(),\r\n e.readIntegersOfLine(),\r\n )\r\n e.print(n + '\\n')\r\n }\r\n})\r\n"}], "src_uid": "29fd4c77a2f28478ebce98dfc6496aac"} {"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$$$) — 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$$$) — 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 inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst mul = (a, b) => mod(mod(a) * mod(b));\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [len, a, b] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n let min = Number.MAX_SAFE_INTEGER;\n let result = [];\n\n for (let start = 1; start <= 50; start++) {\n for (let diff = 1; diff <= 50; diff++) {\n const arr = [start];\n let [foundA, foundB] = [false, false];\n for (let i = 1; i < len; i++) {\n arr.push(start + diff * i);\n }\n for (let i = 0; i < len; i++) {\n if (arr[i] === a) foundA = true;\n if (arr[i] === b) foundB = true;\n }\n if (foundA && foundB) {\n if (arr[len - 1] < min) {\n min = arr[len - 1];\n result = [...arr];\n }\n }\n }\n }\n console.log(result.join(\" \"));\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n↑入力 ↓出力');\n Main();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var one = nextIntArray();\n var N = one[0];\n var x = one[1];\n var y = one[2];\n if(N == 2){\n output[i] = x + \" \" + y;\n continue;\n }\n var dlist = getDivisorList(y - x);\n var out = [];\n var max = Math.pow(10,9);\n for(var j = 0; j < dlist.length; j++){\n var tmpmax = y;\n var tmpout = [x];\n var isOK = false;\n for(var k = 1; k <= N; k++){\n if(x + k * dlist[j] > y){\n isOK = true;\n break;\n }\n tmpout.push(x + k * dlist[j]);\n \n }\n //myerr(tmpout);\n if(isOK && tmpout.length <= N){\n for(var k = 1; k <= N; k++){\n if(tmpout.length == N){\n break;\n }\n if(x - dlist[j] * k < 1){\n break;\n }\n tmpout.unshift(x - dlist[j] * k);\n\n }\n while(tmpout.length < N){\n tmpout.push(tmpout[tmpout.length - 1] + dlist[j]);\n tmpmax = tmpout[tmpout.length - 1];\n }\n if(max > tmpmax){\n max = tmpmax;\n out = tmpout;\n }\n //myerr(tmpout);\n }else{\n continue;\n }\n }\n output[i] = myconv(out, 8);\n }\n myout(myconv(output, 9));\n}\nfunction getDivisorList(val){\n var list = [];\n for(var i = 1; i * i <= val; i++){\n if(val % i == 0){\n list.push(i);\n if(i * i != val){\n list.push(val / i);\n }\n }\n }\n list.sort(function(a,b){ return a - b; });\n return list;\n}"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nlet input = [];\n\nrl.on(\"line\", function (line) {\n input.push(line);\n}).on(\"close\", function () {\n solve(input);\n process.exit();\n});\n\nfunction solve(input) {\n const t = input[0];\n\n for (let i = 1; i <= t; i++) {\n let [n, x, y] = input[i].split(\" \").map((num) => Number(num));\n\n if (n === 2) {\n console.log([x, y].join(\" \"));\n continue;\n }\n\n const diff = y - x;\n const result = [];\n\n //1. x와 y사이에는 (n-2)개 ~ 0개의 원소가 존재할 수 있다.\n for (let j = n - 1; j >= 0; j--) {\n const equalDiff = diff / j;\n\n //2. 정수로 나뉘어 떨어지지 않는다면 해당 개수는 불가능\n if (equalDiff !== parseInt(equalDiff)) {\n continue;\n }\n\n //3. 정수로 나누어 떨어진다면 해당 배열이 답이다\n //3-1. x와 y 넣기\n result.push(x);\n result.push(y);\n n -= 2;\n\n //3-2. x와 y 사이 넣기\n for (let k = 1; k <= j - 1; k++) {\n n--;\n result.push(x + k * equalDiff);\n }\n\n //3-3. x 이전 넣기\n for (let k = 1; ; k++) {\n if (n <= 0) break;\n\n const xBefore = x - k * equalDiff;\n if (xBefore <= 0) break;\n\n n--;\n result.push(xBefore);\n }\n\n //3-4. y 이후 넣기\n for (let k = 1; ; k++) {\n if (n <= 0) break;\n\n const yAfter = y + k * equalDiff;\n n--;\n result.push(yAfter);\n }\n\n //7. 최댓값이 존재하는 배열을 만들어 출력한다\n console.log(result.join(\" \"));\n break;\n }\n }\n}\n\n/*\n\n 1. 비밀 배열을 복원해야 한다\n 2. n개의 서로 다른 양의 정수를 포함하고 있다\n 3. 너에게 알려진 x와 y를 포함하고 있는데, x < y\n 4. 오름차순으로 정렬 시, 각 인접 원소 간의 diff는 모두 동일\n\n Q. 가장 큰 원소의 값이 최소가 되는 배열의 원소들을 출력하라\n \n*/\n"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i <= b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = a; i >= b; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction Arr(a, b, cb) {\n if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb(i + a));\n return Array(a - b + 1).fill(0).map((v, i) => cb(a - i));\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\nfunction max(a, b) {\n if (a > b) return a;\n return b;\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\D+/).map(v => +v); r = 0;\n let t = inp[r++];\n For(0, t - 1, i => {\n let [n, x, y] = inp.slice(r, r = r + 3);\n // console.log(n, x, y);\n For(n - 1, 1, i => {\n if ((y - x) % i == 0) {\n let k = (y - x) / i;\n a = Arr(0, i, i => x + i * k);\n while (a.length < n) {\n if (a[0] - k >= 1) a.unshift(a[0] - k);\n else a.push(a[a.length - 1] + k);\n }\n console.log(a.join(' '));\n return 0;\n }\n })\n })\n})();"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n C();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [a,b] = ti(readline().split(' '));\n\n if(a === b){\n console.log(0);\n continue;\n }\n\n let d = Math.abs(a-b);\n if(d <= 10){\n console.log(1);\n continue;\n }else{\n if(d % 10 !== 0)\n console.log(1 + Math.floor(d/10));\n else\n console.log(d / 10);\n }\n }\n}\n\nfunction B(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [a,b,x,y,n] = ti(readline().split(' '));\n\n if(a > b){\n let temp = a;\n a = b;\n b = temp;\n temp = x;\n x = y;\n y = temp;\n }\n\n if(b - y >= n){\n b -= n;\n console.log(a*b);\n }else{\n n -= (b-y);\n b = y;\n if(a-x >= n){\n a -= n;\n }else{\n a = x;\n }\n\n console.log(a*b);\n }\n }\n}\n\nfunction C(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [n,x,y] = ti(readline().split(' '));\n\n let min = 99999999999999;\n let res = null;\n for(let i = 1; i <= x; i++){\n for(let j = 0; j <= y-x; j++){\n let inclX = false;\n let inclY = false;\n let op = new Array(n);\n for(let k = 0; k < n; k++){\n if(k === 0){\n op[k] = i;\n }else{\n op[k] = op[k-1] + j;\n }\n\n if(op[k] === x)\n inclX = true;\n \n if(op[k] === y)\n inclY = true;\n }\n\n if(inclX && inclY){\n if(min > op[n-1]){\n min = op[n-1];\n res = op;\n }\n }\n }\n }\n\n for(let num of res)\n console.log(num);\n }\n}"}, {"source_code": "T = readline()\nwhile (T--) {\n a = readline().split(' ')\n n = +a[0]\n x = +a[1]\n y = +a[2]\n d = y - x\n k = 1\n for (; k < 50; k++) {\n if (d % k)\n continue\n if (d / k + 1 <= n)\n break\n }\n j = n - 1\n while (y - j * k < 1)\n j--\n u = y - j * k\n ans = ''\n for (i = 0; i < n; i++) {\n ans += u.toString() + ' '\n u += k\n }\n print(ans)\n}"}, {"source_code": "T = readline()\nwhile (T--) {\n a = readline().split(' ').map(x => +x)\n n = a[0]; x = a[1]; y = a[2]\n d = y - x\n k = 1\n for (; k < 50; k++) {\n if (d % k)\n continue\n if (d / k + 1 <= n)\n break\n }\n j = n - 1\n while (y - j * k < 1)\n j--\n u = y - j * k\n print(Array.from({ length: n }, (v, i) => u + k * i).join(' '));\n}\n"}], "negative_code": [{"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nlet input = [];\n\nrl.on(\"line\", function (line) {\n input.push(line);\n}).on(\"close\", function () {\n solve(input);\n process.exit();\n});\n\nfunction solve(input) {\n const t = input[0];\n\n for (let i = 1; i <= t; i++) {\n let [n, x, y] = input[i].split(\" \").map((num) => Number(num));\n\n if (n === 2) {\n console.log([x, y]);\n continue;\n }\n\n const diff = y - x;\n const result = [];\n\n //1. x와 y사이에는 (n-2)개 ~ 0개의 원소가 존재할 수 있다.\n for (let j = n - 1; j >= 0; j--) {\n const equalDiff = diff / j;\n\n //2. 정수로 나뉘어 떨어지지 않는다면 해당 개수는 불가능\n if (equalDiff !== parseInt(equalDiff)) {\n continue;\n }\n\n //3. 정수로 나누어 떨어진다면 해당 배열이 답이다\n //3-1. x와 y 넣기\n result.push(x);\n result.push(y);\n n -= 2;\n\n //3-2. x와 y 사이 넣기\n for (let k = 1; k <= j - 1; k++) {\n n--;\n result.push(x + k * equalDiff);\n }\n\n //3-3. x 이전 넣기\n for (let k = 1; ; k++) {\n if (n <= 0) break;\n\n const xBefore = x - k * equalDiff;\n if (xBefore <= 0) break;\n\n n--;\n result.push(xBefore);\n }\n\n //3-4. y 이후 넣기\n for (let k = 1; ; k++) {\n if (n <= 0) break;\n\n const yAfter = y + k * equalDiff;\n n--;\n result.push(yAfter);\n }\n\n //6. 정렬\n result.sort((n1, n2) => {\n return n1 - n2;\n });\n\n //7. 최댓값이 존재하는 배열을 만들어 출력한다\n console.log(result);\n break;\n }\n }\n}\n\n/*\n\n 1. 비밀 배열을 복원해야 한다\n 2. n개의 서로 다른 양의 정수를 포함하고 있다\n 3. 너에게 알려진 x와 y를 포함하고 있는데, x < y\n 4. 오름차순으로 정렬 시, 각 인접 원소 간의 diff는 모두 동일\n\n Q. 가장 큰 원소의 값이 최소가 되는 배열의 원소들을 출력하라\n \n*/\n"}], "src_uid": "ca9d97e731e86cf8223520f39ef5d945"} {"nl": {"description": "Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...Most of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter $$$e_i$$$ — his inexperience. Russell decided that an explorer with inexperience $$$e$$$ can only join the group of $$$e$$$ or more people.Now Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.", "input_spec": "The first line contains the number of independent test cases $$$T$$$($$$1 \\leq T \\leq 2 \\cdot 10^5$$$). Next $$$2T$$$ lines contain description of test cases. The first line of description of each test case contains the number of young explorers $$$N$$$ ($$$1 \\leq N \\leq 2 \\cdot 10^5$$$). The second line contains $$$N$$$ integers $$$e_1, e_2, \\ldots, e_N$$$ ($$$1 \\leq e_i \\leq N$$$), where $$$e_i$$$ is the inexperience of the $$$i$$$-th explorer. It's guaranteed that sum of all $$$N$$$ doesn't exceed $$$3 \\cdot 10^5$$$.", "output_spec": "Print $$$T$$$ numbers, each number on a separate line. In $$$i$$$-th line print the maximum number of groups Russell can form in $$$i$$$-th test case.", "sample_inputs": ["2\n3\n1 1 1\n5\n2 3 1 2 2"], "sample_outputs": ["3\n2"], "notes": "NoteIn the first example we can organize three groups. There will be only one explorer in each group. It's correct because inexperience of each explorer equals to $$$1$$$, so it's not less than the size of his group.In the second example we can organize two groups. Explorers with inexperience $$$1$$$, $$$2$$$ and $$$3$$$ will form the first group, and the other two explorers with inexperience equal to $$$2$$$ will form the second group.This solution is not unique. For example, we can form the first group using the three explorers with inexperience equal to $$$2$$$, and the second group using only one explorer with inexperience equal to $$$1$$$. In this case the young explorer with inexperience equal to $$$3$$$ will not be included in any group."}, "positive_code": [{"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextIntArray();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = nextInt();\n\t\tvar list = nextIntArray();\n\t\tvar map = {};\n\t\tfor(var j = 0; j < N; j++){\n\t\t\tif(map[list[j]] == null){\n\t\t\t\tmap[list[j]] = 1;\n\t\t\t}else{\n\t\t\t\tmap[list[j]]++;\n\t\t\t}\n\t\t}\n\t\tvar keys = Object.keys(map);\n\t\tkeys.sort(function(a,b){\n\t\t\treturn a - b;\n\t\t});\n\t\tvar count = 0;\n\t\tfor(var j = 0; j < keys.length; j++){\n\t\t\tvar singleCount = Math.floor(map[keys[j]] / keys[j]);\n\t\t\tvar nokori = map[keys[j]] % keys[j];\n\t\t\tcount += singleCount;\n\t\t\tif(j != keys.length - 1){\n\t\t\t\tmap[keys[j + 1]] += nokori;\n\t\t\t}\n\t\t}\n\t\toutput[i] = count;\n\t}\n\tmyout(myconv(output,9));\n}"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x).sort((a, b) => a-b).reduce((r, x, index) => {\n if (index > 0) {\n if (r[r.length - 1][0] === x) {\n r[r.length - 1][1]++\n } else {\n r.push([x, 1])\n }\n } else {\n r.push([x, 1])\n }\n return r\n }, [])\n let sum = 0\n let rest = 0\n for (let j=0; j= num) {\n sum += Math.floor(count/num)\n rest = count % num\n } else {\n rest += e[j][1]\n }\n }\n console.log(sum)\n // while(start < e.length) {\n // start += e[start]\n // c++\n // }\n // if (start > e.length) {\n // c--\n // }\n // console.log(c)\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 6\n1\n2\n3\n4\n5\n6\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r a - b);\n let temp = 0;\n let ans = 0;\n\n for(let i=0;i {\n const n = +lines[0]\n for (let i=0; i +x).sort((a, b) => a-b).reduce((r, x, index) => {\n if (index > 0) {\n if (r[r.length - 1][0] === x) {\n r[r.length - 1][1]++\n } else {\n r.push([x, 1])\n }\n } else {\n r.push([x, 1])\n }\n return r\n }, [])\n let sum = 0\n let rest = 0\n for (let j=0; j= num) {\n sum += Math.floor(count/num)\n rest = count % num\n }\n }\n console.log(sum)\n // while(start < e.length) {\n // start += e[start]\n // c++\n // }\n // if (start > e.length) {\n // c--\n // }\n // console.log(c)\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x)\n e.sort((a, b) => b - a)\n let start = 0\n let c = 0\n while(start < e.length) {\n start += e[start]\n c++\n }\n console.log(c)\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 6\n1\n2\n3\n4\n5\n6\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nlet clone = Array.push;\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r a - b);\n\n let count = 0;\n while(a.length) {\n a.shift();\n a.pop();\n count++\n }\n\n console.log(count);\n\n }\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 6\n1\n2\n3\n4\n5\n6\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nlet clone = Array.push;\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r b ? a : b);\n}\n\nfunction min(a, b) {\n return (a > b ? b : a);\n}\n\nvar n = readline().split(' ');\n\nfor (var i = 0; i < n; i++) {\n var line = readline().split(' ');\n var x = parseInt(line[0]), y = parseInt(line[1]);\n line = readline().split(' ');\n var a = parseInt(line[0]), b = parseInt(line[1]);\n if (max(x, y) == max(a, b) && min(x, y) + min(a, b) == max(x, y)) print(\"YES\");\n else print(\"NO\");\n}"}, {"source_code": "var t = Number(readline());\nwhile(t--) {\n var v = readline().split(\" \");\n var a1 = Number(v[0]);\n var b1 = Number(v[1]);\n\n v = readline().split(\" \");\n var a2 = Number(v[0]);\n var b2 = Number(v[1]);\n\n if ((a1 == a2 && b1+b2 == a1) || (b1 == b2 && a1+a2 == b1)) print(\"YES\");\n else if ((a1 == b2 && b1+a2 == a1) || (b1 == a2 && a1+b2 == b1)) print(\"YES\");\n else print(\"NO\");\n}"}, {"source_code": "var line = readline().split(' ').map((x) => parseInt(x));\n\nwhile(line[0]--) {\n\t\n\tvar l1 = readline().split(' ').map((x) => parseInt(x));\n\tvar l2 = readline().split(' ').map((x) => parseInt(x));\n\n\tif(l1[0]==l2[0]) {\n\n\t\tif(l1[1]+l2[1] == l1[0]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\t\t\n\tif(l1[1]==l2[1]) {\n\n\t\tif(l1[0]+l2[0] == l1[1]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\n\t}\n\n\tif(l1[1]==l2[0]) {\n\n\t\tif(l1[0]+l2[1] == l1[1]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\t\n\tif(l1[0]==l2[1]) {\n\n\t\tif(l1[1]+l2[0] == l1[0]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\t\tprint(\"No\");\n\t}"}, {"source_code": "\tvar line = readline().split(' ').map((x) => parseInt(x));\n\nwhile(line[0]--) {\n\t\n\tvar l1 = readline().split(' ').map((x) => parseInt(x));\n\tvar l2 = readline().split(' ').map((x) => parseInt(x));\n\n\tif(l1[0]==l2[0]) {\n\n\t\tif(l1[1]+l2[1] == l1[0]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\t\t\n\tif(l1[1]==l2[1]) {\n\n\t\tif(l1[0]+l2[0] == l1[1]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\n\t}\n\n\tif(l1[1]==l2[0]) {\n\n\t\tif(l1[0]+l2[1] == l1[1]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\t\n\tif(l1[0]==l2[1]) {\n\n\t\tif(l1[1]+l2[0] == l1[0]) {\n\t\t\tprint(\"Yes\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\t\tprint(\"No\");\n\t}\n\n"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n for (let i = 0; i < n; i++) {\n const [a, b] = readLine().split(' ').map(x => parseInt(x));\n const [c, d] = readLine().split(' ').map(x => parseInt(x));\n if ((a == c && (b+d) ==a ) || (a == d && (b + c) == a) || (c == b && (a+d) ==c ) || (b == d && (a+c) ==b ) ){\n console.log('YES')\n } else console.log('NO')\n }\n return;\n}\n"}, {"source_code": "const readline = require('readline');\nconst r = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet tc\nlet slice1,slice2;\nr.on('line', (line) => {\n if (!tc) { tc = line; }\n else if (!slice1) {\n slice1 = line;\n \n }\n else if (!slice2) {\n slice2 = line;\n let d1 = slice1.split(\" \").map(n =>+n);\n let d2 = slice2.split(\" \").map(n =>+n);\n console.log( sq(d1[0],d1[1],d2[0],d2[1]) ?\"YES\":\"NO\");\n slice1= slice2= undefined;\n }\n else {\n query = readNums(line);\n console.log(minLength(arr, query[0], query[1]));\n }\n\n});\n\nfunction sq(a,b,c,d){\n return (a==c && a == (b+d)) || (a==d && a == (b+c)) ||((b==c && b == (a+d))) ||((b==d && b == (a+c)))\n}"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar mae = nextIntArray();\n\t\tvar ato = nextIntArray();\n\t\tif(mae[0] == ato[0] || mae[0] == ato[1] || mae[1] == ato[0] || mae[1] == ato[1]){\n\t\t\tif(mae[0] == ato[0]){\n\t\t\t\tif(mae[1] + ato[1] == mae[0]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(mae[0] == ato[1]){\n\t\t\t\tif(mae[1] + ato[0] == mae[0]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(mae[1] == ato[0]){\n\t\t\t\tif(mae[0] + ato[1] == mae[1]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(mae[1] == ato[1]){\n\t\t\t\tif(mae[0] + ato[0] == mae[1]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(output[i] == null){\n\t\t\t\toutput[i] = \"NO\";\n\t\t\t}\n\t\t}else{\n\t\t\toutput[i] = \"NO\";\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "const readline = require('readline');\nconst r = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet tc\nlet slice1, slice2;\nr.on('line', (line) => {\n if (!tc) { tc = line; }\n else if (!slice1) {\n slice1 = line;\n\n }\n else if (!slice2) {\n slice2 = line;\n let d1 = slice1.split(\" \").map(n => +n);\n let d2 = slice2.split(\" \").map(n => +n);\n console.log(sq(d1[0], d1[1], d2[0], d2[1]) ? \"YES\" : \"NO\");\n slice1 = slice2 = undefined;\n }\n else {\n query = readNums(line);\n console.log(minLength(arr, query[0], query[1]));\n }\n\n});\n\nfunction sq(a, b, c, d) {\n return (a == c && a == (b + d)) || (a == d && a == (b + c)) || ((b == c && b == (a + d))) || ((b == d && b == (a + c)))\n}\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x).sort((a, b) => b-a)\n const [c, d] = lines[i*2+2].split(' ').map(x => +x).sort((a, b) => b-a)\n if (a === c && b+d === a) {\n console.log('Yes')\n } else {\n console.log('No')\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nvar N = null,\n ab = null\n\nfunction loop(line) {\n\n if (line.trim() == \"\")\n return\n\n let cd = line.split(\" \")\n .map(x => parseInt(x,10))\n .sort((x,y) => x-y)\n\n if (ab == null)\n return ab = cd\n\n if (ab[1] == cd[1] && ab[0] + cd[0] == ab[1])\n console.log(\"Yes\")\n else\n console.log(\"No\")\n\n ab = --N == 0 ? rl.close() : null\n\n}\n\nrl.question(\"\", line => {\n N = parseInt(line,10)\n rl.on(\"line\", loop)\n})"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n for (var i = 0; i < n; i++) {\n let arr = [];\n arr.push(readLine()\n .split(' ')\n .map(value => parseInt(value))\n .sort((a, b) => b - a)\n );\n arr.push(readLine()\n .split(' ')\n .map(value => parseInt(value))\n .sort((a, b) => b - a)\n );\n if (arr[0][0] == arr[1][0]) {\n if (arr[0][1] + arr[1][1] == arr[0][0]) {\n console.log('YES');\n } else\n console.log('NO')\n } else console.log('NO');\n }\n}"}], "negative_code": [{"source_code": "var line = readline().split(' ').map((x)=> parseInt(x));\n\nwhile(line[0]--) {\n\t\n\tvar l1 = readline().split(' ').map((x)=> parseInt(x));\n\tvar l2 = readline().split(' ').map((x)=> parseInt(x));\n\n\tif(l1[0]==l2[0])\n\t{\n\t\tif(l1[1]+l2[1] == l1[0])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse if(l1[1]==l2[1])\n\t{\n\t\tif(l1[0]+l2[0] == l1[1])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\n\t\t}\n\t}\n\telse if(l1[1]==l2[0])\n\t{\n\t\tif(l1[0]+l2[1] == l1[1])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse if(l1[0]==l2[1])\n\t{\n\t\tif(l1[1]+l2[0] == l1[0])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse\n\t{\n\n\t\tprint(\"No\");\n\t}\n\n\n}"}, {"source_code": "var line = readline().split(' ').map((x)=> parseInt(x));\n\nwhile(line[0]--) {\n\t\n\tvar l1 = readline().split(' ').map((x)=> parseInt(x));\n\tvar l2 = readline().split(' ').map((x)=> parseInt(x));\n\n\tif(l1[0]==l2[0])\n\t{\n\t\tif(l1[1]+l2[1] == l1[0])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse if(l1[1]==l2[1])\n\t{\n\t\tif(l1[0]+l2[0] == l1[1])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\n\t\t}\n\t}\n\telse if(l1[1]==l2[0])\n\t{\n\t\tif(l1[0]+l2[1] == l1[1])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse if(l1[0]==l2[1])\n\t{\n\t\tif(l1[1]+l2[0] == l1[0])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse\n\t\t\tprint(\"No\");\n\n\n}"}, {"source_code": "var line = readline().split(' ');\n\nwhile(line[0]--) {\n\t\n\tvar l1 = readline().split(' ');\n\tvar l2 = readline().split(' ');\n\n\tif(l1[0]==l2[0])\n\t{\n\t\tif(l1[1]+l2[1] == l1[0])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse if(l1[1]==l2[1])\n\t{\n\t\tif(l1[0]+l2[0] == l1[1])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\n\t\t}\n\t}\n\telse if(l1[1]==l2[0])\n\t{\n\t\tif(l1[0]+l2[1] == l1[1])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse if(l1[0]==l2[1])\n\t{\n\t\tif(l1[1]+l2[0] == l1[0])\n\t\t{\n\t\t\tprint(\"Yes\");\n\t\t\t\n\t\t}\n\t}\n\telse\n\t\t\tprint(\"No\");\n\n\n}"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n for (let i = 0; i < n; i++) {\n const [a, b] = readLine().split(' ').map(x => parseInt(x));\n const [c, d] = readLine().split(' ').map(x => parseInt(x));\n if (Math.sqrt((a*b) + (c*d))%1 ==0){\n console.log('YES')\n } else console.log('NO')\n }\n return;\n}\n"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n for (let i = 0; i < n; i++) {\n const [a, b] = readLine().split(' ').map(x => parseInt(x));\n const [c, d] = readLine().split(' ').map(x => parseInt(x));\n const totalArea = (a*b) + (c*d);\n if (totalArea > 3 && Math.sqrt(totalArea)%1 ==0){\n console.log('YES')\n } else console.log('NO')\n }\n return;\n}\n"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar mae = nextIntArray();\n\t\tvar ato = nextIntArray();\n\t\t\n\t\tif(mae[0] == ato[0] || mae[0] == ato[1] || mae[1] == ato[0] || mae[1] == ato[1]){\n\t\t\tif(mae[0] == ato[0]){\n\t\t\t\tif(mae[1] + ato[1] == mae[0]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}else if(mae[0] == ato[1]){\n\t\t\t\tif(mae[1] + ato[0] == mae[0]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}else if(mae[1] == ato[0]){\n\t\t\t\tif(mae[0] + ato[1] == mae[1]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}else if(mae[1] == ato[1]){\n\t\t\t\tif(mae[0] + ato[0] == mae[1]){\n\t\t\t\t\toutput[i] = \"YES\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(output[i] == null){\n\t\t\t\toutput[i] = \"NO\";\n\t\t\t}\n\t\t}else{\n\t\t\toutput[i] = \"NO\";\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a1, a2, b1, b2;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2) {\n [a1, b1] = d.split(' ').map(Number);\n c++;\n return;\n }\n\n [a2, b2] = d.split(' ').map(Number);\n\n if (a1 + a2 === b1 || a1 + b2 === b1) {\n console.log('YES');\n }\n else if (b1 + a2 === a1 || b1 + b2 === a1) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a1, a2, b1, b2;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2) {\n [a1, b1] = d.split(' ').map(Number);\n c++;\n return;\n }\n\n [a2, b2] = d.split(' ').map(Number);\n\n if (a1 === a2 || a1 === b2) {\n if (b1 + a2 === a1 || b1 + b2 === a1) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n }\n else if (b1 === a2 || b1 === b2) {\n if (a1 + a2 === b1 || a1 + b2 === b1) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n }\n else {\n console.log('NO');\n }\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet count = 0;\nlet a, b, c, d;\n\nfunction sq(a, b, c, d) {\n return (a == c && a == (b + d)) || (a == d && a == (b + c)) || ((b == c && b == (a + d))) || ((b == d && b == (a + c)))\n}\n\nrl.on('line', (data) => {\n if (count === 0) {\n count++;\n tests = +data;\n return;\n }\n\n if (count % 2) {\n [a, b] = data.split(' ').map(Number);\n count++;\n return;\n }\n\n [c, d] = data.split(' ').map(Number);\n\n console.log(sq(a, b, c, d) ? \"YES\" : \"NO\");\n\n count++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet count = 0;\nlet a, b, c, d;\nlet tests = 0;\n\nrl.on('line', (data) => {\n if (count === 0) {\n count++;\n tests = +data;\n return;\n }\n\n if (count % 2) {\n [a, b] = data.split(' ').map(Number);\n count++;\n return;\n }\n\n if (tests === 0) {\n return;\n }\n\n tests--;\n [c, d] = data.split(' ').map(Number);\n\n if (a > b) {\n [a, b] = [b, a];\n }\n\n if (c > d) {\n [c, d] = [d, c];\n }\n\n if (b === d && a + c === b) {\n console.log('YES');\n }\n else {\n console.log('No');\n }\n\n count++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet count = 0;\nlet a, b, c, d;\n\nrl.on('line', (data) => {\n if (count === 0) {\n count++;\n return;\n }\n\n if (count % 2) {\n [a, b] = data.split(' ').map(Number);\n count++;\n return;\n }\n\n [c, d] = data.split(' ').map(Number);\n\n if (a > b) {\n [a, b] = [b, a];\n }\n\n if (c > d) {\n [c, d] = [d, c];\n }\n\n if (b === d && a + c === b) {\n console.log('YES');\n }\n else {\n console.log('No');\n }\n\n count++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a1, a2, b1, b2;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2) {\n [a1, b1] = d.split(' ').map(Number);\n c++;\n return;\n }\n\n [a2, b2] = d.split(' ').map(Number);\n\n if (a1 === a2 || a1 === b2) {\n if (b1 + a2 === a1 || b1 + b2 === a1) {\n console.log('YES');\n }\n else if (a1 + b1 === a2 + b2) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n }\n else if (b1 === a2 || b1 === b2) {\n if (a1 + a2 === b1 || a1 + b2 === b1) {\n console.log('YES');\n }\n else if (a1 + b1 === a2 + b2) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n }\n else {\n console.log('NO');\n }\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a1, a2, b1, b2;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2) {\n [a1, b1] = d.split(' ').map(Number);\n c++;\n return;\n }\n\n [a2, b2] = d.split(' ').map(Number);\n\n if (a1 === a2 || a1 === b2) {\n if (b1 + a2 === a1 || b1 + b2 === a1) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n }\n else if (b1 === a2 || b1 === b2) {\n if (a1 + a2 === b1 || a1 + b2 === b1) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n }\n else {\n if (a1 + b1 === a2 + b2) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n }\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet arr1, arr2;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2) {\n arr1 = d.split(' ').map(Number);\n arr1.sort((a, b) => a - b);\n c++;\n return;\n }\n\n arr2 = d.split(' ').map(Number);\n arr2.sort((a, b) => a - b);\n\n if (arr1[0] + arr2[0] === arr1[1] && arr1[1] === arr2[1]) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n\n\n c++;\n});\n\nrl.on('close', () => {\n\n});\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nfunction dotest(t) {\n rl.question(\"\", ab => {\n ab = ab.split(\" \").map(Number).sort()\n rl.question(\"\", cd => {\n cd = cd.split(\" \").map(Number).sort()\n if (ab[1] == cd[1] && ab[0] + cd[0] == ab[1]) {\n console.log(\"Yes\")\n } else {\n console.log(\"No\")\n }\n t == 1 ? rl.close():dotest(t-1)\n })\n })\n}\n\nrl.question(\"\", t => dotest(Number(t)))\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nvar t = null,\n ab = null\n\nfunction loop(line) {\n\n if (t == null) return t = Number(line)\n\n const cd = line.split(\" \").map(Number).sort()\n\n if (ab == null) {\n ab = cd\n } else {\n if (ab[1] == cd[1] && ab[0] + cd[0] == ab[1])\n console.log(\"Yes\")\n else\n console.log(\"No\")\n if (--t == 0)\n rl.close()\n else\n ab = null\n }\n\n}\n\nrl.on(\"line\", line => loop(line))\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nvar N = null,\n ab = null\n\nfunction loop(line) {\n\n let cd = line.split(\" \").map(Number).sort((x,y) => x-y)\n\n if (ab == null)\n return ab = cd\n\n if (ab[1] == cd[1] && ab[0] + cd[0] == ab[1])\n console.log(\"Yes\")\n else\n console.log(\"No\")\n\n ab = --N == 0 ? rl.close() : null\n\n}\n\nrl.question(\"\", line => {\n N = parseInt(line,10)\n rl.on(\"line\", line => loop(line))\n})\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nfunction dotest(t) {\n rl.question(\"\", ab => {\n ab = ab.split(\" \").map(Number).sort()\n rl.question(\"\", cd => {\n cd = cd.split(\" \").map(Number).sort()\n if (ab[1] != cd[1] || ab[0] == ab[1] || cd[0] == cd[1]) {\n console.log(\"No\")\n } else if (ab[0] + cd[0] == ab[1]) {\n console.log(\"Yes\")\n }\n t == 1 ? rl.close():dotest(t-1)\n })\n })\n}\n\nrl.question(\"\", t => dotest(Number(t)))\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nfunction dotest(t) {\n rl.question(\"\", ab => {\n ab = ab.split(\" \").map(Number).sort()\n rl.question(\"\", cd => {\n cd = cd.split(\" \").map(Number).sort()\n if (ab[0] != ab[1] && cd[0] != cd[1] && ab[1] == cd[1] && (ab[0] + cd[0]) == ab[1]) {\n console.log(\"Yes\")\n } else {\n console.log(\"No\")\n }\n t == 1 ? rl.close():dotest(t-1)\n })\n })\n}\n\nrl.question(\"\", t => dotest(Number(t)))\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nfunction dotest(t) {\n rl.question(\"\", ab => {\n ab = ab.split(\" \").map(Number)\n rl.question(\"\", cd => {\n cd = cd.split(\" \").map(Number)\n if (ab[0] == ab[1] || cd[0] == cd[1]) {\n console.log(\"No\")\n } else {\n let abcd = ab.concat(cd).sort()\n if (abcd[2] == abcd[3] && abcd[0] + abcd[1] == abcd[2])\n console.log(\"Yes\")\n else\n console.log(\"No\")\n }\n t == 1 ? rl.close():dotest(t-1)\n })\n })\n}\n\nrl.question(\"\", t => dotest(Number(t)))\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nfunction dotest(t) {\n rl.question(\"\", ab => {\n ab = ab.split(\" \")//.map(Number).sort()\n a = Number(ab[0])\n b = Number(ab[1])\n rl.question(\"\", cd => {\n cd = cd.split(\" \")//.map(Number).sort()\n c = Number(cd[0])\n d = Number(cd[1])\n if ((a==c && b+d==a) || (a==d && b+c==a) || (b==c && a+d==b) || (b==d && a+c==b)) {\n console.log(\"Yes\")\n } else {\n console.log(\"No\")\n }\n t == 1 ? rl.close():dotest(t-1)\n })\n })\n}\n\nrl.question(\"\", t => dotest(Number(t)))"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nfunction dotest(t) {\n rl.question(\"\", ab => {\n ab = ab.split(\" \").map(Number).sort()\n rl.question(\"\", cd => {\n cd = cd.split(\" \").map(Number).sort()\n if (ab[0] + cd[0] == ab[1] && ab[0] + cd[0] == cd[1]) {\n console.log(\"Yes\")\n } else {\n console.log(\"No\")\n }\n t == 1 ? rl.close():dotest(t-1)\n })\n })\n}\n\nrl.question(\"\", t => dotest(Number(t)))\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nvar t = null,\n ab = null\n\nfunction loop(line) {\n\n if (t == null) return t = Number(line)\n\n const cd = line.split(\" \").map(Number).sort()\n\n if (ab == null) {\n ab = cd\n } else {\n if (ab[1] == cd[1] && ab[0] + cd[0] == ab[1])\n console.log(\"Yes\")\n else\n console.log(\"No\")\n if (--t == 0)\n rl.close()\n else\n ab = null\n console.log(t)\n }\n\n}\n\nrl.on(\"line\", line => loop(line))"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nvar N = null,\n ab = null\n\nfunction loop(line) {\n\n let cd = line.split(\" \")\n .map(x => parseInt(x,10))\n .sort((x,y) => x-y)\n\n if (ab == null)\n return ab = cd\n\n if (ab[1] == cd[1] && ab[0] + cd[0] == ab[1])\n console.log(\"Yes\")\n else\n console.log(\"No\")\n\n ab = --N == 0 ? rl.close() : null\n\n}\n\nrl.question(\"\", line => {\n N = parseInt(line,10)\n rl.on(\"line\", loop)\n})\n"}], "src_uid": "a375dd323b7adbfa9f1cad9aa48f7247"} {"nl": {"description": "You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.", "input_spec": "The first line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \\le c, m, x \\le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time. ", "output_spec": "Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into. ", "sample_inputs": ["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"], "sample_outputs": ["1\n3\n0\n0\n1\n3"], "notes": "NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians. "}, "positive_code": [{"source_code": "\"use strict\";\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nString.prototype.getNumArray = function () {\n return String(this).split(' ').map(function (value) {\n return parseInt(value);\n });\n};\n\nvar n = parseInt(readline());\nvar answers = [];\n\nfor (var i = 0; i < n; i++) {\n var _readline$getNumArray = readline().getNumArray(),\n _readline$getNumArray2 = _slicedToArray(_readline$getNumArray, 3),\n c = _readline$getNumArray2[0],\n m = _readline$getNumArray2[1],\n l = _readline$getNumArray2[2];\n\n var mainMin = c < m ? c : m;\n l += Math.abs(c - m);\n\n if (l >= mainMin) {\n answers.push(mainMin);\n } else {\n var transport = Math.ceil((mainMin - l) / 3);\n answers.push(mainMin - transport);\n }\n}\n\nwrite(answers.join('\\n'));"}, {"source_code": "// c, m, x(코더, 수학자, 쩌리) \nlet lines = ''\n \nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\nprocess.stdin.on('data', input => lines += input)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n lines = lines.split(EOL)\n \n main()\n})\n \nfunction main() {\n const q = lines[0]\n\n for(let i = 0; i < q; i++) {\n const [ c, m, x ] = lines[i + 1].split(/\\s/).map(Number)\n const sum = Math.floor((c + m + x) / 3)\n const min = Math.min(c, m)\n\n console.log(Math.min(sum, min))\n }\n}\n"}], "negative_code": [], "src_uid": "b18dac401b655c06bee331e71eb3e4de"} {"nl": {"description": "Recall that a permutation of length $$$n$$$ is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once.For a fixed positive integer $$$d$$$, let's define the cost of the permutation $$$p$$$ of length $$$n$$$ as the number of indices $$$i$$$ $$$(1 \\le i < n)$$$ such that $$$p_i \\cdot d = p_{i + 1}$$$.For example, if $$$d = 3$$$ and $$$p = [5, 2, 6, 7, 1, 3, 4]$$$, then the cost of such a permutation is $$$2$$$, because $$$p_2 \\cdot 3 = p_3$$$ and $$$p_5 \\cdot 3 = p_6$$$.Your task is the following one: for a given value $$$n$$$, find the permutation of length $$$n$$$ and the value $$$d$$$ with maximum possible cost (over all ways to choose the permutation and $$$d$$$). If there are multiple answers, then print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$) — the number of test cases. The single line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the value $$$d$$$ in the first line, and $$$n$$$ integers in the second line — the permutation itself. If there are multiple answers, then print any of them.", "sample_inputs": ["2\n\n2\n\n3"], "sample_outputs": ["2\n1 2\n3\n2 1 3"], "notes": null}, "positive_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar arr = \"\";\r\nprocess.stdin.on(\"data\", function (chunk) {\r\n arr += chunk;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n arr = arr.split(\"\\n\");\r\n const testcases = parseInt(arr.shift());\r\n\r\n for (let t = 0; t < testcases; t++) {\r\n const n = arr[t].split(\" \").map((el) => parseInt(el));\r\n\r\n const d = 2;\r\n\r\n const set = new Set();\r\n\r\n const res = [1];\r\n\r\n for (let i = 2; i <= n; i++) {\r\n if (!set.has(i)) {\r\n for (let j = i; j <= n; j *= 2) {\r\n if (!set.has(j)) {\r\n res.push(j);\r\n set.add(j);\r\n }\r\n }\r\n }\r\n }\r\n\r\n console.log(d);\r\n console.log(res.join(\" \"));\r\n }\r\n});\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n if (n === 2) {\r\n console.log(2);\r\n console.log(`${1} ${2}`);\r\n continue;\r\n } else {\r\n let res = [],\r\n obj = {};\r\n res[0] = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (!obj[i]) {\r\n obj[i] = 1;\r\n res.push(i);\r\n let k = i * 2;\r\n while (k <= n) {\r\n obj[k] = 1;\r\n res.push(k);\r\n k = k * 2;\r\n }\r\n }\r\n }\r\n console.log(2);\r\n console.log(res.join(\" \"));\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n\r\nvar T = readline();\r\n// var inf = 1000000000000;\r\nfor(var qe=1;qe<=T;qe++) {\r\n var n = readline();\r\n // var [a,b] = readline().split(' ').map((x) => parseInt(x));\r\n console.log(2);\r\n var ans = [], c = []\r\n for(var i=1;i<=n;i++) {\r\n if(c[i] == undefined) {\r\n for(var j=i;j<=n;j*=2) {\r\n ans.push(j);\r\n c[j] = true;\r\n }\r\n }\r\n }\r\n console.log(ans.join(\" \"))\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction main(){\r\n var tests = parseInt(readline());\r\n for (let t = 0;t < tests; ++t) {\r\n let n = parseInt(readline());\r\n let hsh = Array(n+1).fill(false);\r\n let res = [];\r\n for (let j = 1;j <= n;++j) {\r\n if (hsh[j]) {\r\n continue;\r\n }\r\n for (let i = j;i <= n;i*=2) {\r\n hsh[i] = true;\r\n res.push(i);\r\n }\r\n }\r\n console.log(2);\r\n console.log(res.join(' ').toString());\r\n }\r\n\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = readline();\r\n\r\n let used = {};\r\n let smallestNotUsed = 3;\r\n let arr = [1, 2];\r\n let i = 1;\r\n\r\n while (arr.length < n) {\r\n let double = arr[i] * 2;\r\n if (double <= n) {\r\n arr[i + 1] = double;\r\n used[double] = true;\r\n } else {\r\n arr[i + 1] = smallestNotUsed;\r\n used[smallestNotUsed] = true;\r\n let newSmallest = smallestNotUsed + 1;\r\n while (used[newSmallest]) {\r\n newSmallest++;\r\n }\r\n smallestNotUsed = newSmallest;\r\n }\r\n i++;\r\n }\r\n\r\n output(2);\r\n output(arr.join(' '));\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n) {\r\n const res = [],\r\n set = new Set();\r\n for (let i = 1; i <= n; i++) {\r\n if (set.has(i)) continue;\r\n for (let j = i; j <= n; j *= 2) {\r\n res.push(j);\r\n set.add(j);\r\n }\r\n }\r\n return `${2}\\n${res.join(' ')}`;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n res[i] = solve(n);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "var n = +readline();\r\n\r\nwhile (n--) {\r\n\tvar t = +readline();\r\n\tprint(2);\r\n\tvar ans = 1;\r\n\tvar arrCheck = new Array(t + 1);\r\n\tvar mid = parseInt(t / 2);\r\n\tfor (var i = 1; i <= mid; i++) {\r\n\t\tvar ans = i;\r\n\t\twhile (ans <= t && arrCheck[ans] === undefined) {\r\n\t\t\twrite(ans + \" \");\r\n\t\t\tarrCheck[ans] = 1;\r\n\t\t\tans *= 2;\r\n\t\t}\r\n\t}\r\n\tfor (var i = 1; i <= t; i++) {\r\n\t\tif (arrCheck[i] === undefined) write(i, \" \");\r\n\t}\r\n\tprint();\r\n}\r\n"}], "negative_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar arr = \"\";\r\nprocess.stdin.on(\"data\", function (chunk) {\r\n arr += chunk;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n arr = arr.split(\"\\n\");\r\n const testcases = parseInt(arr.shift());\r\n\r\n for (let t = 0; t < testcases; t++) {\r\n const n = arr[t].split(\" \").map((el) => parseInt(el));\r\n\r\n const d = 2;\r\n\r\n const set = new Set();\r\n\r\n const res = [];\r\n\r\n for (let i = 2; i <= n; i++) {\r\n if (!set.has(i)) {\r\n for (let j = i; j <= n; j *= 2) {\r\n if (!set.has(j)) {\r\n res.push(j);\r\n set.add(j);\r\n }\r\n }\r\n }\r\n }\r\n\r\n console.log(d);\r\n console.log(res.join(\" \"));\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar arr = \"\";\r\nprocess.stdin.on(\"data\", function (chunk) {\r\n arr += chunk;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n arr = arr.split(\"\\n\");\r\n const testcases = parseInt(arr.shift());\r\n\r\n for (let t = 0; t < testcases; t++) {\r\n const n = arr[t].split(\" \").map((el) => parseInt(el));\r\n\r\n const d = 2;\r\n\r\n const set = new Set();\r\n\r\n const res = [];\r\n\r\n for (let i = 1; i <= n; i = i * 2) {\r\n res.push(i);\r\n set.add(i);\r\n }\r\n\r\n for (let i = 1; i <= parseInt(n / 2); i++) {\r\n if (!set.has(i)) {\r\n res.push(i);\r\n res.push(i * 2);\r\n set.add(i);\r\n set.add(i * 2);\r\n } else {\r\n set.add(i * 2);\r\n }\r\n }\r\n\r\n for (let i = parseInt(n / 2); i <= n; i++) {\r\n if (!set.has(i)) res.push(i);\r\n }\r\n\r\n console.log(d);\r\n console.log(res.join(\" \"));\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar arr = \"\";\r\nprocess.stdin.on(\"data\", function (chunk) {\r\n arr += chunk;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n arr = arr.split(\"\\n\");\r\n const testcases = parseInt(arr.shift());\r\n\r\n for (let t = 0; t < testcases; t++) {\r\n const n = arr[t].split(\" \").map((el) => parseInt(el));\r\n\r\n const d = 2;\r\n\r\n const set = new Set();\r\n\r\n const res = [];\r\n\r\n for (let i = 1; i <= n; i = i * 2) {\r\n res.push(i);\r\n set.add(i);\r\n }\r\n\r\n for (let i = 1; i <= n; i++) {\r\n if (!set.has(i)) res.push(i);\r\n }\r\n\r\n console.log(d);\r\n console.log(res.join(\" \"));\r\n }\r\n});\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n if (n === 2) {\r\n console.log(2);\r\n console.log(`${1} ${2}`);\r\n continue;\r\n } else {\r\n let res = [],\r\n obj = {};\r\n res[0] = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (!obj[i]) {\r\n obj[i] = 1;\r\n res.push(i);\r\n if (i * 2 <= n) {\r\n obj[i * 2] = 1;\r\n res.push(i * 2);\r\n }\r\n }\r\n }\r\n console.log(2);\r\n console.log(res.join(\" \"));\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n\r\nvar T = readline();\r\n// var inf = 1000000000000;\r\nfor(var qe=1;qe<=T;qe++) {\r\n var n = readline();\r\n // var [a,b] = readline().split(' ').map((x) => parseInt(x));\r\n console.log(2);\r\n var ans = [], c = []\r\n for(var i=1;i<=n;i*=2) {\r\n ans.push(i);\r\n c[i] = true;\r\n }\r\n for(var i=3;i<=n;i++) {\r\n if(c[i] == undefined) ans.push(i)\r\n }\r\n console.log(ans.join(\" \"))\r\n}\r\n"}, {"source_code": "var n = +readline();\r\n\r\nwhile (n--) {\r\n\tvar t = +readline();\r\n\tprint(2);\r\n\tvar ans = 1;\r\n\tvar arrCheck = new Array(t + 1);\r\n\tvar mid = parseInt(t / 2);\r\n\tfor (var i = 1; i <= mid; i++) {\r\n\t\tvar ans = i;\r\n\t\twhile (ans <= t && arrCheck[ans] === undefined) {\r\n\t\t\twrite(ans + \" \");\r\n\t\t\tarrCheck[ans] = 1;\r\n\t\t\tans *= 2;\r\n\t\t}\r\n\t}\r\n\tif (t % 2) write(t + \" \");\r\n\tprint();\r\n}\r\n"}, {"source_code": "var n = +readline();\r\n\r\nwhile (n--) {\r\n\tvar t = +readline();\r\n\tprint(2);\r\n\tvar ans = 1;\r\n\tvar arrCheck = new Array(t + 1);\r\n\twhile (ans <= t) {\r\n\t\twrite(ans + \" \");\r\n\t\tarrCheck[ans] = 1;\r\n\t\tans *= 2;\r\n\t}\r\n\r\n\tfor (var i = 3; i <= t; i++) {\r\n\t\tif (arrCheck[i] === undefined) write(i + \" \");\r\n\t}\r\n\r\n\tprint();\r\n}\r\n"}], "src_uid": "3b9380ca571dbf3e24fc1b1c8b91790b"} {"nl": {"description": "Let's call left cyclic shift of some string $$$t_1 t_2 t_3 \\dots t_{n - 1} t_n$$$ as string $$$t_2 t_3 \\dots t_{n - 1} t_n t_1$$$.Analogically, let's call right cyclic shift of string $$$t$$$ as string $$$t_n t_1 t_2 t_3 \\dots t_{n - 1}$$$.Let's say string $$$t$$$ is good if its left cyclic shift is equal to its right cyclic shift.You are given string $$$s$$$ which consists of digits 0–9.What is the minimum number of characters you need to erase from $$$s$$$ to make it good?", "input_spec": "The first line contains single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test cases — one per line. The first and only line of each test case contains string $$$s$$$ ($$$2 \\le |s| \\le 2 \\cdot 10^5$$$). Each character $$$s_i$$$ is digit 0–9. It's guaranteed that the total length of strings doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the minimum number of characters you need to erase from $$$s$$$ to make it good.", "sample_inputs": ["3\n95831\n100120013\n252525252525"], "sample_outputs": ["3\n5\n0"], "notes": "NoteIn the first test case, you can erase any $$$3$$$ characters, for example, the $$$1$$$-st, the $$$3$$$-rd, and the $$$4$$$-th. You'll get string 51 and it is good.In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good.In the third test case, the given string $$$s$$$ is already good."}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const str = readLine();\n let ans = 0;\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n let count = 0;\n for (let k = 0; k < str.length; k++) {\n if (count % 2 === 0 && +str[k] === i) {\n count++;\n } else if (count % 2 !== 0 && +str[k] === j) {\n count++;\n }\n }\n if (i !== j && count % 2 !== 0) {\n count = count - 1;\n }\n ans = Math.max(ans, count);\n }\n }\n console.log(`${str.length - ans}`);\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n C(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = parseInt(a[i]);\n\n return a;\n}\n\nfunction B(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n let [n,k,z] = ti(readline().split(' '));\n let a = ti(readline().split(' '));\n\n let solve = (i, k, z) => {\n if(k < 0 || z < 0)\n return 0;\n\n if(i < 0 || i >= n)\n return 0;\n \n let right = a[i] + solve(i+1, k-1, z);\n let left = a[i] + solve(i-1, k-1, z-1);\n\n return Math.max(left, right);\n }\n\n console.log(solve(0, k, z));\n }\n}\n\nfunction C(){\n let t = parseInt(readline());\n\n while(t > 0){\n t--;\n let max = 0;\n let s = readline();\n\n for(let i = 0; i < 10; i++){\n for(let j = i; j < 10; j++){\n let pre = -1;\n let len = 0;\n for(let k = 0; k < s.length; k++){\n if(i === j){\n if(parseInt(s.charAt(k)) === i){\n len += 1;\n }\n }else{\n if(parseInt(s.charAt(k)) === i){\n if(pre !== i){\n len += 1;\n pre = i;\n }\n }else if(parseInt(s.charAt(k)) === j){\n if(pre != j){\n len += 1;\n pre = j;\n }\n }\n }\n }\n\n if(i !== j && len % 2 !== 0)\n len -= 1;\n \n max = Math.max(max, len);\n }\n }\n\n console.log(s.length - max);\n }\n}\n\nfunction main(){\n let [n,k] = ti(readline().split(' '));\n let w = new Array(n);\n let v = new Array(n);\n\n for(let i = 0; i < n; i++){\n let [x,y] = ti(readline().split(' '));\n w[i] = x;\n v[i] = y;\n }\n\n let dp = new Array(n);\n for(let i = 0; i < n; i++){\n dp[i] = new Array(100001);\n dp[i].fill(99999999999);\n }\n\n for(let i = 0; i < n; i++){\n for(let j = 0; j < 100001; j++){\n if(i === 0 || j === 0){\n if(i === 0 && j === 0)\n dp[i][j] = 0;\n else if(i === 0)\n dp[i][j] = v[0] === j ? w[0] : 99999999999;\n }else{\n dp[i][j] = dp[i-1][j];\n if(j >= v[i])\n dp[i][j] = Math.min(dp[i][j], w[i] + dp[i-1][j-v[i]]);\n }\n }\n }\n\n let max = 0;\n for(let i = 100000; i >= 0; i--){\n if(dp[n-1][i] <= k){\n max = i;\n break;\n }\n }\n\n console.log(max);\n}"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const str = readLine();\n let ans = 0;\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n let count = 0;\n for (let k = 0; k < str.length; k++) {\n if (k % 2 === 0 && +str[k] === i) {\n count++;\n } else if (k % 2 !== 0 && +str[k] === j) {\n count++;\n }\n }\n if (i !== j) {\n count -= count % 2;\n ans = Math.max(ans, count);\n }\n }\n }\n console.log(`${str.length - ans}`);\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const str = readLine();\n let ans = 0;\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n let count = 0;\n for (let k = 0; k < str.length; k++) {\n if (k % 2 === 0 && +str[k] === i) {\n count++;\n } else if (k % 2 !== 0 && +str[k] === j) {\n count++;\n }\n }\n if (i !== j) {\n count -= count % 2;\n }\n ans = Math.max(ans, count);\n }\n }\n console.log(`${str.length - ans}`);\n }\n}\n"}], "src_uid": "977db81b5c1d3725e384e8f093655172"} {"nl": {"description": "Diamond Miner is a game that is similar to Gold Miner, but there are $$$n$$$ miners instead of $$$1$$$ in this game.The mining area can be described as a plane. The $$$n$$$ miners can be regarded as $$$n$$$ points on the y-axis. There are $$$n$$$ diamond mines in the mining area. We can regard them as $$$n$$$ points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point $$$(0, 0)$$$). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $$$(a,b)$$$ uses his hook to mine a diamond mine at the point $$$(c,d)$$$, he will spend $$$\\sqrt{(a-c)^2+(b-d)^2}$$$ energy to mine it (the distance between these points). The miners can't move or help each other.The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum?", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 10$$$) — 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$$$) — the number of miners and mines. Each of the next $$$2n$$$ lines contains two space-separated integers $$$x$$$ ($$$-10^8 \\le x \\le 10^8$$$) and $$$y$$$ ($$$-10^8 \\le y \\le 10^8$$$), which represent the point $$$(x,y)$$$ to describe a miner's or a diamond mine's position. Either $$$x = 0$$$, meaning there is a miner at the point $$$(0, y)$$$, or $$$y = 0$$$, meaning there is a diamond mine at the point $$$(x, 0)$$$. There can be multiple miners or diamond mines at the same point. It is guaranteed that no point is at the origin. It is guaranteed that the number of points on the x-axis is equal to $$$n$$$ and the number of points on the y-axis is equal to $$$n$$$. It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single real number — the minimal sum of energy that should be spent. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. 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^{-9}$$$.", "sample_inputs": ["3\n2\n0 1\n1 0\n0 -1\n-2 0\n4\n1 0\n3 0\n-5 0\n6 0\n0 3\n0 1\n0 2\n0 4\n5\n3 0\n0 4\n0 -3\n4 0\n2 0\n1 0\n-3 0\n0 -10\n0 -2\n0 -10"], "sample_outputs": ["3.650281539872885\n18.061819283610362\n32.052255376143336"], "notes": "NoteIn the first test case, the miners are at $$$(0,1)$$$ and $$$(0,-1)$$$, while the diamond mines are at $$$(1,0)$$$ and $$$(-2,0)$$$. If you arrange the miners to get the diamond mines in the way, shown in the picture, you can get the sum of the energy $$$\\sqrt2 + \\sqrt5$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = BigInt(1e9 + 7);\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let min = [],\r\n dia = [];\r\n for (let i = 0; i < n * 2; i++) {\r\n let k = iInpArr();\r\n if (k[0] === 0) min.push([k[0], Math.abs(k[1])]);\r\n else dia.push([Math.abs(k[0]), k[1]]);\r\n }\r\n min.sort((a, b) => a[1] - b[1]);\r\n dia.sort((a, b) => a[0] - b[0]);\r\n let sum = 0;\r\n for (let i = 0; i < n; i++) {\r\n let k = min[i][1] * min[i][1] + dia[i][0] * dia[i][0];\r\n sum += Math.sqrt(k);\r\n }\r\n console.log(sum + \"\");\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "const mineAllDays = (miners, diamonds) => {\n let res = 0;\n for (let i = 0; i < miners.length; i++) {\n res += Math.sqrt(miners[i] ** 2 + diamonds[i] ** 2);\n }\n return res;\n};\n\nconst main = () => {\n let test = readInt();\n while (test--) {\n const miners = [];\n const diamonds = [];\n const n = readInt();\n for (let i = 0; i < 2 * n; i++) {\n const [x, y] = readListInt();\n if (x === 0) miners.push(Math.abs(y));\n else diamonds.push(Math.abs(x));\n }\n miners.sort((a, b) => a - b);\n diamonds.sort((a, b) => a - b);\n console.log(mineAllDays(miners, diamonds));\n }\n};\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", () => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map(string => string.trim());\n main();\n});\n\nconst readLine = () => {\n return inputString[currentLine++];\n};\n\nconst readInt = () => {\n return parseInt(inputString[currentLine++]);\n};\n\nconst readListInt = () => {\n return inputString[currentLine++].split(\" \").map(s => parseInt(s));\n};\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar alist = [];\r\n\t\tvar blist = [];\r\n\t\tfor(var j = 0; j < 2 * N; j++){\r\n\t\t\tvar x = nextInt();\r\n\t\t\tvar y = nextInt();\r\n\t\t\tif(x != 0){\r\n\t\t\t\tblist.push({\r\n\t\t\t\t\tx : x,\r\n\t\t\t\t\ty : y\r\n\t\t\t\t});\r\n\t\t\t}else{\r\n\t\t\t\talist.push({\r\n\t\t\t\t\tx : x,\r\n\t\t\t\t\ty : y\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t\talist.sort(function(a,b){\r\n\t\t\treturn Math.abs(a.y) - Math.abs(b.y);\r\n\t\t});\r\n\t\tblist.sort(function(a,b){\r\n\t\t\treturn Math.abs(a.x) - Math.abs(b.x);\r\n\t\t});\r\n\t\tvar sum = 0;\r\n\t\t\r\n\t\tfor(var j = 0; j < N; j++){\r\n\t\t\tsum += Math.sqrt(alist[j].y * alist[j].y + blist[j].x * blist[j].x);\r\n\t\t}\r\n\t\tmyout(sum);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n var n = parseInt(readline())\r\n // var a = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // })\r\n\r\n var x = []\r\n var y = []\r\n for (let i = 0; i < 2 * n; i++) {\r\n var [xx, yy] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n if (xx === 0) y.push(yy)\r\n if (yy === 0) x.push(xx)\r\n }\r\n x = x.sort((a, b) => Math.abs(a) - Math.abs(b))\r\n y = y.sort((a, b) => Math.abs(a) - Math.abs(b))\r\n // console.log(x)\r\n // console.log(y)\r\n var sum = 0\r\n for (let i = 0; i < n; i++) {\r\n sum += Math.sqrt(x[i] * x[i] + y[i] * y[i])\r\n }\r\n console.log(sum)\r\n\r\n })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar alist = [];\r\n\t\tvar blist = [];\r\n\t\tfor(var j = 0; j < 2 * N; j++){\r\n\t\t\tvar x = nextInt();\r\n\t\t\tvar y = nextInt();\r\n\t\t\tif(x != 0){\r\n\t\t\t\tblist.push({\r\n\t\t\t\t\tx : x,\r\n\t\t\t\t\ty : y\r\n\t\t\t\t});\r\n\t\t\t}else{\r\n\t\t\t\talist.push({\r\n\t\t\t\t\tx : x,\r\n\t\t\t\t\ty : y\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t\talist.sort(function(a,b){\r\n\t\t\treturn Math.abs(a.y) - Math.abs(b.y);\r\n\t\t});\r\n\t\tblist.sort(function(a,b){\r\n\t\t\treturn Math.abs(a.x) - Math.abs(b.x);\r\n\t\t});\r\n\t\tvar sum = 0;\r\n\t\t\r\n\t\tfor(var j = 0; j < N; j++){\r\n\t\t\tsum += Math.sqrt(alist[j].y * alist[j].y + blist[j].x * blist[j].x);\r\n\t\t}\r\n\t\tmyout(sum);\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "ba27ac62b84705d80fa580567ab64c3b"} {"nl": {"description": "There are $$$n$$$ piranhas with sizes $$$a_1, a_2, \\ldots, a_n$$$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely: The piranha $$$i$$$ can eat the piranha $$$i-1$$$ if the piranha $$$i-1$$$ exists and $$$a_{i - 1} < a_i$$$. The piranha $$$i$$$ can eat the piranha $$$i+1$$$ if the piranha $$$i+1$$$ exists and $$$a_{i + 1} < a_i$$$. When the piranha $$$i$$$ eats some piranha, its size increases by one ($$$a_i$$$ becomes $$$a_i + 1$$$).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if $$$a = [5, 3, 4, 4, 5]$$$, then the third piranha can be dominant. Consider the sequence of its moves: The piranha eats the second piranha and $$$a$$$ becomes $$$[5, \\underline{5}, 4, 5]$$$ (the underlined piranha is our candidate). The piranha eats the third piranha and $$$a$$$ becomes $$$[5, \\underline{6}, 5]$$$. The piranha eats the first piranha and $$$a$$$ becomes $$$[\\underline{7}, 5]$$$. The piranha eats the second piranha and $$$a$$$ becomes $$$[\\underline{8}]$$$. 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$$$) — 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 3 \\cdot 10^5$$$) — the number of piranhas in the aquarium. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the size of the $$$i$$$-th piranha. It is guaranteed that the sum of $$$n$$$ does not exceed $$$3 \\cdot 10^5$$$ ($$$\\sum n \\le 3 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer: -1 if there are no dominant piranhas in the aquarium or index of any dominant piranha otherwise. If there are several answers, you can print any.", "sample_inputs": ["6\n5\n5 3 4 4 5\n3\n1 1 1\n5\n4 4 3 4 4\n5\n5 5 4 3 2\n3\n1 1 2\n5\n5 4 3 5 5"], "sample_outputs": ["3\n-1\n4\n3\n3\n1"], "notes": "NoteThe first test case of the example is described in the problem statement.In the second test case of the example, there are no dominant piranhas in the aquarium.In the third test case of the example, the fourth piranha can firstly eat the piranha to the left and the aquarium becomes $$$[4, 4, 5, 4]$$$, then it can eat any other piranha in the aquarium."}, "positive_code": [{"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nconst print = console.log\nconst lines = []\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nlet mem = new Map();\nfunction query(arr){\n let max_i = 0, min_i = 0;\n for (let i=0; i arr[i] ? i : min_i;\n }\n if (max_i==min_i)\n return -1;\n for (let i=0; i+a);\n print(query(arr));\n }\n}\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet lineNum = 0;\nlet countOfData = null;\nlet data = [];\nreadline.on('line', line => {\n lineNum++;\n if(lineNum === 1) {\n countOfData = +line * 2;\n return;\n }\n\n data.push(line);\n \n if(lineNum - 1 === countOfData) {\n goToSolution(data);\n }\n \n});\n\nfunction goToSolution(data) { \n data.forEach((piranhas, i) => {\n if(i % 2 !== 0) {\n const splitted = piranhas.split(' ');\n const sorted = splitted.map((piranha, i) => [+piranha, i])\n .sort((a, b) => b[0] - a[0]);\n\n for(let i = 0; i < sorted.length && sorted[i][0] == sorted[0][0]; i++) {\n const cur = sorted[i][0];\n const left = splitted[sorted[i][1] - 1];\n const right = splitted[sorted[i][1] + 1];\n if(left < cur || right < cur) {\n console.log(sorted[i][1] + 1)\n return;\n }\n }\n\n console.log(-1)\n }\n })\n}\n\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n const arr = readLine().split(\" \").map(Number);\n let [max, maxIndex, allSame] = [-Infinity, 0, true];\n\n for (let i = 1; i < len; i++) {\n const [curr, prev] = [arr[i], arr[i - 1]];\n const diff = Math.abs(curr - prev);\n if (diff !== 0) {\n allSame = false;\n if (curr > prev && curr > max) {\n max = curr;\n maxIndex = i;\n } else if (prev > curr && prev > max) {\n max = prev;\n maxIndex = i - 1;\n }\n }\n }\n if (allSame) console.log(-1);\n else {\n console.log(maxIndex + 1);\n }\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = nextInt();\n\t\tvar list = nextIntArray();\n\t\tvar isOK = true;\n\t\tvar max = 0;\n\t\tvar maxIndex = -1;\n\t\tfor(var j = 0; j < N - 1; j++){\n\t\t\tif(list[j] != list[j + 1]){\n\t\t\t\tisOK = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(isOK){\n\t\t\toutput[i] = -1;\n\t\t\tcontinue;\n\t\t}\n\t\tfor(var j = 0; j < N; j++){\n\t\t\tif(j == 0){\n\t\t\t\tif(max < list[j] && list[j] != list[j + 1]){\n\t\t\t\t\tmax = list[j];\n\t\t\t\t\tmaxIndex = j + 1;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(j == N - 1){\n\t\t\t\tif(max < list[j] && list[j] != list[j - 1]){\n\t\t\t\t\tmax = list[j];\n\t\t\t\t\tmaxIndex = j + 1;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif((list[j] != list[j + 1] || list[j] != list[j - 1]) && max < list[j]){\n\t\t\t\tmax = list[j];\n\t\t\t\tmaxIndex = j + 1;\n\t\t\t}\n\t\t}\n\t\toutput[i] = maxIndex;\n\t}\n\tmyout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n})\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n})\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 2;\n let i = 1;\n while (i <= testCases) {\n // let a = data[i].trim();\n // const n = data[i] * 1;\n // const k = a[1];\n const s = data[i + 1].trim().split(' ').map(Number);\n // s.sort((a, b) => b - a);\n let idx = 0;\n let max = 0;\n let obj = {};\n \n for (let j = 0; j < s.length; j += 1) {\n if (obj[s[j]]) obj[s[j]].push(j);\n else obj[s[j]] = [j];\n if (s[j] > max) {\n max = s[j];\n idx = j;\n }\n }\n // console.log(obj, obj[max]);\n \n let j = 0;\n idx = -1\n // console.log(idx, 'idx', max)\n for (; j < obj[max].length; j += 1) {\n let x = obj[max][j];\n if (s[x + 1] && s[x + 1] < s[x]) {\n idx = x + 1;\n // console.log(j,'j');\n break;\n \n } else if (s[x - 1] && s[x - 1] < s[x]) {\n idx = x + 1;\n // console.log(j,'ej');\n break;\n }\n }\n \n console.log(idx);\n i += 2;\n }\n}"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a)return i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),void(o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{u+=t})),process.stdin.on(\"end\",(e=>{i=u.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return i[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}, {"source_code": "var t = parseInt(readline());\n\nwhile (t--) {\n var n = parseInt(readline());\n var ar = readline().split(' ').map(function(x, index) {\n // print(\"index: \" + index + \" val: \" + x);\n return parseInt(x);\n });\n var same = 1;\n for (var i = 1; i < ar.length; ++i) if (ar[0] !== ar[i]) same = 0;\n if (same) {\n print(\"-1\");\n continue;\n }\n\n var ans = -1;\n var big = ar[0];\n\n for (var i = 1; i < ar.length; ++i) if (ar[i] > big) big = ar[i];\n\n for (var i = 0; i < ar.length; ++i) {\n if (i - 1 >= 0 && ar[i] === big && ar[i-1] < ar[i]) {\n ans = i + 1;\n break;\n }\n if (i + 1 < ar.length && ar[i] === big && ar[i+1] < ar[i]) {\n ans = i + 1;\n break;\n }\n }\n\n print(ans);\n\n // ar.forEach(function(val) {\n // print(val[0] + ' -> ' + val[1]);\n // });\n}\n"}, {"source_code": "// your code goes here\nvar t = parseInt(readline());\nfor (var x = 0; x < t; ++x) {\n\tvar n = parseInt(readline());\n\tvar a = readline().split(' ').map(x => parseInt(x));\n\tvar mx = 0;\n\tfor (var i = 0; i < n; ++i) {\n\t\tif (a[i] > mx) {\n\t\t\tmx = a[i];\n\t\t}\n\t}\n\tvar ind = -2;\n\tfor (var i = 0; i < n; ++i) {\n\t\tif (a[i] == mx) {\n\t\t\tif (i > 0 && a[i - 1] < mx) {\n\t\t\t\tind = i;\n\t\t\t\tbreak;\n\t\t\t} else if (i < n - 1 && a[i + 1] < mx) {\n\t\t\t\tind = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprint(ind + 1);\n}"}], "negative_code": [{"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a)return i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),void(o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{u+=t})),process.stdin.on(\"end\",(e=>{i=u.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return i[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){return Math.max(...this)},Array.prototype.min=function(){return Math.min(...this)},Array.prototype.sum=function(){let t=0;for(let e=0;e{if(a)return i=u.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),u.default.writeFileSync(\"output.txt\",l),console.log(l),void(u.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{o+=t})),process.stdin.on(\"end\",(e=>{i=o.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return i[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var u=e[n]={exports:{}};return t[n].call(u.exports,u,u.exports,r),u.exports}(965)})();"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){return Math.max(...this)},Array.prototype.min=function(){return Math.min(...this)},Array.prototype.sum=function(){let t=0;for(let e=0;e{if(a)return i=u.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),u.default.writeFileSync(\"output.txt\",l),console.log(l),void(u.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{o+=t})),process.stdin.on(\"end\",(e=>{i=o.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return i[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var u=e[n]={exports:{}};return t[n].call(u.exports,u,u.exports,r),u.exports}(965)})();"}, {"source_code": "var t = parseInt(readline());\n\nwhile (t--) {\n var n = parseInt(readline());\n var ar = readline().split(' ').map(function(x, index) {\n // print(\"index: \" + index + \" val: \" + x);\n return [parseInt(x), index + 1];\n });\n var same = 1;\n for (var i = 1; i < ar.length; ++i) if (ar[0][0] !== ar[i][0]) same = 0;\n if (same) {\n print(\"-1\");\n continue;\n }\n\n ar.sort(function(v1, v2) {\n if (v1[0] < v2[0]) return 1;\n return -1;\n });\n\n print(ar[0][1]);\n\n // ar.forEach(function(val) {\n // print(val[0] + ' -> ' + val[1]);\n // });\n}\n"}, {"source_code": "// your code goes here\nvar t = +readline();\nfor (var x = 0; x < t; ++x) {\n\tvar n = +readline();\n\tvar a = readline().split(' ');\n\tvar mx = 0;\n\tfor (var i = 0; i < n; ++i) {\n\t\tif (a[i] > mx) {\n\t\t\tmx = a[i];\n\t\t}\n\t}\n\tvar ind = -2;\n\tfor (var i = 0; i < n; ++i) {\n\t\tif (a[i] == mx) {\n\t\t\tif (i > 0 && a[i - 1] < mx) {\n\t\t\t\tind = i;\n\t\t\t\tbreak;\n\t\t\t} else if (i < n - 1 && a[i + 1] < mx) {\n\t\t\t\tind = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprint(ind + 1);\n}"}, {"source_code": "// your code goes here\nvar t = parseInt(readline());\nfor (var x = 0; x < t; ++x) {\n\tvar n = parseInt(readline());\n\tvar a = readline().split(' ').map(x => parseInt(x));\n\tvar mx = 0;\n\tfor (var i = 0; i < n; ++i) {\n\t\tif (a[i] > mx) {\n\t\t\tmx = a[i];\n\t\t}\n\t}\n\tprint(mx);\n\tvar ind = -2;\n\tfor (var i = 0; i < n; ++i) {\n\t\tif (a[i] == mx) {\n\t\t\tif (i > 0 && a[i - 1] < mx) {\n\t\t\t\tind = i;\n\t\t\t\tbreak;\n\t\t\t} else if (i < n - 1 && a[i + 1] < mx) {\n\t\t\t\tind = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprint(ind + 1);\n}"}], "src_uid": "5598d5954fa3e3cecedb413033259760"} {"nl": {"description": "A tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to at most one vertex.The gardener Vitaly grew a tree from $$$n$$$ vertices. He decided to trim the tree. To do this, he performs a number of operations. In one operation, he removes all leaves of the tree. Example of a tree. For example, consider the tree shown in the figure above. The figure below shows the result of applying exactly one operation to the tree. The result of applying the operation \"remove all leaves\" to the tree. Note the special cases of the operation: applying an operation to an empty tree (of $$$0$$$ vertices) does not change it; applying an operation to a tree of one vertex removes this vertex (this vertex is treated as a leaf); applying an operation to a tree of two vertices removes both vertices (both vertices are treated as leaves). Vitaly applied $$$k$$$ operations sequentially to the tree. How many vertices remain?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. Each test case consists of several lines. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 4 \\cdot 10^5$$$, $$$1 \\le k \\le 2 \\cdot 10^5$$$) — the number of vertices in the tree and the number of operations, respectively. Then $$$n - 1$$$ lines follow, each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges. It is guaranteed that the sum of $$$n$$$ from all test cases does not exceed $$$4 \\cdot 10^5$$$.", "output_spec": "For each test case output on a separate line a single integer — the number of vertices that remain in the tree after applying $$$k$$$ operations.", "sample_inputs": ["6\n\n14 1\n1 2\n2 3\n2 4\n4 5\n4 6\n2 7\n7 8\n8 9\n8 10\n3 11\n3 12\n1 13\n13 14\n\n2 200000\n1 2\n\n3 2\n1 2\n2 3\n\n5 1\n5 1\n3 2\n2 1\n5 4\n\n6 2\n5 1\n2 5\n5 6\n4 2\n3 4\n\n7 1\n4 3\n5 1\n1 3\n6 1\n1 7\n2 1"], "sample_outputs": ["7\n0\n0\n3\n1\n2"], "notes": "NoteThe first test case is considered in the statement.The second test case contains a tree of two vertices. $$$200000$$$ operations are applied to it. The first one removes all two vertices, the other operations do not change the tree.In the third test case, a tree of three vertices is given. As a result of the first operation, only $$$1$$$ vertex remains in it (with the index $$$2$$$), the second operation makes the tree empty."}, "positive_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n // if (t === 6) {\n // console.log([7, 0, 0, 3, 1, 2].join('\\n'))\n // return\n // }\n const output = []\n for (let i = 0; i < t; i++) {\n l++\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, edges))\n // output[i] = solve(n, k, edges)\n }\n // console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, edges) {\n if (n === 1) return 0\n // console.log(edges)\n const adj = {}\n const d = []\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n d[a] = (d[a] || 0) + 1\n d[b] = (d[b] || 0) + 1\n })\n\n let q = []\n for (let u = 1; u <= n; u++) {\n if (d[u] === 1) q.push(u)\n }\n// console.log(d)\n let ans = n\n const visited = {}\n for (let i = 0; i < k; i++) {\n const next = []\n for (let j = 0; j < q.length; j++) {\n const u = q[j]\n if (visited[u]) continue\n visited[u] = 1\n ans--\n\n (adj[u] || []).forEach(v => {\n if (!visited[v] && --d[v] === 1) {\n next.push(v)\n }\n })\n }\n q = next\n if (!q.length) break\n }\n return ans\n}\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n // console.log(...args);\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INF = Number.MAX_SAFE_INTEGER;\r\nconst INIT = -1;\r\nlet n;\r\nlet k;\r\nlet adjList;\r\nlet ld;\r\nfunction diam() {\r\n let dist = af(n + 1).fill(INIT);\r\n dist[1] = 0;\r\n let q = [1];\r\n for (let i = 0; i < q.length; i++) {\r\n let u = q[i];\r\n for (let v of adjList[u]) {\r\n if (dist[v] == INIT) {\r\n dist[v] = dist[u] + 1;\r\n q.push(v);\r\n }\r\n }\r\n }\r\n let s = INIT;\r\n let mx = INIT;\r\n for (let u = 1; u <= n; u++) {\r\n if (mx < dist[u]) {\r\n mx = dist[u];\r\n s = u;\r\n }\r\n }\r\n check(s != INIT);\r\n const p = af(n + 1).fill(INIT);\r\n dist.fill(INIT);\r\n dist[s] = 0;\r\n q = [s];\r\n for (let i = 0; i < q.length; i++) {\r\n let u = q[i];\r\n for (let v of adjList[u]) {\r\n if (dist[v] == INIT) {\r\n dist[v] = dist[u] + 1;\r\n p[v] = u;\r\n q.push(v);\r\n }\r\n }\r\n }\r\n let t = INIT;\r\n mx = INIT;\r\n for (let u = 1; u <= n; u++) {\r\n if (mx < dist[u]) {\r\n mx = dist[u];\r\n t = u;\r\n }\r\n }\r\n check(t != INIT);\r\n const rv = [t];\r\n for (let i = 0; i < mx; i++) {\r\n rv.push(p[t]);\r\n t = p[t];\r\n }\r\n return rv;\r\n}\r\nfunction getLd(s, ex) {\r\n const dist = af(n + 1).fill(INIT);\r\n const p = af(n + 1).fill(INIT);\r\n if (ex != INIT) {\r\n dist[ex] = 0;\r\n }\r\n dist[s] = 0;\r\n const q = [s];\r\n const topo = [];\r\n for (let i = 0; i < q.length; i++) {\r\n let u = q[i];\r\n for (let v of adjList[u]) {\r\n if (dist[v] == INIT) {\r\n dist[v] = dist[u] + 1;\r\n p[v] = u;\r\n q.push(v);\r\n }\r\n }\r\n topo.push(u);\r\n }\r\n for (let i = topo.length - 1; i > 0; i--) {\r\n let u = topo[i];\r\n ld[p[u]] = Math.max(ld[p[u]], ld[u] + 1);\r\n }\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n k = nextInt();\r\n adjList = Array.from({ length: n + 1 });\r\n for (let i = 0; i <= n; i++) {\r\n adjList[i] = [];\r\n }\r\n for (let i = 0; i + 1 < n; i++) {\r\n let u = nextInt();\r\n let v = nextInt();\r\n adjList[u].push(v);\r\n adjList[v].push(u);\r\n }\r\n // for (let u = 1; u <= n; u++) {\r\n // for (let v of adjList[u]) {\r\n // if (u > v) continue;\r\n // console.log('u %d v %d', u, v);\r\n // }\r\n // }\r\n const path = diam();\r\n let pathlen = path.length;\r\n ld = af(n + 1).fill(0);\r\n if ((pathlen % 2) == 0) {\r\n let r1 = path[Math.trunc(pathlen / 2)];\r\n let r2 = path[Math.trunc(pathlen / 2) - 1];\r\n getLd(r1, r2);\r\n getLd(r2, r1);\r\n }\r\n else {\r\n let root = path[Math.trunc(pathlen / 2)];\r\n getLd(root, INIT);\r\n }\r\n let ans = 0;\r\n for (let u = 1; u <= n; u++) {\r\n if (ld[u] >= k) {\r\n ans++;\r\n }\r\n }\r\n printf(\"%d\\n\", ans);\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n//const util = require('util');\r\n//process.stdin.resume();\r\n//process.stdin.setEncoding('ascii');\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\n// function printf(...args: [...T]) {\r\n// process.stdout.write(util.format(...args));\r\n// // console.log(...args);\r\n// }\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INF = Number.MAX_SAFE_INTEGER;\r\nconst INIT = -1;\r\nlet n;\r\nlet k;\r\nlet adjList;\r\nlet ld;\r\nfunction diam() {\r\n let dist = af(n + 1).fill(INIT);\r\n dist[1] = 0;\r\n let q = [1];\r\n for (let i = 0; i < q.length; i++) {\r\n let u = q[i];\r\n for (let v of adjList[u]) {\r\n if (dist[v] == INIT) {\r\n dist[v] = dist[u] + 1;\r\n q.push(v);\r\n }\r\n }\r\n }\r\n let s = INIT;\r\n let mx = INIT;\r\n for (let u = 1; u <= n; u++) {\r\n if (mx < dist[u]) {\r\n mx = dist[u];\r\n s = u;\r\n }\r\n }\r\n check(s != INIT);\r\n const p = af(n + 1).fill(INIT);\r\n dist.fill(INIT);\r\n dist[s] = 0;\r\n q = [s];\r\n for (let i = 0; i < q.length; i++) {\r\n let u = q[i];\r\n for (let v of adjList[u]) {\r\n if (dist[v] == INIT) {\r\n dist[v] = dist[u] + 1;\r\n p[v] = u;\r\n q.push(v);\r\n }\r\n }\r\n }\r\n let t = INIT;\r\n mx = INIT;\r\n for (let u = 1; u <= n; u++) {\r\n if (mx < dist[u]) {\r\n mx = dist[u];\r\n t = u;\r\n }\r\n }\r\n check(t != INIT);\r\n const rv = [t];\r\n for (let i = 0; i < mx; i++) {\r\n rv.push(p[t]);\r\n t = p[t];\r\n }\r\n return rv;\r\n}\r\nfunction getLd(s, ex) {\r\n const dist = af(n + 1).fill(INIT);\r\n const p = af(n + 1).fill(INIT);\r\n if (ex != INIT) {\r\n dist[ex] = 0;\r\n }\r\n dist[s] = 0;\r\n const q = [s];\r\n const topo = [];\r\n for (let i = 0; i < q.length; i++) {\r\n let u = q[i];\r\n for (let v of adjList[u]) {\r\n if (dist[v] == INIT) {\r\n dist[v] = dist[u] + 1;\r\n p[v] = u;\r\n q.push(v);\r\n }\r\n }\r\n topo.push(u);\r\n }\r\n for (let i = topo.length - 1; i > 0; i--) {\r\n let u = topo[i];\r\n ld[p[u]] = Math.max(ld[p[u]], ld[u] + 1);\r\n }\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n k = nextInt();\r\n adjList = Array.from({ length: n + 1 });\r\n for (let i = 0; i <= n; i++) {\r\n adjList[i] = [];\r\n }\r\n for (let i = 0; i + 1 < n; i++) {\r\n let u = nextInt();\r\n let v = nextInt();\r\n adjList[u].push(v);\r\n adjList[v].push(u);\r\n }\r\n // for (let u = 1; u <= n; u++) {\r\n // for (let v of adjList[u]) {\r\n // if (u > v) continue;\r\n // console.log('u %d v %d', u, v);\r\n // }\r\n // }\r\n const path = diam();\r\n let pathlen = path.length;\r\n ld = af(n + 1).fill(0);\r\n if ((pathlen % 2) == 0) {\r\n let r1 = path[Math.trunc(pathlen / 2)];\r\n let r2 = path[Math.trunc(pathlen / 2) - 1];\r\n getLd(r1, r2);\r\n getLd(r2, r1);\r\n }\r\n else {\r\n let root = path[Math.trunc(pathlen / 2)];\r\n getLd(root, INIT);\r\n }\r\n let ans = 0;\r\n for (let u = 1; u <= n; u++) {\r\n if (ld[u] >= k) {\r\n ans++;\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n}\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nlet n, k, g, rem, layer;\r\n\r\n//q.push(x)\r\n//q.shift() -> remove and return the leftmost element\r\n//q.peek() -> return the leftmost element\r\n//q.size()\r\n\r\nclass Queue {\r\n\tconstructor () {\r\n\t\tthis.a = [];\r\n\t\tthis.p = 0;\r\n\t}\r\n\r\n\tpush = (x) => this.a.push(x);\r\n\tshift = () => this.size() ? this.a[this.p++] : -1;\r\n\tpeek = () => this.size() ? this.a[this.p] : -1;\r\n\tsize = () => this.a.length - this.p;\r\n}\r\n\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\trl();\r\n\t\t[n, k] = rna();\r\n\t\tg = Array.from(Array(n), _ => []);\r\n\t\trem = Array(n).fill(0);\r\n\t\tfor (let i = 0; i < n - 1; i++) {\r\n\t\t\tlet [u, v] = rna(); u--, v--;\r\n\t\t\tg[u].push(v);\r\n\t\t\tg[v].push(u);\r\n\t\t\trem[u]++;\r\n\t\t\trem[v]++;\r\n\t\t}\r\n\t\tlayer = Array(n).fill(1);\r\n\r\n\t\tconst q = new Queue();\r\n\t\tfor (let i = 0; i < n; i++) if (rem[i] == 1) q.push(i);\r\n\t\twhile (q.size()) {\r\n\t\t\tconst u = q.shift();\r\n\t\t\tfor (const v of g[u]) {\r\n\t\t\t\trem[v]--;\r\n\t\t\t\tif (rem[v] == 1) {\r\n\t\t\t\t\tlayer[v] = layer[u] + 1;\r\n\t\t\t\t\tq.push(v);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 0; i < n; i++) ans += layer[i] > k;\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n // if (t === 6) {\r\n // console.log([7, 0, 0, 3, 1, 2].join('\\n'))\r\n // return\r\n // }\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n l++\r\n const [n, k] = lines[l++].trim().split(' ').map(Number)\r\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\r\n l += n - 1\r\n console.log(solve(n, k, edges))\r\n // output[i] = solve(n, k, edges)\r\n }\r\n // console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(n, k, edges) {\r\n if (n === 1) return 0\r\n // console.log(edges)\r\n const adj = {}\r\n edges.forEach(([a, b]) => {\r\n adj[a] = adj[a] || []\r\n adj[b] = adj[b] || []\r\n adj[a].push(b)\r\n adj[b].push(a)\r\n })\r\n// return\r\n let u = 1\r\n // let p = -1\r\n // while (1) {\r\n // const has = (adj[u] || []).some(v => {\r\n // if (v !== p) {\r\n // p = u\r\n // u = v\r\n // return true\r\n // }\r\n // })\r\n // if (!has) break\r\n // }\r\n // return\r\n const [hs, haschild] = dfs(adj, u, {}, k)\r\n// console.log(u, hs, haschild)\r\n return dfs2(adj, u, {}, k, hs, haschild)\r\n // let ans = n\r\n // for (let i = 1; i <= n; i++) {\r\n // if (removed[i]) ans--\r\n // }\r\n // return ans\r\n}\r\nfunction dfs(adj, r, visited, k) {\r\n const stack = [[r, 0, -1]]\r\n const hs = []\r\n const haschild = []\r\n while (stack.length) {\r\n const [u, i, p] = stack[stack.length - 1]\r\n // visited[u] = 1\r\n\r\n const nb = adj[u] || []\r\n if (!i) {\r\n // first visited\r\n }\r\n if (i < nb.length) {\r\n stack[stack.length - 1][1]++\r\n const v = nb[i]\r\n // if (!visited[v]) { // has circle\r\n if (v !== p) {\r\n stack.push([v, 0, u])\r\n }\r\n } else {\r\n // last visited\r\n hs[u] = 1\r\n haschild[u] = 0\r\n ;(adj[u] || []).forEach(v => {\r\n if (v !== p) {\r\n hs[u] = Math.max(hs[u], hs[v] + 1)\r\n if (hs[v] >= k) haschild[u]++\r\n }\r\n })\r\n // if (hs[u] <= k) removed[u] = 1\r\n stack.pop()\r\n }\r\n }\r\n return [hs, haschild]\r\n}\r\nfunction dfs2(adj, r, visited, k, hs, haschild) {\r\n const stack = [[r, 0, -1]]\r\n let count = 0\r\n while (stack.length) {\r\n const [u, i, p] = stack[stack.length - 1]\r\n // visited[u] = 1\r\n\r\n const nb = adj[u] || []\r\n if (!i) {\r\n // first visited\r\n const rh = hs[r] - hs[u] + 1\r\n if (hs[u] > k && (rh > k || (rh === k && haschild[u] > 1))) {\r\n // console.log('left', u)\r\n count++\r\n }\r\n }\r\n if (i < nb.length) {\r\n stack[stack.length - 1][1]++\r\n const v = nb[i]\r\n // if (!visited[v]) { // has circle\r\n if (v !== p) {\r\n stack.push([v, 0, u])\r\n }\r\n } else {\r\n // last visited\r\n stack.pop()\r\n }\r\n }\r\n return count\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n // if (t === 6) {\n // console.log([7, 0, 0, 3, 1, 2].join('\\n'))\n // return\n // }\n const output = []\n for (let i = 0; i < t; i++) {\n l++\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, edges))\n // output[i] = solve(n, k, edges)\n }\n // console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, edges) {\n if (n === 1) return 0\n // console.log(edges)\n const adj = {}\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n })\n// return\n let u = 1\n // let p = -1\n // while (1) {\n // const has = (adj[u] || []).some(v => {\n // if (v !== p) {\n // p = u\n // u = v\n // return true\n // }\n // })\n // if (!has) break\n // }\n // return\n const [hs, haschild] = dfs(adj, u, {}, k)\n// console.log(u, hs, haschild)\n return dfs2(adj, u, {}, k, hs, haschild)\n // let ans = n\n // for (let i = 1; i <= n; i++) {\n // if (removed[i]) ans--\n // }\n // return ans\n}\nfunction dfs(adj, r, visited, k) {\n const stack = [[r, 0, -1]]\n const hs = []\n const haschild = []\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n hs[u] = 1\n haschild[u] = 0\n ;(adj[u] || []).forEach(v => {\n if (v !== p) {\n hs[u] = Math.max(hs[u], hs[v] + 1)\n if (hs[v] >= k) haschild[u]++\n }\n })\n // if (hs[u] <= k) removed[u] = 1\n stack.pop()\n }\n }\n return [hs, haschild]\n}\nfunction dfs2(adj, r, visited, k, hs, haschild) {\n const stack = [[r, 0, -1]]\n let count = 0\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n const rh = hs[r] - hs[u] + 1\n if (hs[u] > k && (rh > k || (haschild[u] > 1))) {\n // console.log('left', u)\n count++\n }\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n stack.pop()\n }\n }\n return count\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n // if (t === 6) {\n // console.log([7, 0, 0, 3, 1, 2].join('\\n'))\n // return\n // }\n const output = []\n for (let i = 0; i < t; i++) {\n l++\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, edges))\n // output[i] = solve(n, k, edges)\n }\n // console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, edges) {\n if (n === 1) return 0\n // console.log(edges)\n const adj = {}\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n })\n// return\n let u = 1\n // let p = -1\n // while (1) {\n // const has = (adj[u] || []).some(v => {\n // if (v !== p) {\n // p = u\n // u = v\n // return true\n // }\n // })\n // if (!has) break\n // }\n // return\n const [hs, haschild] = dfs(adj, u, {}, k)\n// console.log(u, hs, haschild)\n return dfs2(adj, u, {}, k, hs, haschild)\n // let ans = n\n // for (let i = 1; i <= n; i++) {\n // if (removed[i]) ans--\n // }\n // return ans\n}\nfunction dfs(adj, r, visited, k) {\n const stack = [[r, 0, -1]]\n const hs = []\n const haschild = []\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n hs[u] = 1\n haschild[u] = 0\n ;(adj[u] || []).forEach(v => {\n if (v !== p) {\n hs[u] = Math.max(hs[u], hs[v] + 1)\n if (hs[v] >= k) haschild[u]++\n }\n })\n // if (hs[u] <= k) removed[u] = 1\n stack.pop()\n }\n }\n return [hs, haschild]\n}\nfunction dfs2(adj, r, visited, k, hs, haschild) {\n const stack = [[r, 0, -1]]\n let count = 0\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n const rh = hs[r] - hs[u] + 1\n if (hs[u] > k && (rh > k || (rh === k && haschild[u] > 1))) {\n // console.log('left', u)\n count++\n }\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n stack.pop()\n }\n }\n return count\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n // if (t === 6) {\n // console.log([7, 0, 0, 3, 1, 2].join('\\n'))\n // return\n // }\n const output = []\n for (let i = 0; i < t; i++) {\n l++\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, edges))\n // output[i] = solve(n, k, edges)\n }\n // console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, edges) {\n if (n === 1) return k < 1 ? 1 : 0\n // console.log(edges)\n const adj = {}\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n })\n// return\n let u = 1\n let p = -1\n while (1) {\n const has = adj[u].some(v => {\n if (v !== p) {\n p = u\n u = v\n return true\n }\n })\n if (!has) break\n }\n // return\n const hs = dfs(adj, u, {})\n// console.log(u, hs)\n return dfs2(adj, u, {}, hs, k)\n}\nfunction dfs(adj, r, visited) {\n const stack = [[r, 0, -1]]\n const hs = []\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n hs[u] = 1\n ;(adj[u] || []).forEach(v => {\n if (v !== p) hs[u] = Math.max(hs[u], hs[v] + 1)\n })\n stack.pop()\n }\n }\n return hs\n}\nfunction dfs2(adj, r, visited, hs, k) {\n const stack = [[r, 0, -1]]\n let count = 0\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n // visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n if (hs[u] > k && hs[r] - hs[u] + 1 > k) {\n count++\n }\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n // if (!visited[v]) { // has circle\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n stack.pop()\n }\n }\n return count\n}\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nlet n, k;\r\nlet g;\r\nlet mp = [];\r\nlet ans = 0;\r\n\r\nconst key = (x, y) => x + ',' + y;\r\n\r\nfunction dfs (u=0, p=-1) {\r\n\tlet mx = 0;\r\n\tfor (const c of g[u]) {\r\n\t\tif (c == p) continue;\r\n\t\tconst tm = dfs(c, u);\r\n\t\tmp[key(c, u)] = tm + 1;\r\n\t\t//console.log('***', c, u, mp[key(c, u)]);\r\n\t\tmx = Math.max(mx, tm);\r\n\t}\r\n\treturn mx + 1;\r\n}\r\n\r\nfunction dfs2 (u=0, p=-1, inCost=0) {\r\n\tmp[key(p, u)] = inCost;\r\n\r\n\tconst cur = [];\r\n\tcur.push(1);\r\n\tfor (const c of g[u]) {\r\n\t\tcur.push(mp[key(c, u)]);\r\n\t\t//console.log(c, u, mp[key(c, u)]);\r\n\t}\r\n\tcur.sort((x, y) => y - x);\r\n\r\n\t//console.log({u, cur, k})\r\n\tif (cur[1] <= k) ans--;\r\n\r\n\tfor (const c of g[u]) {\r\n\t\tif (c == p) continue;\r\n\t\tconst outCost = mp[key(c, u)] == cur[0] ? cur[1] : cur[0];\r\n\t\tdfs2(c, u, outCost + 1);\r\n\t}\r\n}\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\trl();\r\n\t\t[n, k] = rna();\r\n\t\tg = Array.from(Array(n), _ => []);\r\n\t\tfor (let i = 0; i < n - 1; i++) {\r\n\t\t\tlet [u, v] = rna(); u--, v--;\r\n\t\t\tg[u].push(v);\r\n\t\t\tg[v].push(u);\r\n\t\t}\r\n\r\n\t\tmp = [];\r\n\t\tans = n;\r\n\t\tdfs();\r\n\t\tdfs2();\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "07ac198c1086323517540ecd0669eb4c"} {"nl": {"description": "Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle: its vertices have integer coordinates, the coordinates of vertices are non-negative, and its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from at least one point of the line $$$y = 0$$$ walking along some straight line, without crossing the interior of the triangle. In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct. Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.", "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. Description of the test cases follows. Each test case contains three lines, each of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$0 \\le x_i, y_i \\le 10^9$$$) — coordinates of the vertices of the downtown's border.", "output_spec": "For each test case print a single number — the answer to the problem. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally let your answer be $$$a$$$, jury answer be $$$b$$$. Your answer will be considered correct if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-9}$$$.", "sample_inputs": ["5\n8 10\n10 4\n6 2\n4 6\n0 1\n4 2\n14 1\n11 2\n13 2\n0 0\n4 0\n2 4\n0 1\n1 1\n0 0"], "sample_outputs": ["0.0000000\n0\n2.0000\n0.00\n1"], "notes": "NoteIn the picture, the downtowns of the first three test cases are illustrated. Triangles are enumerated according to the indices of test cases they belong to. In the first two test cases, all points on the borders of the downtowns are safe, thus the answers are $$$0$$$.In the following picture unsafe points for the third test case are marked with black color: In the fourth test case, all points on the border of the downtown are safe."}, "positive_code": [{"source_code": "function solve(input) {\r\n input.forEach(e => {\r\n const dots = e.map(data => data.split(' '));\r\n // console.log(dots)\r\n\r\n const setDotsY = new Set(dots.map(data => data[1]));\r\n const arrDotsY = [...setDotsY];\r\n if (arrDotsY.length === 2) {\r\n const a = countObj(dots.map(data => data[1]), arrDotsY[0]);\r\n const b = countObj(dots.map(data => data[1]), arrDotsY[1]);\r\n if (a > b) {\r\n if (parseInt(arrDotsY[0]) > parseInt(arrDotsY[1])) {\r\n const x = dots.filter(data => data[1] === arrDotsY[0])\r\n console.log(Math.abs(x[0][0] - x[1][0]))\r\n } else console.log(0);\r\n } else {\r\n if (parseInt(arrDotsY[1]) > parseInt(arrDotsY[0])) {\r\n const x = dots.filter(data => data[1] === arrDotsY[1])\r\n console.log(Math.abs(x[0][0] - x[1][0]))\r\n }\r\n else console.log(0);\r\n }\r\n } else if (arrDotsY.length === 1) {\r\n console.log(0)\r\n } else {\r\n console.log(0);\r\n }\r\n });\r\n}\r\n\r\nconst countObj = (arr, val) => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);\r\n\r\n/** =========== DEFAULT FORMAT ==============\r\n * \r\n * */ \r\nfunction set_n_line() {\r\n // set return 0 if the problem needs dynamic n line inputs\r\n // set return n > 0 if the problem needs fixed n line inputs\r\n return 3\r\n}\r\nconst readline = require('readline').createInterface({ input: process.stdin });\r\nlet inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();\r\nfunction fillInput(line) {\r\n // dynamic n_line\r\n if (n_line_subinput == 0) n_line_subinput = parseInt(line)\r\n else if (sub_input.length < n_line_subinput) {\r\n sub_input.push(line)\r\n if (sub_input.length == n_line_subinput) {\r\n inputs.push(sub_input); sub_input = []; \r\n n_line_subinput = set_n_line();\r\n }\r\n }\r\n}\r\n\r\nreadline.on('line', line => {\r\n if (t == 0) t = parseInt(line)\r\n else if (inputs.length < t) {\r\n fillInput(line)\r\n if (inputs.length == t) { solve(inputs);readline.close() }\r\n }\r\n});\r\n/* =========== DEFAULT FORMAT END ============== */\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(a) {\r\n for (let i = 0; i < 3; i++) {\r\n const x = a[i];\r\n for (let j = i + 1; j < 3; j++) {\r\n const y = a[j],\r\n z = a.find((_, k) => k !== i && k !== j);\r\n if (x[1] === y[1] && x[1] !== 0 && z[1] < x[1]) return Math.abs(x[0] - y[0]);\r\n }\r\n }\r\n return 0;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const a = [];\r\n let tmp = 3;\r\n while (tmp--) {\r\n a.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let [x1, y1] = readline().split(' ').map(Number);\r\n let [x2, y2] = readline().split(' ').map(Number);\r\n let [x3, y3] = readline().split(' ').map(Number);\r\n\r\n if (y1 !== y2 && y1 !== y3 && y2 !== y3) {\r\n output(0);\r\n } else if (y1 === y2 && y3 < y1) {\r\n output(Math.abs(x1 - x2));\r\n } else if (y1 === y3 && y2 < y1) {\r\n output(Math.abs(x1 - x3));\r\n } else if (y2 === y3 && y1 < y2) {\r\n output(Math.abs(x2 - x3));\r\n } else {\r\n output(0);\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\nconst { throws } = require('assert');\n \n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst l = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\n \nconst ra = ()=>readline().split(' ').map(a=>+a)\n \nconst MOD = 1e9+7;\n\nlet sqr = x=>x*x;\nlet dist = (p1, p2)=>{\n return Math.sqrt(sqr(p1.x-p2.x)+sqr(p1.y-p2.y));\n};\n \nconst calc = (arr)=>{\n let ans = 0;\n for (let i=0; i<3; i++){\n for (let j=i+1; j<3; j++){\n if (arr[i].y==arr[j].y){\n for (let k=0; k<3; k++){\n if (k==i || k==j) continue;\n if (arr[k].y {\r\n const dots = e.map(data => data.split(' '));\r\n // console.log(dots)\r\n\r\n const setDotsY = new Set(dots.map(data => data[1]));\r\n const arrDotsY = [...setDotsY];\r\n if (arrDotsY.length === 2) {\r\n const a = countObj(dots.map(data => data[1]), arrDotsY[0]);\r\n const b = countObj(dots.map(data => data[1]), arrDotsY[1]);\r\n if (a > b) {\r\n if (parseInt(arrDotsY[0]) > parseInt(arrDotsY[1])) console.log(arrDotsY[0])\r\n else console.log(0);\r\n } else {\r\n if (parseInt(arrDotsY[1]) > parseInt(arrDotsY[0])) console.log(arrDotsY[1])\r\n else console.log(0);\r\n }\r\n } else if (arrDotsY.length === 1) {\r\n console.log(0)\r\n } else {\r\n console.log(0);\r\n }\r\n });\r\n}\r\n\r\nconst countObj = (arr, val) => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);\r\n\r\n/** =========== DEFAULT FORMAT ==============\r\n * \r\n * */ \r\nfunction set_n_line() {\r\n // set return 0 if the problem needs dynamic n line inputs\r\n // set return n > 0 if the problem needs fixed n line inputs\r\n return 3\r\n}\r\nconst readline = require('readline').createInterface({ input: process.stdin });\r\nlet inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();\r\nfunction fillInput(line) {\r\n // dynamic n_line\r\n if (n_line_subinput == 0) n_line_subinput = parseInt(line)\r\n else if (sub_input.length < n_line_subinput) {\r\n sub_input.push(line)\r\n if (sub_input.length == n_line_subinput) {\r\n inputs.push(sub_input); sub_input = []; \r\n n_line_subinput = set_n_line();\r\n }\r\n }\r\n}\r\n\r\nreadline.on('line', line => {\r\n if (t == 0) t = parseInt(line)\r\n else if (inputs.length < t) {\r\n fillInput(line)\r\n if (inputs.length == t) { solve(inputs);readline.close() }\r\n }\r\n});\r\n/* =========== DEFAULT FORMAT END ============== */\r\n"}, {"source_code": "function solve(input) {\r\n input.forEach(e => {\r\n const dots = e.map(data => data.split(' '));\r\n // console.log(dots)\r\n\r\n const setDotsY = new Set(dots.map(data => data[1]));\r\n const arrDotsY = [...setDotsY];\r\n if (arrDotsY.length === 2) {\r\n const a = countObj(dots.map(data => data[1]), arrDotsY[0]);\r\n const b = countObj(dots.map(data => data[1]), arrDotsY[1]);\r\n if (a > b) {\r\n if (parseInt(arrDotsY[0]) > parseInt(arrDotsY[1])) console.log(arrDotsY[0])\r\n else console.log(0);\r\n } else {\r\n if (parseInt(arrDotsY[1]) > parseInt(arrDotsY[0])) console.log(arrDotsY[1])\r\n else console.log(0);\r\n }\r\n } else if (arrDotsY.length === 1) {\r\n console.log(arrDotsY[0])\r\n } else {\r\n console.log(0);\r\n }\r\n });\r\n}\r\n\r\nconst countObj = (arr, val) => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);\r\n\r\n/** =========== DEFAULT FORMAT ==============\r\n * \r\n * */ \r\nfunction set_n_line() {\r\n // set return 0 if the problem needs dynamic n line inputs\r\n // set return n > 0 if the problem needs fixed n line inputs\r\n return 3\r\n}\r\nconst readline = require('readline').createInterface({ input: process.stdin });\r\nlet inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();\r\nfunction fillInput(line) {\r\n // dynamic n_line\r\n if (n_line_subinput == 0) n_line_subinput = parseInt(line)\r\n else if (sub_input.length < n_line_subinput) {\r\n sub_input.push(line)\r\n if (sub_input.length == n_line_subinput) {\r\n inputs.push(sub_input); sub_input = []; \r\n n_line_subinput = set_n_line();\r\n }\r\n }\r\n}\r\n\r\nreadline.on('line', line => {\r\n if (t == 0) t = parseInt(line)\r\n else if (inputs.length < t) {\r\n fillInput(line)\r\n if (inputs.length == t) { solve(inputs);readline.close() }\r\n }\r\n});\r\n/* =========== DEFAULT FORMAT END ============== */\r\n"}, {"source_code": "function solve(input) {\r\n input.forEach(e => {\r\n const dots = e.map(data => data.split(' '));\r\n // console.log(dots)\r\n\r\n const setDotsY = new Set(dots.map(data => data[1]));\r\n const arrDotsY = [...setDotsY];\r\n if (arrDotsY.length === 2) {\r\n const a = countObj(dots.map(data => data[1]), arrDotsY[0]);\r\n const b = countObj(dots.map(data => data[1]), arrDotsY[1]);\r\n if (a > b) {\r\n console.log(arrDotsY[0])\r\n } else {\r\n console.log(arrDotsY[1])\r\n }\r\n } else if (arrDotsY.length === 1) {\r\n console.log(arrDotsY[0])\r\n } else {\r\n console.log(0);\r\n }\r\n });\r\n}\r\n\r\nconst countObj = (arr, val) => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);\r\n\r\n/** =========== DEFAULT FORMAT ==============\r\n * \r\n * */ \r\nfunction set_n_line() {\r\n // set return 0 if the problem needs dynamic n line inputs\r\n // set return n > 0 if the problem needs fixed n line inputs\r\n return 3\r\n}\r\nconst readline = require('readline').createInterface({ input: process.stdin });\r\nlet inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();\r\nfunction fillInput(line) {\r\n // dynamic n_line\r\n if (n_line_subinput == 0) n_line_subinput = parseInt(line)\r\n else if (sub_input.length < n_line_subinput) {\r\n sub_input.push(line)\r\n if (sub_input.length == n_line_subinput) {\r\n inputs.push(sub_input); sub_input = []; \r\n n_line_subinput = set_n_line();\r\n }\r\n }\r\n}\r\n\r\nreadline.on('line', line => {\r\n if (t == 0) t = parseInt(line)\r\n else if (inputs.length < t) {\r\n fillInput(line)\r\n if (inputs.length == t) { solve(inputs);readline.close() }\r\n }\r\n});\r\n/* =========== DEFAULT FORMAT END ============== */\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(a) {\r\n for (let i = 0; i < 3; i++) {\r\n const x = a[i];\r\n for (let j = i + 1; j < 3; j++) {\r\n const y = a[j];\r\n if (x[1] === y[1] && x[1] !== 0) return Math.abs(x[0] - y[0]);\r\n }\r\n }\r\n return 0;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const a = [];\r\n let tmp = 3;\r\n while (tmp--) {\r\n a.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "src_uid": "9f019c3898f27d687c5b3498586644e8"} {"nl": {"description": "The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.", "input_spec": "The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999).", "output_spec": "Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print \"No solution\" (without the quotes).", "sample_inputs": ["3\n1875\n1936\n1721", "4\n9999\n2000\n3000\n3011", "3\n1999\n5055\n2000"], "sample_outputs": ["1835\n1836\n1921", "1999\n2000\n2000\n2011", "No solution"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1081) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join(' ')).join('\\n'), iii.slice(rr.length - 3, rr.length + 3))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n if (f + fss == p + pss) return p + pss\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9) && fs.filter(v => v != 9).length > 1)\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}], "negative_code": [{"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) return console.log('No solution')\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n f1 = 1\n else\n f1 = 2\n }\n else {\n if (f1 < p1) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n f1 = p1\n else\n f1 = p1 + 1\n } else if (f1 > p1) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n f1 = p1\n else\n f2 = 0\n } else {\n if (f2 < p2) {\n if (+`${f3}${f4}` >= +`${p3}${p4}`)\n f2 = p2\n else\n f2 = p2 + 1\n } else if (f2 > p2) {\n if (+`${f3}${f4}` >= +`${p3}${p4}`)\n f2 = p2\n else\n f3 = 0\n } else {\n if (f3 < p3) {\n if (f4 >= p4)\n f3 = p3\n else\n f3 = p3 + 1\n } else if (+f3 > f4) {\n if (f4 >= p4)\n f3 = p3\n else\n f4 = 0\n } else {\n f4 = p4\n }\n }\n }\n }\n\n return test([f1, f2, f3, f4], p) && `${f1}${f2}${f3}${f4}`\n }\n\n function test([f1, f2, f3, f4], p) {\n if ([f1, f2, f3, f4].some(v => v > 9)) return\n const f = +`${f1}${f2}${f3}${f4}`\n if (f < p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) return console.log('No solution')\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (psn > fsn)\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL)\n if (iii[1] == 1600) {\n console.log(iii.reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join('')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[1] == 1600) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = `${v}-${iii[i]}`\n return m\n }, []).map(l => l.join(' ')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1081) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join(' ')).join('\\n'), iii.slice(rr.length - 3, rr.length + 3))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n if (f + fss == p + pss) return p + pss\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL)\n if (iii[1] == 1600) {\n console.log(iii.reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join(' ')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1081) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = `${iii[i]}-${v}`\n return m\n }, []).map(l => l.join(' ')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) return console.log('No solution')\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1081) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join(' ')).join('\\n'), iii.slice(rr.length - 3, rr.length + 3))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n if (fss == pss) return pss\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1081) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join(' ')).join('\\n'), iii.slice(rr.length - 3, rr.length + 3))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n if (f + fss == p + pss) return pss\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1600) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = `${iii[i]}-${v}`\n return m\n }, []).map(l => l.join(' ')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1081) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join(' ')).join('\\n'), iii.slice(rr.length - 3, rr.length + 3))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1600) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = `${v}-${iii[i]}`\n return m\n }, []).map(l => l.join(' ')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL).slice(1)\n if (iii[0] == 1081) {\n console.log(rr.slice(-50).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join(' ')).join('\\n'), iii.slice(rr.length - 3, rr.length + 3))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (psn > fsn && ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL)\n if (iii[1] == 1600) {\n console.log(rr.slice(-100).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join('')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f) {\n const iii = ipt.split(EOL)\n if (iii[1] == 1600) {\n console.log(rr.slice(-150).reduce((m, v, i) => {\n if (!m[i / 100 | 0]) m[i / 100 | 0] = []\n m[i / 100 | 0][i % 100] = v\n return m\n }, []).map(l => l.join('')).join('\\n'))\n }\n return console.log('No solution')\n }\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n ils[0] = '1000'\n\n const rr = []\n\n for (let i = 1; i < ils.length; i++) {\n const p = ils[i - 1]\n const c = ils[i]\n const f = best(p, c)\n if (!f)return console.log('No solution')\n rr.push(f)\n ils[i] = f\n }\n\n console.log(rr.join('\\n'))\n\n function best (p, f) {\n let [f1, f2, f3, f4] = f.split('')\n let [p1, p2, p3, p4] = p.split('')\n if (p1 == 0) {\n if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)\n return `1${f2}${f3}${f4}`\n else\n return `2${f2}${f3}${f4}`\n }\n\n let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])\n\n return test(p, res.split('')) && res\n\n function search ([p, ...ps], [f, ...fs]) {\n if (!ps.length) {\n return p\n }\n let fss = fs.join('')\n let pss = ps.join('')\n let psn = +pss\n let fsn = +fss\n let pn = +p\n let fn = +f\n if (pn > fn || pn + 1 < fn) {\n if (psn > fsn) {\n return pn + 1 + fss\n } else {\n return pn + fss\n }\n } else if (pn + 1 == fn) {\n if (psn <= fsn) {\n return pn + fss\n } else {\n for (let i = 0; i < fs.length; i++) {\n if (fs[i] != 0) {\n fs[i] = 0\n break\n }\n }\n return f + fs.join('')\n }\n } else { // pn == fn\n if (ps.every(v => v == 9))\n return pn + 1 + fss\n return f + search(ps, fs)\n }\n }\n\n function test(p, fs) {\n if (fs.length > 4) return\n let f = +fs.join('')\n if (f < +p) return\n if (f < 1000) return\n if (f > 2011) return\n return true\n }\n }\n})"}], "src_uid": "c175d010d75c391d0b25391fecff007c"} {"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, p2, ..., pn 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, a2, ..., an and b1, b2, ..., bn respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.Well, she almost had it all — each of the sequences a and b matched exactly n - 1 elements in Sengoku's permutation. In other words, there is exactly one i (1 ≤ i ≤ n) such that ai ≠ pi, and exactly one j (1 ≤ j ≤ n) such that bj ≠ pj.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 ≤ n ≤ 1 000) — 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, a2, ..., an (1 ≤ ai ≤ n) — the sequence of colours in the first meteor outburst. The third line contains n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ n) — the sequence of colours in the second meteor outburst. At least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.", "output_spec": "Output n space-separated integers p1, p2, ..., pn, 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, 2, 5, 4, 3 and 1, 2, 3, 4, 5 are acceptable outputs.In the second sample, 5, 4, 2, 3, 1 is the only permutation to satisfy the constraints."}, "positive_code": [{"source_code": "var row = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = row[0];\n\nvar a = [];\na = readline().split(\" \").map(function(x) { return parseInt(x); });\n\nvar b = [];\nb = readline().split(\" \").map(function(x) { return parseInt(x); });\n\nvar ax = [];\nvar bx = [];\nvar current = 0;\n\nvar mem = [];\nvar remain = [];\nvar result1 = [];\nvar result2 = [];\n\nfor(var i = 0; i < a.length; i++) {\n\tif(a[i] == b[i]){\n\t\tresult1[i] = a[i];\n\t\tresult2[i] = a[i];\n\t\tmem[a[i]] = 1;\n\t} else {\n\t\tresult1[i] = 0;\n\t\tresult2[i] = 0;\t\n\t}\n}\n\nfor(var i = 1; i <= n; i++) {\n\tif(mem[i] != 1) {\n\t\tremain.push(i);\n\t}\n}\n\nfor(var i = 0; i < a.length; i++) {\n\tif(a[i] != b[i]){\n\t\tif(current == 0) {\n\t\t\tresult1[i] = remain[0];\n\t\t\tresult2[i] = remain[1];\n\t\t\tcurrent++;\n\t\t} else {\n\t\t\tresult1[i] = remain[1];\n\t\t\tresult2[i] = remain[0];\n\t\t}\n\t}\n}\n\nvar numA = 0;\nvar numB = 0;\nfor(var i = 0; i < a.length; i++) {\n\tif(a[i] == result1[i])\n\t\tnumA++;\n\tif(b[i] == result1[i])\n\t\tnumB++;\n}\n\nif(numA == n-1 && numB == n-1) {\n\tfor(var i = 0; i < a.length; i++)\n\t\twrite(result1[i] + ' ');\n} else {\n\tfor(var i = 0; i < a.length; i++)\n\t\twrite(result2[i] + ' ');\n}"}], "negative_code": [], "src_uid": "6fc3da19da8d9ab024cdd5acfc4f4164"} {"nl": {"description": "You are given a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.A substring of string $$$s$$$ is a continuous segment of letters from $$$s$$$. For example, \"defor\" is a substring of \"codeforces\" and \"fors\" is not. The length of the substring is the number of letters in it.Let's call some string of length $$$n$$$ diverse if and only if there is no letter to appear strictly more than $$$\\frac n 2$$$ times. For example, strings \"abc\" and \"iltlml\" are diverse and strings \"aab\" and \"zz\" are not.Your task is to find any diverse substring of string $$$s$$$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) — the length of string $$$s$$$. The second line is the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.", "output_spec": "Print \"NO\" if there is no diverse substring in the string $$$s$$$. Otherwise the first line should contain \"YES\". The second line should contain any diverse substring of string $$$s$$$.", "sample_inputs": ["10\ncodeforces", "5\naaaaa"], "sample_outputs": ["YES\ncode", "NO"], "notes": "NoteThe first example has lots of correct answers. Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to \"No comments\" answer."}, "positive_code": [{"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n\tterminal: false\n});\n\nlet n;\nrl.on('line', function(line){\n\tif (!n) {\n\t\tn = parseInt(line);\n\t} else {\n\t\tconst s = line;\n\t\tlet i = 0;\n\t\twhile (s[i] === s[i + 1] && i < s.length) {\n\t\t\ti++;\n\t\t}\n\t\tif (i < s.length - 1) {\n\t\t\tconsole.log('YES');\n\t\t\tconsole.log(s.substr(i, 2));\n\t\t} else {\n\t\t\tconsole.log('NO');\n\t\t}\n\t\trl.close();\n\t}\n});\n"}, {"source_code": "process.stdin.on('data', function(chunk){\n\tvar lns = chunk.toString().replace(/\\r/g, \"\").split(/\\n/),r;\n\t(r = lns[1].match(/(.)(?!\\1)/g)).length > 1 ? console.log('YES\\n' + r[0] + r[1]) : console.log('NO');\n});"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet counter=0, N\n\nrl.on('line', (input) => {\n if(counter==0){\n N=parseInt(input);\n counter++;\n }\n else\n {\n let ans=\"NO\", helper=\"\";\n for(let i=0; i (b ? gcd(b, a % b) : a);\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const n = parseInt(input[index]);\n index++;\n const a = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n a,\n };\n\n testCases.push(testCase);\n }\n}\n\nfunction solution(testCase) {\n const { n, a } = testCase;\n // console.log(n, a);\n let g = a[0];\n for (let i = 1; i < n; i++) g = gcd(g, a[i]);\n\n if (g == 1) {\n console.log(0);\n return;\n }\n\n for (let i = 0; i < n; i++) {\n a[i] = gcd(g, i + 1);\n }\n\n let result = Infinity;\n\n const check = (gg, ind, val) => {\n // console.log(\"check\", gg, ind, val);\n if (gg == 1) {\n if (val < result) result = val;\n return;\n }\n if (ind == 0) return;\n\n check(gg, ind - 1, val);\n check(gcd(gg, a[ind - 1]), ind - 1, val + n - ind + 1);\n };\n\n check(g, n, 0);\n console.log(result);\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var allGcd = a[0];\r\n for (var i = 1; i < n; i++) {\r\n allGcd = gcd(allGcd, a[i]);\r\n }\r\n if (allGcd === 1) {\r\n write(0);\r\n return;\r\n }\r\n if (gcd(allGcd, n) === 1) {\r\n write(1);\r\n return;\r\n }\r\n if (gcd(allGcd, n - 1) === 1) {\r\n write(2);\r\n return;\r\n }\r\n write(3);\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0) {\r\n return a;\r\n }\r\n return gcd(b, a % b)\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX = 0;\r\nvar ANS = '';\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\nfunction sortNumbers(a, b) {\r\n return a - b;\r\n}\r\nfunction sortNumbersDec(a, b) {\r\n return b - a;\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}], "negative_code": [{"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nconst gcd = (a, b) => (b ? gcd(b, a % b) : a);\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const n = parseInt(input[index]);\n index++;\n const a = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n a,\n };\n\n testCases.push(testCase);\n }\n}\n\nfunction solution(testCase) {\n const { n, a } = testCase;\n // console.log(n, a);\n\n let g = a[0];\n for (let i = 1; i < n; i++) g = gcd(g, a[i]);\n\n // console.log(\"gcd\", g);\n\n let result = 0;\n let i = n;\n while (g != 1) {\n // console.log(\"while\", i);\n const gg = gcd(g, i);\n if (gg != g) {\n // console.log(\"Found\", g, gg, i, n, n - i + 1);\n g = gg;\n result += n - i + 1;\n }\n i--;\n }\n\n console.log(result);\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}], "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$$$) — 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$$$) — 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$$$) — 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": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet ones = 0, zeros = 0;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tones += a[i] == 1;\r\n\t\t\tzeros += a[i] == 0;\r\n\t\t}\r\n\r\n\t\tconst ans = BigInt(ones) << BigInt(zeros);\r\n\r\n\t\tconsole.log(ans.toString());\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet ones = 0, zeros = 0;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tones += a[i] == 1;\r\n\t\t\tzeros += a[i] == 0;\r\n\t\t}\r\n\r\n\t\tconst ans = BigInt(ones)*1n< dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet ones = 0, zeros = 0;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tones += a[i] == 1;\r\n\t\t\tzeros += a[i] == 0;\r\n\t\t}\r\n\r\n\t\tconst ans = BigInt(ones)*2n**BigInt(zeros);\r\n\r\n\t\tconsole.log(ans.toString());\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "function solve() {\r\n read();\r\n let c1 = 0n;\r\n let c0 = 0n;\r\n readArray((value) => {\r\n if (value === '0') {\r\n c0 += 1n;\r\n }\r\n if (value === '1') {\r\n c1 += 1n;\r\n }\r\n });\r\n write(c1 * (1n << c0));\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n}\r\ninit();\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n let c0 = 0\n let c1 = 0\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === 0) c0++\n if (arr[i] === 1) c1++\n }\n let ans = BigInt(c1)\n for (let i = 0; i < c0; i++) {\n ans = ans * 2n\n }\n return ans.toString()\n}\n"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet ones = 0, zeros = 0;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tones += a[i] == 1;\r\n\t\t\tzeros += a[i] == 0;\r\n\t\t}\r\n\r\n\t\tconst ans = ones*2**zeros;\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "function solve() {\r\n read();\r\n let c1 = 0n;\r\n let c0 = 0n;\r\n readArray((value) => {\r\n if (value === '0') {\r\n c0 += 1n;\r\n }\r\n if (value === '1') {\r\n c1 += 1n;\r\n }\r\n });\r\n const d = c0 === 0n ? 1n : (c0 << 1n);\r\n write(c1 * d);\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n}\r\ninit();\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n let c0 = 0\n let c1 = 0\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === 0) c0++\n if (arr[i] === 1) c1++\n }\n return c1 * Math.pow(2, c0)\n}\n"}], "src_uid": "d786585fee251ebfd5c3e8d8b0425791"} {"nl": {"description": "There is a square matrix n × n, 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 ≤ n ≤ 1000), 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": "\nvar c = parseInt( readline() );\nvar m = [];\n\nvar zero=false;\n\nfor(var i=0; i n[i][j-1] ){\n\t\t\t\tn[i][j] = weight( m[i][j], k ) + n[i][j-1];\n\t\t\t\tp[i][j] = 'R';\n\t\t\t}else{\n\t\t\t\tn[i][j] = weight( m[i][j], k ) + n[i-1][j];\n\t\t\t\tp[i][j] = 'D';\n\t\t\t}\n\t\t}\n\t}\n\n\ti=j=c-1;\n\tvar path = [];\n\twhile( i>0 || j>0){\n\t\tpath.push( p[i][j] );\n\t\tif( p[i][j] == 'R'){\n\t\t\tj--\n\t\t}else{\n\t\t\ti--\n\t\t}\n\t}\n\treturn {\n\t\tn: n[c-1][c-1],\n\t\tpath: path\n\t}\n}\n\nvar path2 = path(m, 2);\nvar path5 = path(m, 5);\n//print(path2);\n//print(path5)\nvar p = path2.n>path5.n ? path5 : path2;\n\nif(p.n>1 && zero){\n\tprint(1);\n\n\tvar _p=[];\n\tfor(var i=0;i { let r = 0; while (v && v % k === 0) { v = v / k; r++; } return r; }\nconst n = parseInt(readline());\nconst m = Array(n).fill().map(() => readline().split(' ').map(Number))\n \nconst f = k => {\n const b = Array(n).fill().map(() => []);\n for(let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n b[i][j] = g(m[i][j], k);\n }\n }\n for(let i = 1; i < n; i++) {\n b[i][0] += b[i-1][0];\n b[0][i] += b[0][i-1];\n }\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n b[i][j] += Math.min(b[i-1][j], b[i][j-1]);\n }\n }\n let p = '', i = n-1, j = n-1;\n while (i+j) {\n if (i === 0) { p += 'R'.repeat(j); break; }\n if (j === 0) { p += 'D'.repeat(i); break; }\n \n if (b[i][j-1] < b[i-1][j]) { j--; p += 'R'; }\n else { i--; p += 'D'; }\n }\n \n return [ b[n-1][n-1], p ];\n}\n \nconst main = () => {\n const r = ((a, b) => a[0] < b[0] ? a : b)(f(2), f(5));\n if (r[0] > 1) {\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n if(m[i][j] === 0) {\n return '1\\n' + 'D'.repeat(i) + 'R'.repeat(n-1) + 'D'.repeat(n-1-i);\n }\n }\n }\n }\n return r[0] + '\\n' + r[1].split('').reverse().join('');\n}\nwrite(main());"}, {"source_code": "'use strict'\n \nconst g = (v, k) => { let r = 0; while (v && v % k === 0) { v = v / k; r++; } return r; }\nconst n = parseInt(readline());\nconst m = Array.from({length: n}, () => readline().split(' ').map(Number))\n \nconst f = k => {\n const b = Array.from({length: n}, () => []);\n for(let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n b[i][j] = g(m[i][j], k);\n }\n }\n for(let i = 1; i < n; i++) {\n b[i][0] += b[i-1][0];\n b[0][i] += b[0][i-1];\n }\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n b[i][j] += Math.min(b[i-1][j], b[i][j-1]);\n }\n }\n \n return b;\n}\n \nconst main = () => {\n const r = ((a, b) => a[n-1][n-1] < b[n-1][n-1] ? a : b)(f(2), f(5));\n if (r[n-1][n-1] > 1) {\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n if(m[i][j] === 0) {\n return '1\\n' + 'D'.repeat(i) + 'R'.repeat(n-1) + 'D'.repeat(n-1-i);\n }\n }\n }\n }\n let p = '', i = n-1, j = n-1;\n while (i+j) {\n if (i === 0) { p += 'R'.repeat(j); break; }\n if (j === 0) { p += 'D'.repeat(i); break; }\n \n if (r[i][j-1] < r[i-1][j]) { j--; p += 'R'; }\n else { i--; p += 'D'; }\n }\n return r[n-1][n-1] + '\\n' + p.split('').reverse().join('');\n}\nwrite(main());"}, {"source_code": "n = parseInt(readline());\n \ngrid = [];\n \njscantparse = v => parseInt(v);\nfor(i=0; i {\n if (n === 0) return 0;\n var ret = 0;\n while(n%k === 0) ret++, n/=k;\n return ret;\n}\n \nconst dp = (k) => {\n best = [], prev=[];\n for(i=0; i=0;) for(j=n-1; j>=0;) {\n if (i===0 && j===0) i--, j--;\n else {\n path = prev[i][j] + path;\n if (prev[i][j] === 'R') j--;\n else i--;\n }\n }\n return [best[n-1][n-1], path];\n};\n \nres2 = dp(2);\nres5 = dp(5);\n \nbest = res2[0] <= res5[0] ? res2 : res5;\n \nconst getPathWith = coordinate => {\n path = \"\";\n for (i=0; i 1) best = [1, getPathWith(zeroPosition)];\n \nconst printResult = result => {\n print(result[0]);\n print(result[1]);\n}\n \n \nprintResult(best);"}, {"source_code": "var size = parseInt(readline());\n\nvar matrix = [];\nvar column;\nvar row;\nvar zeroPosition = null;\nfor (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n for (row = 0; row < size; row++) if (matrix[column][row] === 0) zeroPosition = [column, row];\n}\n\nfunction factorize(prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nvar accMatrix = [];\nvar accPath = [];\nfunction accumulate(prime) {\n\n for (column = 0; column < size; column++) {\n accMatrix[column] = [];\n accPath[column] = [];\n }\n accMatrix[0][0] = factorize(prime, matrix[0][0]);\n accPath[0][0] = \"\";\n // print('accMatrix[0][0]', accMatrix[0][0])\n // print('accPath[0][0]', accPath[0][0])\n\n for (column = 1; column < size; column++) {\n accMatrix[0][column] = accMatrix[0][column - 1] + factorize(prime, matrix[0][column]);\n accPath[0][column] = \"R\";\n accMatrix[column][0] = accMatrix[column - 1][0] + factorize(prime, matrix[column][0]);\n accPath[column][0] = \"D\";\n\n // print(accMatrix[0][column])\n // print(accPath[0][column])\n // print(accMatrix[column][0])\n // print(accPath[column][0])\n }\n\n // print('---')\n\n for (column = 1; column < size; column++) for (row = 1; row < size; row++) {\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n if (accMatrix[column - 1][row] < accMatrix[column][row - 1]) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n }\n\n // print(accMatrix[column][row])\n // print(accPath[column][row])\n }\n\n path = \"\";\n for (column = size - 1; column >= 0;) for (row = size - 1; row >= 0;) {\n if (column === 0 && row === 0) {column--; row--;}\n else {\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n }\n }\n\n return [accMatrix[size - 1][size - 1], path]\n}\n\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\nvar i = 0;\nfunction getPathWith(coordinates) {\n path = \"\";\n for (i = 0; i < coordinates[0]; i++) {\n path += \"D\";\n }\n for (i = 0; i < size - 1; i++) {\n path += \"R\";\n }\n for (i = coordinates[0]; i < size - 1; i++) {\n path += \"D\";\n }\n return path;\n}\n\nif (zeroPosition !== null && best[0] > 1) best = [1, getPathWith(zeroPosition)]\n\nprint(best[0]);\nprint(best[1]);"}, {"source_code": "var size = parseInt(readline());\n\nvar matrix = [];\nvar column;\nvar row;\nvar zeroPosition = null;\nfor (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n for (row = 0; row < size; row++) if (matrix[column][row] === 0) zeroPosition = [column, row];\n}\n\nfunction factorize(prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nvar accMatrix = [];\nvar accPath = [];\nvar path = \"\";\nfunction accumulate(prime) {\n\n for (column = 0; column < size; column++) {\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column - 1 >= 0 && row - 1 >= 0) {\n if (accMatrix[column - 1][row] < accMatrix[column][row - 1]) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n }\n } else if (column - 1 >= 0) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else if (row - 1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n }\n }\n\n path = \"\";\n for (column = size - 1; column >= 0;) for (row = size - 1; row >= 0;) {\n if (column === 0 && row === 0) {column--; row--;}\n else {\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n }\n }\n\n return [accMatrix[size - 1][size - 1], path]\n}\n\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\nvar i = 0;\nfunction getPathWith(coordinates) {\n path = \"\";\n for (i = 0; i < coordinates[0]; i++) path += \"D\";\n for (i = 0; i < size - 1; i++) path += \"R\";\n for (i = coordinates[0]; i < size - 1; i++) path += \"D\";\n return path;\n}\n\nif (zeroPosition !== null && best[0] > 1) best = [1, getPathWith(zeroPosition)]\n\nprint(best[0]);\nprint(best[1]);"}, {"source_code": "var size = parseInt(readline());\n\nvar matrix = [];\nvar column;\nvar row;\nfor (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n}\n\nvar zeroPosition = null;\nfor (column = 0; column < size; column++) for (row = 0; row < size; row++) if (matrix[column][row] === 0) zeroPosition = [column, row];\n\n\nfunction factorize(prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\n\nfunction accumulate(prime) {\n accMatrix = [];\n accPath = [];\n for (column = 0; column < size; column++) {\n accMatrix[column] = [];\n accPath[column] = [];\n }\n accMatrix[0][0] = factorize(prime, matrix[0][0]);\n accPath[0][0] = \"\";\n // print('accMatrix[0][0]', accMatrix[0][0])\n // print('accPath[0][0]', accPath[0][0])\n\n for (column = 1; column < size; column++) {\n accMatrix[0][column] = accMatrix[0][column - 1] + factorize(prime, matrix[0][column]);\n accPath[0][column] = \"R\";\n accMatrix[column][0] = accMatrix[column - 1][0] + factorize(prime, matrix[column][0]);\n accPath[column][0] = \"D\";\n\n // print(accMatrix[0][column])\n // print(accPath[0][column])\n // print(accMatrix[column][0])\n // print(accPath[column][0])\n }\n\n // print('---')\n\n for (column = 1; column < size; column++) for (row = 1; row < size; row++) {\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n if (accMatrix[column - 1][row] < accMatrix[column][row - 1]) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n }\n\n // print(accMatrix[column][row])\n // print(accPath[column][row])\n }\n\n path = \"\";\n for (column = size - 1; column >= 0;) for (row = size - 1; row >= 0;) {\n if (column === 0 && row === 0) {column--; row--;}\n else {\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n }\n }\n\n return [accMatrix[size - 1][size - 1], path]\n}\n\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\nvar i = 0;\nfunction getPathWith(coordinates) {\n path = \"\";\n for (i = 0; i < coordinates[0]; i++) {\n path += \"D\";\n }\n for (i = 0; i < size - 1; i++) {\n path += \"R\";\n }\n for (i = coordinates[0]; i < size - 1; i++) {\n path += \"D\";\n }\n return path;\n}\n\nif (zeroPosition !== null && best[0] > 1) best = [1, getPathWith(zeroPosition)]\n\nprint(best[0]);\nprint(best[1]);"}, {"source_code": "var size = parseInt(readline());\n\nvar matrix = [];\nvar column;\nvar row;\nvar zeroPosition = null;\nfor (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n for (row = 0; row < size; row++) if (matrix[column][row] === 0) zeroPosition = [column, row];\n}\n\nfunction factorize(prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nvar accMatrix = [];\nvar accPath = [];\nvar path = \"\";\nfunction accumulate(prime) {\n\n for (column = 0; column < size; column++) {\n accMatrix[column] = [];\n accPath[column] = [];\n }\n accMatrix[0][0] = factorize(prime, matrix[0][0]);\n accPath[0][0] = \"\";\n // print('accMatrix[0][0]', accMatrix[0][0])\n // print('accPath[0][0]', accPath[0][0])\n\n for (column = 1; column < size; column++) {\n accMatrix[0][column] = accMatrix[0][column - 1] + factorize(prime, matrix[0][column]);\n accPath[0][column] = \"R\";\n accMatrix[column][0] = accMatrix[column - 1][0] + factorize(prime, matrix[column][0]);\n accPath[column][0] = \"D\";\n }\n\n for (column = 1; column < size; column++) for (row = 1; row < size; row++) {\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n if (accMatrix[column - 1][row] < accMatrix[column][row - 1]) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n }\n\n }\n \n path = \"\";\n for (column = size - 1; column >= 0;) for (row = size - 1; row >= 0;) {\n if (column === 0 && row === 0) {column--; row--;}\n else {\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n }\n }\n\n return [accMatrix[size - 1][size - 1], path]\n}\n\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\nvar i = 0;\nfunction getPathWith(coordinates) {\n path = \"\";\n for (i = 0; i < coordinates[0]; i++) path += \"D\";\n for (i = 0; i < size - 1; i++) path += \"R\";\n for (i = coordinates[0]; i < size - 1; i++) path += \"D\";\n return path;\n}\n\nif (zeroPosition !== null && best[0] > 1) best = [1, getPathWith(zeroPosition)]\n\nprint(best[0]);\nprint(best[1]);"}, {"source_code": "/**\n * dynamic programming solution:\n * - process 2 and 5 separately b/c of RAM\n * - don't store full paths during traversal\n * - handle 0 in path\n */\n\nvar count = parseInt(readline());\nvar input = [];\n\nfor (var i = 0; i < count; i++) {\n input[i] = readline().split(' ').map(function(element) {\n return parseInt(element);\n });\n}\n\n// solve for 2's\nvar twos = traverseInReverse(input, count, findTwos);\n\n// if there's a path with no 2's, return it\nif (twos[0] === 0) {\n print(twos[0]);\n print(twos[1]);\n} else {\n // solve for 5's\n var fives = traverseInReverse(input, count, findFives);\n\n // final answer is least of twos and fives\n if (twos[0] <= fives[0]) {\n print(twos[0]);\n print(twos[1]);\n } else {\n print(fives[0]);\n print(fives[1]);\n }\n}\n// ------------------------------------------------------------------------\n\nfunction findTwos(input) {\n var output = 0;\n while (input % 2 === 0) {\n input /= 2;\n output++;\n }\n return output;\n}\n\nfunction findFives(input) {\n var output = 0;\n while (input % 5 === 0) {\n input /= 5;\n output++;\n }\n return output;\n}\n\nfunction traverseInReverse(input, count, findFn) {\n var downSolution, rightSolution, path;\n var boundary = count - 1;\n\n var answerCounts = [];\n var answerPaths = []; // array of arrays\n var pathContainsZero = []; // best path contains just 1 zero\n\n rowLoop:\n for (var a = boundary; a > -1; a--) {\n answerPaths[a] = [];\n\n columnLoop:\n for (var b = boundary; b > -1; b--) {\n\n // --- start check zero\n if (input[a][b] === 0) {\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n if (a < boundary) {\n answerPaths[a][b] = 'D'; // default down\n } else if (b < boundary) {\n answerPaths[a][b] = 'R';\n } else {\n answerPaths[a][b] = ''; // last node\n }\n continue columnLoop;\n }\n\n if (b < boundary && pathContainsZero[b + 1]) {\n // right contains zero\n if (a === boundary || answerCounts[b] > 0) {\n // there is no down or down count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'R';\n continue columnLoop;\n }\n }\n\n if (a < boundary && pathContainsZero[b]) {\n // down contains zero\n if (b === boundary || answerCounts[b + 1] > 0) {\n // there is no right or right count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'D';\n continue columnLoop;\n }\n }\n // --- end check zero\n\n var found = findFn(input[a][b]);\n\n if (a === boundary && b === boundary) {\n // last node\n answerCounts[b] = found;\n answerPaths[a][b] = '';\n } else if (a < boundary && b < boundary) {\n // down and right available\n // existing answerCounts[b] is from previous row\n if (answerCounts[b] <= answerCounts[b + 1]) {\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n pathContainsZero[b] = !!pathContainsZero[b];\n } else {\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n pathContainsZero[b] = !!pathContainsZero[b + 1];\n }\n } else if (a === boundary && b < boundary) {\n // right available\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n pathContainsZero[b] = !!pathContainsZero[b + 1];\n } else if (a < boundary && b === boundary) {\n // down available\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n pathContainsZero[b] = !!pathContainsZero[b];\n }\n }\n }\n\n // recreate path\n var a = 0;\n var b = 0;\n var path = '';\n while (a < boundary || b < boundary) {\n var next = answerPaths[a][b];\n path += next;\n if (next == 'D') {\n a++;\n } else {\n b++;\n }\n\n if (a > boundary || b > boundary) {\n print('error while recreating path');\n break;\n }\n }\n\n return [answerCounts[0], path];\n}\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nvar re = /0*$/;\n\nvar hasZero = false;\nvar pathZero;\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n\n if (value === 0) {\n if (!hasZero) {\n hasZero = true;\n pathZero =\n (new Array(i + 1)).join('D') +\n (new Array(n)).join('R') +\n (new Array(n - i)).join('D');\n }\n\n array2[i].push(1);\n array5[i].push(1);\n }\n\n array2[i].push(value.toString(2).match(re)[0].length);\n array5[i].push(value.toString(5).match(re)[0].length);\n }\n}\n\nvar foo = function(array) {\n var i, j;\n\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n\n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar result2 = foo(array2);\nvar result5 = foo(array5);\n\nif (hasZero && result2[0] > 1 && result5[0] > 1) {\n write('1\\n');\n write(pathZero);\n} else {\n if (result2[0] < result5[0]) {\n write(result2[0] + '\\n');\n write(result2[1]);\n } else {\n write(result5[0] + '\\n');\n write(result5[1]);\n }\n}\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nvar re = /0*$/;\n\nvar hasZero = false;\nvar zeroI, zeroJ;\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n \n if (value === 0) {\n hasZero = true;\n zeroI = i;\n zeroJ = j;\n }\n \n array2[i].push(value.toString(2).match(re)[0].length);\n array5[i].push(value.toString(5).match(re)[0].length);\n }\n}\n\nvar foo = function(array) {\n var i, j;\n\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n\n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar result2 = foo(array2);\nvar result5 = foo(array5);\n\nif (hasZero && result2[0] > 1 && result5[0] > 1) {\n write('1\\n');\n write((new Array(zeroI + 1)).join('D') + (new Array(n)).join('R') + (new Array(n - zeroI)).join('D'));\n} else {\n if (result2[0] < result5[0]) {\n write(result2[0] + '\\n');\n write(result2[1]);\n } else {\n write(result5[0] + '\\n');\n write(result5[1]);\n }\n}\n"}, {"source_code": "n = parseInt(readline());\n\ngrid = [];\n\njscantparse = v => parseInt(v);\nfor(i=0; i {\n if (n === 0) return 0;\n var ret = 0;\n while(n%k === 0) ret++, n/=k;\n return ret;\n}\n\nconst dp = (k) => {\n best = [], prev=[];\n for(i=0; i=0;) for(j=n-1; j>=0;) {\n if (i===0 && j===0) i--, j--;\n else {\n path = prev[i][j] + path;\n if (prev[i][j] === 'R') j--;\n else i--;\n }\n }\n return [best[n-1][n-1], path];\n};\n\nres2 = dp(2);\nres5 = dp(5);\n\nbest = res2[0] <= res5[0] ? res2 : res5;\n\nconst getPathWith = coordinate => {\n path = \"\";\n for (i=0; i 1) best = [1, getPathWith(zeroPosition)];\n\nconst printResult = result => {\n print(result[0]);\n print(result[1]);\n}\n\n\nprintResult(best);"}], "negative_code": [{"source_code": "\nvar c = parseInt( readline() );\nvar list = [];\nfor(var i=0; ic*c ? null : step( i+c, {\n\t\t'2': s[2]+list[i][2],\n\t\t'5': s[5]+list[i][5]\n\t});\n\n\tif(!R && !D){\n\t\treturn {\n\t\t\t'way': '',\n\t\t\t'2': list[i][2],\n\t\t\t'5': list[i][5]\n\t\t};\n\t}\n\tif(!D){\n\t\treturn {\n\t\t\tway: 'R'+R.way,\n\t\t\t'2': list[i][2]+R[2],\n\t\t\t'5': list[i][5]+R[5]\n\t\t}\n\t}\n\tif(!R){\n\t\treturn {\n\t\t\tway: 'D'+D.way,\n\t\t\t'2': list[i][2]+D[2],\n\t\t\t'5': list[i][2]+D[5]\n\t\t}\n\t}\n\n\tif(Math.min( s[2]+R[2], s[5]+R[5] ) > Math.min( s[2]+D[2], s[5]+D[5] )){\n\t\treturn {\n\t\t\tway: 'D'+D.way,\n\t\t\t'2': list[i][2]+D[2],\n\t\t\t'5': list[i][5]+D[5]\n\t\t}\n\t}else{\n\t\treturn {\n\t\t\tway: 'R'+R.way,\n\t\t\t'2': list[i][2]+R[2],\n\t\t\t'5': list[i][5]+R[5]\n\t\t}\n\t}\n}\n\nvar way = step(1, {'2':list[1][2], '5':list[1][5]});\n\nprint( Math.min(way[2], way[5]) );\nprint( way.way );"}, {"source_code": "var c = parseInt( readline() );\nvar m = [];\n\nfor(var i=0; i up.c2 ){\n\t\t\t\t\tself.c2 = self.n2 + up.c2;\n\t\t\t\t\tself.w2 = 'D';\n\t\t\t\t}else{\n\t\t\t\t\tself.c2 = self.n2 + left.c2;\n\t\t\t\t\tself.w2 = 'R';\n\t\t\t\t}\n\t\t\t\tif(left.c5 > up.c5 ){\n\t\t\t\t\tself.c5 = self.n5 + up.c5;\n\t\t\t\t\tself.w5 = 'D';\n\t\t\t\t}else{\n\t\t\t\t\tself.c5 = self.n5 + left.c5;\n\t\t\t\t\tself.w5 = 'R';\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tself.c2 = self.n2 + up.c2;\n\t\t\t\tself.w2 = 'D';\n\t\t\t\tself.c5 = self.n5 + up.c5;\n\t\t\t\tself.w5 = 'D';\n\t\t\t}\n\t\t}else{\n\t\t\tif(left){\n\t\t\t\tself.c2 = self.n2 + left.c2;\n\t\t\t\tself.w2 = 'R';\n\t\t\t\tself.c5 = self.n5 + left.c5;\n\t\t\t\tself.w5 = 'R';\n\t\t\t}else{\n\t\t\t\tself.c2 = self.n2;\n\t\t\t\tself.w2 = '';\n\t\t\t\tself.c5 = self.n5;\n\t\t\t\tself.w5 = '';\n\t\t\t}\n\t\t}\n\t}\n}\nfunction path(n){\n\t//var c = 'c'+n;\n\tvar w = 'w'+n;\n\tvar x=c-1;\n\tvar y=c-1;\n\tvar ret = []\n\twhile( x!=0 || y!=0 ){\n\t\tprint(x, y)\n\t\tret.push( m[y][x][w] );\n\t\tif(m[y][x][w]=='R'){\n\t\t\tx--;\n\t\t}else{\n\t\t\ty--;\n\t\t}\n\t}\n\treturn ret.reverse().join('');\n}\n\nvar end = m[c-1][c-1];\n\nif( end.c5>end.c2 ){\n\tprint(end.c2);\n\tprint( path('2') )\n}else{\n\tprint(end.c5);\n\tprint( path('5') );\n}\n"}, {"source_code": "\nvar c = parseInt( readline() );\nvar m = [];\n\nvar zero=false;\n\nfor(var i=0; i n[i][j-1] ){\n\t\t\t\tn[i][j] = weight( m[i][j], k ) + n[i][j-1];\n\t\t\t\tp[i][j] = 'R';\n\t\t\t}else{\n\t\t\t\tn[i][j] = weight( m[i][j], k ) + n[i-1][j];\n\t\t\t\tp[i][j] = 'D';\n\t\t\t}\n\t\t}\n\t}\n\n\ti=j=c-1;\n\tvar path = [];\n\twhile( i>0 || j>0){\n\t\tpath.push( p[i][j] );\n\t\tif( p[i][j] == 'R'){\n\t\t\tj--\n\t\t}else{\n\t\t\ti--\n\t\t}\n\t}\n\treturn {\n\t\tn: n[c-1][c-1],\n\t\tpath: path\n\t}\n}\n\nvar path2 = path(m, 2);\nvar path5 = path(m, 5);\n//print(path2);\n//print(path5)\nvar p = path2.n>path5.n ? path5 : path2;\n\nif(p.n>1 && zero){\n\tprint(1);\n\n\tvar _p=[];\n\tfor(var i=0;i1E-6; ){\n\tvar dd = d(xx, yy);\n\tif(dd<1E-6){\n\t\tprint(xx + ' ' + yy);\n\t\tbreak;\n\t}\n\tif( dd>d(xx-i, yy) ){\n\t\txx -= i; \n\t}else if( dd>d(xx+i, yy) ){\n\t\txx += i; \n\t}else if( dd>d(xx, yy-i) ){\n\t\tyy -= i; \n\t}else if( dd>d(xx, yy+i) ){\n\t\tyy += i; \n\t}else{\n\t\ti *=0.7;\n\t}\n}\n"}, {"source_code": "var c = parseInt( readline() );\nvar m = [];\n\nfor(var i=0; i0 || j>0){\n\t\tif( i>0 && j>0 && (n[i-1][j] > n[i][j-1] || i>0) ){\n\t\t\tpath.push('D');\n\t\t\tj--;\n\t\t}else{\n\t\t\tpath.push('R');\n\t\t\ti--;\n\t\t}\n\t}\n\treturn {\n\t\tn: n[c-1][c-1],\n\t\tpath: path.reverse().join('')\n\t}\n}\n\nvar path2 = path(m, 2);\nvar path5 = path(m, 5);\nif(path2.n>path5.n){\n\tprint(path5.n);\n\tprint(path5.path);\n}else{\n\tprint(path2.n);\n\tprint(path2.path);\n}"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n const q = [ { v: M[0][0], x: 0, y: 0, h: '', z: `${M[0][0]}`.split('').reverse().findIndex(i => i !== '0') } ];\n \n while (q.length) {\n let i = q.sort((a, b) => a.z > b.z ? 1 : a.z < b.z ? -1 : b.h.length - a.h.length).shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x + 1, y: i.y, h: i.h + 'D' });\n }\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x, y: i.y + 1, h: i.h + 'R' });\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n let Z = 0;\n let V = M[0][0];\n while (V % 10 === 0) { V = V / 10; Z++; }\n const q = [ { v: V, x: 0, y: 0, h: '', z: Z } ];\n \n while (q.length) {\n let i = q.shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x, y: i.y + 1, h: i.h + 'D' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x + 1, y: i.y, h: i.h + 'R' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\nconst g = (v, k) => {\n let r = 0;\n while (v % k === 0) { v = v / k; r++; }\n return r;\n}\nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number).map(i => [ g(i, 2), g(i, 5) ]); }\n \n \nconst f = (n, M) => {\n const Two = M[0][0][0];\n const Five = M[0][0][1];\n const q = [ Two, Five, Math.min(Two, Five), 0, 0, '', 0 ];\n \n while (q.length) {\n let i = q.shift();\n if (i.x === n && i.y === n) return [ i[3], i[5] ].join('\\n');\n if (i.x < n) {\n const j = M[i[4]][i[3] + 1];\n const two = i[0] + j[0];\n const five = i[1] + j[1];\n const next = [ two, five, Math.min(two, five), i[3] + 1, i[4], i[5] + 'R', i[6] + 1 ];\n const index = q.findIndex(item => item[2] > next[2] || (item[2] === next[2] && item[6] < next[6]));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n if (i.y < n) {\n const j = M[i[4] + 1][i[3]];\n const two = i[0] + j[0];\n const five = i[1] + j[1];\n const next = [ two, five, Math.min(two, five), i[3], i[4] + 1, i[5] + 'D', i[6] + 1 ];\n const index = q.findIndex(item => item[2] > next[2] || (item[2] === next[2] && item[6] < next[6]));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n }\n}\nwrite(f(n - 1, M));\n"}, {"source_code": "'use strict'\n\nconst g = (v, k) => { let r = 0; while (v % k === 0) { v = v / k; r++; } return r; }\nconst n = parseInt(readline());\nconst m = Array(n).fill().map(() => readline().split(' ').map(Number))\n\nconst f = k => {\n const b = Array(n).fill().map(() => []);\n for(let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n b[i][j] = g(m[i][j], k);\n }\n }\n for(let i = 1; i < n; i++) {\n b[i][0] += b[i-1][0];\n b[0][i] += b[0][i-1];\n }\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n b[i][j] += Math.min(b[i-1][j], b[i][j-1]);\n }\n }\n let p = '', i = n-1, j = n-1;\n while (i+j) {\n if (i === 0) { p += 'R'.repeat(j); break; }\n if (j === 0) { p += 'D'.repeat(i); break; }\n \n if (b[i][j-1] < b[i-1][j]) { j--; p += 'R'; }\n else { i--; p += 'D'; }\n }\n \n return [ b[n-1][n-1], p ];\n}\n\nconst r = ((a, b) => a[0] < b[0] ? a : b)(f(2), f(5));\n\nwrite(r[0] + '\\n' + r[1]);"}, {"source_code": "'use strict'\n\nconst g = (v, k) => { let r = 0; while (v % k === 0) { v = v / k; r++; } return r; }\nconst n = parseInt(readline());\nconst m = Array(n).fill().map(() => readline().split(' ').map(Number))\n\nconst f = k => {\n const b = Array(n).fill().map(() => []);\n for(let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n b[i][j] = g(m[i][j], k);\n }\n }\n for(let i = 1; i < n; i++) {\n b[i][0] += b[i-1][0];\n b[0][i] += b[0][i-1];\n }\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n b[i][j] += Math.min(b[i-1][j], b[i][j-1]);\n }\n }\n let p = '', i = n-1, j = n-1;\n while (i+j) {\n if (i === 0) { p += 'R'.repeat(j); break; }\n if (j === 0) { p += 'D'.repeat(i); break; }\n \n if (b[i][j-1] < b[i-1][j]) { j--; p += 'R'; }\n else { i--; p += 'D'; }\n }\n \n return [ b[n-1][n-1], p ];\n}\nconst f2 = f(2);\nconst f5 = f(5);\n\nconst r = (a, b) => a[0] < b[0] ? a : b;\n\nwrite(r[0] + '\\n' + r[1]);\n"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n let Z = 0;\n let V = M[0][0];\n while (V % 10 === 0) { V = V / 10; Z++; }\n const q = [ { v: V, x: 0, y: 0, h: '', z: Z } ];\n \n if (n === 19) return `0\nDDDRDRDDDDDDDDRDDRRRRDRRRRRDRRRRDRDRDR`;\n \n while (q.length) {\n let i = q.shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x, y: i.y + 1, h: i.h + 'R' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x + 1, y: i.y, h: i.h + 'D' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n let Z = 0;\n let V = M[0][0];\n while (V % 10 === 0) { V = V / 10; Z++; }\n const q = [ { v: V, x: 0, y: 0, h: '', z: Z } ];\n \n while (q.length) {\n let i = q.sort((a, b) => a.z > b.z ? 1 : a.z < b.z ? -1 : b.h.length - a.h.length).shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x, y: i.y + 1, h: i.h + 'R' });\n }\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x + 1, y: i.y, h: i.h + 'D' });\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n let Z = 0;\n let V = M[0][0];\n while (V % 10 === 0) { V = V / 10; Z++; }\n const q = [ { v: V, x: 0, y: 0, h: '', z: Z } ];\n \n while (q.length) {\n let i = q.sort((a, b) => a.z > b.z ? 1 : a.z < b.z ? -1 : b.h.length - a.h.length).shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x + 1, y: i.y, h: i.h + 'D' });\n }\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x, y: i.y + 1, h: i.h + 'R' });\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst g = (v, k) => {\n let r = 0;\n while (v % k) { v = v / k; r++; }\n return r;\n}\nconst f = (n, M) => {\n const Two = g(M[0][0], 2);\n const Five = g(M[0][0], 5);\n const q = [ { two: Two, five: Five, x: 0, y: 0, h: '', z: Math.min(Two, Five) } ];\n \n while (q.length) {\n let i = q.shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.x < n) {\n const two = i.two + g(M[i.y][i.x + 1], 2);\n const five = i.five + g(M[i.y][i.x + 1], 5);\n const next = {two, five, x: i.x + 1, y: i.y, h: i.h + 'R', z: Math.min(two, five) };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n if (i.y < n) {\n const two = i.two + g(M[i.y + 1][i.x], 2);\n const five = i.five + g(M[i.y + 1][i.x], 5);\n const next = {two, five, x: i.x, y: i.y + 1, h: i.h + 'D', z: Math.min(two, five) };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst g = (v, k) => { let r = 0; while (v && v % k === 0) { v = v / k; r++; } return r; }\nconst n = parseInt(readline());\nconst m = Array(n).fill().map(() => readline().split(' ').map(Number))\n \nconst f = k => {\n const b = Array(n).fill().map(() => []);\n for(let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n b[i][j] = g(m[i][j], k);\n }\n }\n for(let i = 1; i < n; i++) {\n b[i][0] += b[i-1][0];\n b[0][i] += b[0][i-1];\n }\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n b[i][j] += Math.min(b[i-1][j], b[i][j-1]);\n }\n }\n let p = '', i = n-1, j = n-1;\n while (i+j) {\n if (i === 0) { p += 'R'.repeat(j); break; }\n if (j === 0) { p += 'D'.repeat(i); break; }\n \n if (b[i][j-1] < b[i-1][j]) { j--; p += 'R'; }\n else { i--; p += 'D'; }\n }\n \n return [ b[n-1][n-1], p ];\n}\n \nconst main = () => {\n const r = ((a, b) => a[0] < b[0] ? a : b)(f(2), f(5));\n if (r[0] > 1) {\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n if(m[i][j] === 0) {\n return '0\\n' + 'R'.repeat(i) + 'D'.repeat(n-1) + 'R'.repeat(n-1-i);\n }\n }\n }\n }\n return r[0] + '\\n' + r[1].split('').reverse().join('');\n}\nwrite(main());"}, {"source_code": "'use strict'\n \nconst g = (v, k) => { let r = 0; while (v && v % k === 0) { v = v / k; r++; } return r; }\nconst n = parseInt(readline());\nconst m = Array(n).fill().map(() => readline().split(' ').map(Number))\n \nconst f = k => {\n const b = Array(n).fill().map(() => []);\n for(let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n b[i][j] = g(m[i][j], k);\n }\n }\n for(let i = 1; i < n; i++) {\n b[i][0] += b[i-1][0];\n b[0][i] += b[0][i-1];\n }\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n b[i][j] += Math.min(b[i-1][j], b[i][j-1]);\n }\n }\n let p = '', i = n-1, j = n-1;\n while (i+j) {\n if (i === 0) { p += 'R'.repeat(j); break; }\n if (j === 0) { p += 'D'.repeat(i); break; }\n \n if (b[i][j-1] < b[i-1][j]) { j--; p += 'R'; }\n else { i--; p += 'D'; }\n }\n \n return [ b[n-1][n-1], p ];\n}\n\nfor (let i = 0; i < n; i++) {\n \n} \nconst r = ((a, b) => a[0] < b[0] ? a : b)(f(2), f(5));\n \nwrite(r[0] + '\\n' + r[1].split('').reverse().join(''));\n"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n let Z = 0;\n let V = M[0][0];\n while (V % 10 === 0) { V = V / 10; Z++; }\n const q = [ { v: V, x: 0, y: 0, h: '', z: Z } ];\n \n while (q.length) {\n let i = q.sort((a, b) => a.z > b.z ? 1 : a.z < b.z ? -1 : b.h.length - a.h.length).shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x, y: i.y + 1, h: i.h + 'R' });\n }\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x + 1, y: i.y, h: i.h + 'D' });\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n let Z = 0;\n let V = M[0][0];\n while (V % 10 === 0) { V = V / 10; Z++; }\n const q = [ { v: V, x: 0, y: 0, h: '', z: Z } ];\n \n while (q.length) {\n let i = q.shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x, y: i.y + 1, h: i.h + 'R' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x + 1, y: i.y, h: i.h + 'D' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\nconst g = (v, k) => {\n let r = 0;\n while (v % k === 0) { v = v / k; r++; }\n return r;\n}\nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number).map(i => [ g(i, 2), g(i, 5) ]); }\n \n \nconst f = (n, M) => {\n const Two = M[0][0][0];\n const Five = M[0][0][1];\n const q = [ Two, Five, Math.min(Two, Five), 0, 0, '', 0 ];\n \n while (q.length) {\n let i = q.shift();\n if (i[3] === n && i[4] === n) return [ i[2], i[5] ].join('\\n');\n if (i[3] < n) {\n const j = M[i[4]][i[3] + 1];\n const two = i[0] + j[0];\n const five = i[1] + j[1];\n const next = [ two, five, Math.min(two, five), i[3] + 1, i[4], i[5] + 'R', i[6] + 1 ];\n const index = q.findIndex(item => item[2] > next[2] || (item[2] === next[2] && item[6] < next[6]));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n if (i[4] < n) {\n const j = M[i[4] + 1][i[3]];\n const two = i[0] + j[0];\n const five = i[1] + j[1];\n const next = [ two, five, Math.min(two, five), i[3], i[4] + 1, i[5] + 'D', i[6] + 1 ];\n const index = q.findIndex(item => item[2] > next[2] || (item[2] === next[2] && item[6] < next[6]));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n }\n}\nwrite(f(n - 1, M));\n"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n let Z = 0;\n let V = M[0][0];\n while (V % 10 === 0) { V = V / 10; Z++; }\n const q = [ { v: V, x: 0, y: 0, h: '', z: Z } ];\n \n while (q.length) {\n let i = q.shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x, y: i.y + 1, h: i.h + 'R' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n q.splice(index, 0, next);\n }\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n while (v % 10 === 0) { v = v / 10; z++; }\n const next = { z, v, x: i.x + 1, y: i.y, h: i.h + 'D' };\n const index = q.findIndex(item => item.z > next.z || (item.z === next.z && item.h.length < next.h.length));\n q.splice(index, 0, next);\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst g = (v, k) => { let r = 0; while (v && v % k === 0) { v = v / k; r++; } return r; }\nconst n = parseInt(readline());\nconst m = Array(n).fill().map(() => readline().split(' ').map(Number))\n \nconst f = k => {\n const b = Array(n).fill().map(() => []);\n for(let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n b[i][j] = g(m[i][j], k);\n }\n }\n for(let i = 1; i < n; i++) {\n b[i][0] += b[i-1][0];\n b[0][i] += b[0][i-1];\n }\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n b[i][j] += Math.min(b[i-1][j], b[i][j-1]);\n }\n }\n let p = '', i = n-1, j = n-1;\n while (i+j) {\n if (i === 0) { p += 'R'.repeat(j); break; }\n if (j === 0) { p += 'D'.repeat(i); break; }\n \n if (b[i][j-1] < b[i-1][j]) { j--; p += 'R'; }\n else { i--; p += 'D'; }\n }\n \n return [ b[n-1][n-1], p ];\n}\n \nconst main = () => {\n const r = ((a, b) => a[0] < b[0] ? a : b)(f(2), f(5));\n if (r[0] > 1) {\n for(let i = 1; i < n; i++) {\n for (let j = 1; j < n; j++) {\n if(m[i][j] === 0) {\n return '1\\n' + 'R'.repeat(i) + 'D'.repeat(n-1) + 'R'.repeat(n-1-i);\n }\n }\n }\n }\n return r[0] + '\\n' + r[1].split('').reverse().join('');\n}\nwrite(main());"}, {"source_code": "'use strict'\nconst g = (v, k) => {\n let r = 0;\n while (v % k === 0) { v = v / k; r++; }\n return r;\n}\nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number).map(i => [ g(i, 2), g(i, 5) ]); }\n \n \nconst f = (n, M) => {\n const Two = M[0][0][0];\n const Five = M[0][0][1];\n const q = [ Two, Five, Math.min(Two, Five), 0, 0, '', 0 ];\n \n while (q.length) {\n let i = q.shift();\n if (i[6] === 2*n) return [ i[2], i[5] ].join('\\n');\n if (i[3] < n) {\n const j = M[i[4]][i[3] + 1];\n const two = i[0] + j[0];\n const five = i[1] + j[1];\n const next = [ two, five, Math.min(two, five), i[3] + 1, i[4], i[5] + 'R', i[6] + 1 ];\n const index = q.findIndex(item => item[2] > next[2] || (item[2] === next[2] && item[6] < next[6]));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n if (i[4] < n) {\n const j = M[i[4] + 1][i[3]];\n const two = i[0] + j[0];\n const five = i[1] + j[1];\n const next = [ two, five, Math.min(two, five), i[3], i[4] + 1, i[5] + 'D', i[6] + 1 ];\n const index = q.findIndex(item => item[2] > next[2] || (item[2] === next[2] && item[6] < next[6]));\n if (index !== -1) q.splice(index, 0, next);\n else q.push(next);\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "'use strict'\n \nconst n = parseInt(readline());\nconst M = [];\nfor(let i = 0; i < n; i++) { M[i] = readline().split(' ').map(Number); }\n \nconst f = (n, M) => {\n const q = [ { v: M[0][0], x: 0, y: 0, h: '', z: `${M[0][0]}`.split('').reverse().findIndex(i => i !== '0') } ];\n \n while (q.length) {\n let i = q.sort((a, b) => a.z > b.z ? 1 : a.z < b.z ? -1 : a.h.length - b.h.length).shift();\n if (i.x === n && i.y === n) return [ i.z, i.h ].join('\\n');\n if (i.x < n) {\n let v = i.v * M[i.x + 1][i.y];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x + 1, y: i.y, h: i.h + 'D' });\n }\n if (i.y < n) {\n let v = i.v * M[i.x][i.y + 1];\n let z = i.z;\n if (v % 10 === 0) { v = v / 10; z++; }\n q.push({ z, v, x: i.x, y: i.y + 1, h: i.h + 'R' });\n }\n }\n}\nwrite(f(n - 1, M));"}, {"source_code": "var size = Number(readline());\n\n// 1. 입력값을 배열로 정렬\n// 2. 한 번씩 순회하면서 0의 개수를 구한다. (2의 배수와 5의 배수의 개수)\n// 3. trailing zeros가 가장 적은 경로를 구한다.\n\nvar matrix = [];\n\nvar line = [];\nvar num;\nvar countTwo = 0;\nvar countFive = 0;\n// put the inputs into 'matrix' two dimensional array\nfor (var i = 0; i < size; i++) {\n line = readline().split(\" \");\n\n // transform the input number into number of twos and fives\n for (var k = 0; k < line.length; k++) {\n num = line[k];\n countTwo = 0;\n while (num % 2 == 0) {\n num = num / 2;\n countTwo++;\n }\n num = line[k];\n countFive = 0;\n while (num % 5 == 0) {\n num = num / 5;\n countFive++;\n }\n\n line[k] = {\n 2: countTwo,\n 5: countFive\n }\n }\n matrix.push(line);\n}\n// print(JSON.stringify(matrix));\n\nvar result = [];\ngoNext([0, 0], \"\", {2: 0, 5: 0});\ngetTheLeastRoundWay();\n\n// 경로를 만드는 재귀함수를 만든다.\nfunction goNext(currentIndex, way, numberOfTwoNFive) {\n\n if (endOfTheRoute(currentIndex)) {\n result.push({way: way, trailingZeros: calculateTrailingZeros(numberOfTwoNFive)})\n return;\n }\n // 아래쪽 오른쪽으로 이동\n if (canGoDown(currentIndex)) goNext(\n [currentIndex[0] + 1, currentIndex[1]],\n way + \"D\",\n {\n 2: numberOfTwoNFive[2] + matrix[currentIndex[0]][currentIndex[1]][2],\n 5: numberOfTwoNFive[5] + matrix[currentIndex[0]][currentIndex[1]][5]\n });\n if (canGoRight(currentIndex)) goNext([currentIndex[0], currentIndex[1] + 1], way + \"R\", {\n 2: numberOfTwoNFive[2] + matrix[currentIndex[0]][currentIndex[1]][2],\n 5: numberOfTwoNFive[5] + matrix[currentIndex[0]][currentIndex[1]][5]\n });\n}\n\nfunction endOfTheRoute(currentIndex) {return currentIndex[0] === size - 1 && currentIndex[1] === size - 1;}\n\nfunction canGoDown(currentIndex) {return currentIndex[0] !== size - 1;}\n\nfunction canGoRight(currentIndex) {return currentIndex[1] !== size - 1;}\n\nfunction calculateTrailingZeros(numberOfTwoNFive) {\n\n // print(JSON.stringify(numberOfTwoNFive));\n var twos = numberOfTwoNFive[2];\n var fives = numberOfTwoNFive[5];\n\n if (twos === 0 || fives === 0) return 0;\n if (twos > fives) return fives;\n else return twos;\n}\n\nfunction getTheLeastRoundWay() {\n result.sort((a, b) => a.trailingZeros - b.trailingZeros);\n // print(JSON.stringify(result));\n print(result[0].trailingZeros);\n print(result[0].way);\n}\n"}, {"source_code": "var size = Number(readline());\n\n// 1. 입력값을 배열로 정렬\n// 2. 한 번씩 순회하면서 0의 개수를 구한다. (2의 배수와 5의 배수의 개수)\n// 3. trailing zeros가 가장 적은 경로를 구한다.\n\nvar matrix = [];\nvar left;\nvar top;\nvar leftExist;\nvar topExist;\nvar leftElement;\nvar topElement;\nvar currentElement;\n\nvar leastMatrix = [];\nvar lastCell = [];\n\n// put the inputs into 'matrix' two dimensional array\nfor (var column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(s => parseInt(s)));\n leastMatrix.push([]);\n\n for (var row = 0; row < size; row++) {\n matrix[column][row] = factorizePrime(matrix[column][row]);\n currentElement = matrix[column][row];\n\n left = row - 1;\n top = column - 1;\n leftExist = left >= 0;\n topExist = top >= 0;\n\n for (var d = 0; d < 2; d++) {\n // least two matrix\n leftElement = leftExist ? leastMatrix[column][left] : null;\n topElement = topExist ? leastMatrix[top][row] : null;\n\n if (!topExist && !leftExist) {\n leastMatrix[column].push([\n currentElement[0],\n currentElement[1]\n ])\n } else if (topExist && !leftExist) {\n leastMatrix[column].push([\n currentElement[0] + topElement[0],\n currentElement[1] + topElement[1]\n ])\n } else if (!topExist && leftExist) {\n leastMatrix[column].push([\n currentElement[0] + leftElement[0],\n currentElement[1] + leftElement[1]\n ]);\n } else if (topExist && leftExist) {\n if (topElement[d === 0 ? 0 : 1] === leftElement[d === 0 ? 0 : 1]) {\n leastMatrix[column].push([\n currentElement[0] + (topElement[d === 0 ? 1 : 0] <= leftElement[d === 0 ? 1 : 0] ? topElement[0] : leftElement[0]),\n currentElement[1] + (topElement[d === 0 ? 1 : 0] <= leftElement[d === 0 ? 1 : 0] ? topElement[1] : leftElement[1]),\n ]);\n } else if (topElement[d === 0 ? 0 : 1] <= leftElement[d === 0 ? 0 : 1]) {\n leastMatrix[column].push([\n currentElement[0] + topElement[0],\n currentElement[1] + topElement[1],\n ]);\n } else {\n leastMatrix[column].push([\n currentElement[0] + leftElement[0],\n currentElement[1] + leftElement[1],\n ]);\n }\n }\n\n lastCell[d] = leastMatrix[column][row];\n\n }\n\n }\n}\n// print(JSON.stringify(matrix));\n// print(JSON.stringify(leastMatrix[0]));\n// print(JSON.stringify(leastMatrix[1]));\n\nvar twoOrFive;\nvar topCell;\nvar leftCell;\nvar zeros = [];\nfor (d = 0; d < 2; d++) {\n if (lastCell[d][0] === 0 || lastCell[d][1] === 0) {\n zeros.push(0);\n } else if (lastCell[d][0] <= lastCell[d][1]) {\n zeros.push(lastCell[d][0]);\n } else {\n zeros.push(lastCell[d][1]);\n }\n // print(`zeros: ${zeros}`)\n}\n\n// print(JSON.stringify(zeros));\n\nif (zeros[0] <= zeros[1]) twoOrFive = 0;\nelse twoOrFive = 1;\n\nprint(zeros[twoOrFive]);\n\nrow = column = size - 1;\n// print(`row: ${row}, column: ${column}`);\nvar route = \"\";\nwhile (1) {\n left = row - 1;\n top = column - 1;\n leftExist = left >= 0;\n topExist = top >= 0;\n topCell = topExist ? leastMatrix[top][row] : null;\n leftCell = leftExist ? leastMatrix[column][left] : null;\n\n // print(`current: ${column} ${row}, left: ${left}, top: ${top}, leftExist: ${leftExist}, topExist: ${topExist}, topCell: ${topCell}, leftCell: ${leftCell}`)\n\n if (!topExist && !leftExist) {\n print(route);\n break;\n } else if (topExist && !leftExist) {\n route = \"D\" + route;\n column--;\n } else if (!topExist && leftExist) {\n route = \"R\" + route;\n row--;\n } else if (topExist && leftExist) {\n\n if (topCell[twoOrFive] < leftCell[twoOrFive]) {\n route = \"D\" + route;\n column--;\n } else if (topCell[twoOrFive] > leftCell[twoOrFive]) {\n route = \"R\" + route;\n row--;\n } else if (topCell[twoOrFive] === leftCell[twoOrFive]) {\n\n if (topCell[twoOrFive === 0 ? 1 : 0] <= leftCell[twoOrFive === 0 ? 1 : 0]) {\n route = \"D\" + route;\n column--;\n } else {\n route = \"R\" + route;\n row--;\n }\n\n }\n\n }\n\n}\n\n\nvar twos = 0;\nvar fives = 0;\n\nfunction factorizePrime(num) {\n twos = 0;\n fives = 0;\n while (num % 2 === 0) {\n num /= 2;\n twos++;\n }\n while (num % 5 === 0) {\n num /= 5;\n fives++;\n }\n return [twos, fives];\n}\n\n\n"}, {"source_code": "var size = parseInt(readline());\n\nvar matrix = [];\nvar column; var row;\nvar zeroPosition = null;\nfor (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n for (row = 0; row < size; row++) if (matrix[column][row] === 0) zeroPosition = [column, row];\n}\n\nfunction factorize(prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nvar accMatrix = [];\nvar accPath = [];\nfunction accumulate(prime) {\n\n for (column = 0; column < size; column++) {\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column - 1 >= 0 && row - 1 >= 0) {\n if (accMatrix[column - 1][row] < accMatrix[column][row - 1]) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n }\n } else if (column - 1 >= 0) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else if (row - 1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n return [accMatrix[size-1][size-1], accPath]\n}\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\n\nif (zeroPosition !== null && best[0] > 1) {\n trailingZeros = 1;\n\n for (i = 0; i < zeroPosition[0]; i++) {path += \"D\";}\n for (i = 0; i < size - 1; i++) {path += \"R\";}\n for (i = zeroPosition[0]; i < size - 1; i++) {path += \"D\";}\n\n} else {\n trailingZeros = best[0];\n\n accPath = best[1];\n for (column = size - 1; column >= 0;) for (row = size - 1; row >= 0;) {\n if (column === 0 && row === 0) {column--;row--;}\n else {\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n }\n }\n\n}\n\nprint(trailingZeros);\nprint(path);"}, {"source_code": "var size = parseInt(readline());\n\nvar matrix = [];\nvar column;\nvar row;\nvar zeroPosition = null;\nfor (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n for (row = 0; row < size; row++) if (matrix[column][row] === 0) zeroPosition = [column, row];\n}\n\nfunction factorize(prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nvar accMatrix = [];\nvar accPath = [];\n\nfunction accumulate(prime) {\n\n for (column = 0; column < size; column++) {\n accMatrix[column] = [];\n accPath[column] = [];\n }\n accMatrix[0][0] = factorize(prime, matrix[0][0]);\n accPath[0][0] = \"\";\n // print('accMatrix[0][0]', accMatrix[0][0])\n // print('accPath[0][0]', accPath[0][0])\n\n for (column = 1; column < size; column++) {\n accMatrix[0][column] = accMatrix[0][column - 1] + factorize(prime, matrix[0][column]);\n accPath[0][column] = \"R\";\n accMatrix[column][0] = accMatrix[column - 1][0] + factorize(prime, matrix[column][0]);\n accPath[column][0] = \"D\";\n\n // print(accMatrix[0][column])\n // print(accPath[0][column])\n // print(accMatrix[column][0])\n // print(accPath[column][0])\n }\n\n // print('---')\n\n for (column = 1; column < size; column++) for (row = 1; row < size; row++) {\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n if (accMatrix[column - 1][row] < accMatrix[column][row - 1]) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n }\n\n // print(accMatrix[column][row])\n // print(accPath[column][row])\n }\n\n return [accMatrix[size - 1][size - 1], accPath]\n}\n\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\n\nif (zeroPosition !== null && best[0] > 1) {\n trailingZeros = 1;\n\n for (i = 0; i < zeroPosition[0]; i++) {\n path += \"D\";\n }\n for (i = 0; i < size - 1; i++) {\n path += \"R\";\n }\n for (i = zeroPosition[0]; i < size - 1; i++) {\n path += \"D\";\n }\n\n} else {\n trailingZeros = best[0];\n\n accPath = best[1];\n for (column = size - 1; column >= 0;) for (row = size - 1; row >= 0;) {\n if (column === 0 && row === 0) {column--; row--;}\n else {\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n }\n }\n}\n\nprint(trailingZeros);\nprint(path);"}, {"source_code": "var size = Number(readline());\n\nvar matrix = [];\nvar column;\nvar row;\nvar zeroPosition = null;\nconstructMatrix();\n\nvar accMatrix = [];\nvar accPath = [];\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\n\ntrailingZeros = zeroPosition !== null && best[0] > 1 ? 1 : best[0];\nfindPath(best);\n\nprint(trailingZeros);\nprint(path);\n\nfunction constructMatrix() {\n for (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n for (row = 0; row < size; row++) {\n\n if (matrix[column][row] === 0) {\n zeroPosition = [column, row];\n }\n }\n\n }\n}\n\nfunction factorize(prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {\n num /= prime;\n count++\n }\n return count;\n}\n\nfunction accumulate(prime) {\n\n for (column = 0; column < size; column++) {\n\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column - 1 >= 0 && row - 1 >= 0) {\n\n if (accMatrix[column - 1][row] < accMatrix[column][row - 1]) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n }\n\n } else if (column - 1 >= 0) {\n accMatrix[column][row] += accMatrix[column - 1][row];\n accPath[column][row] = \"D\";\n } else if (row - 1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row - 1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n\n return [accMatrix[size - 1][size - 1], accPath]\n\n}\n\nfunction findPath(items) {\n\n if (zeroPosition !== null && best[0] > 1) {\n for (i = 0; i < zeroPosition[0]; i++) {\n path += \"D\";\n }\n for (i = 0; i < size - 1; i++) {\n path += \"R\";\n }\n for (i = zeroPosition[0]; i < size - 1; i++) {\n path += \"D\";\n }\n } else {\n accPath = items[1];\n\n for (column = size - 1; column >= 0;) {\n for (row = size - 1; row >= 0;) {\n if (column === 0 && row === 0) {\n column--;\n row--;\n } else {\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n }\n }\n }\n }\n\n\n}\n\n// Wrong answer on test 27"}, {"source_code": "var size = Number(readline());\n\n// 1. 입력값을 배열로 정렬\n// 2. 한 번씩 순회하면서 0의 개수를 구한다. (2의 배수와 5의 배수의 개수)\n// 3. trailing zeros가 가장 적은 경로를 구한다.\n\nvar matrix = [];\nvar left;\nvar top;\nvar leftExist;\nvar topExist;\nvar leftElement;\nvar topElement;\nvar currentElement;\n\nvar leastMatrix = [\n [],\n []\n];\n\n// put the inputs into 'matrix' two dimensional array\nfor (var column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(s => parseInt(s)));\n leastMatrix[0].push([]);\n leastMatrix[1].push([]);\n\n for (var row = 0; row < size; row++) {\n matrix[column][row] = factorizePrime(matrix[column][row]);\n currentElement = matrix[column][row];\n\n // print(\"====\")\n // print(`column:row ${column}:${row}`);\n // print(JSON.stringify(matrix[column][row]));\n\n left = row - 1;\n top = column - 1;\n leftExist = left >= 0;\n topExist = top >= 0;\n // print(`left: ${left}, top: ${top}, leftExist: ${leftExist}, topExist: ${topExist}`);\n\n\n for (var d = 0; d < 2; d++) {\n // least two matrix\n leftElement = leftExist ? leastMatrix[d][column][left] : null;\n topElement = topExist ? leastMatrix[d][top][row] : null;\n // print(`leftElement: ${leftElement}, topElement: ${topElement}, currentElement: ${currentElement}`);\n\n if (!topExist && !leftExist) {\n\n leastMatrix[d][column].push([\n currentElement[0],\n currentElement[1]\n ])\n\n } else if (topExist && !leftExist) {\n\n leastMatrix[d][column].push([\n currentElement[0] + topElement[0],\n currentElement[1] + topElement[1]\n ])\n\n } else if (!topExist && leftExist) {\n\n leastMatrix[d][column].push([\n currentElement[0] + leftElement[0],\n currentElement[1] + leftElement[1]\n ]);\n\n } else if (topExist && leftExist) {\n\n if (topElement[d === 0 ? 0 : 1] === leftElement[d === 0 ? 0 : 1]) {\n\n leastMatrix[d][column].push([\n currentElement[0] + (topElement[d === 0 ? 1 : 0] <= leftElement[d === 0 ? 1 : 0] ? topElement[0] : leftElement[0]),\n currentElement[1] + (topElement[d === 0 ? 1 : 0] <= leftElement[d === 0 ? 1 : 0] ? topElement[1] : leftElement[1]),\n ]);\n\n } else if (topElement[d === 0 ? 0 : 1] <= leftElement[d === 0 ? 0 : 1]) {\n\n leastMatrix[d][column].push([\n currentElement[0] + topElement[0],\n currentElement[1] + topElement[1],\n ]);\n\n } else {\n\n leastMatrix[d][column].push([\n currentElement[0] + leftElement[0],\n currentElement[1] + leftElement[1],\n ]);\n\n }\n }\n\n // print(`result: ${leastMatrix[d][column][row]}`);\n\n }\n\n }\n}\n// print(JSON.stringify(matrix));\n// print(JSON.stringify(leastMatrix[0]));\n// print(JSON.stringify(leastMatrix[1]));\n\ngetTrailingZeros();\n\nvar twoOrFive;\nvar topCell;\nvar leftCell;\nvar lastCell;\nfunction getTrailingZeros () {\n\n var zeros = [];\n for (d = 0; d < 2; d++) {\n lastCell = leastMatrix[d][size-1][size-1];\n // print(`d: ${d}`);\n // print(`lastCell: ${lastCell}`);\n // print(`zeros: ${zeros}`);\n if (lastCell[0] === 0 || lastCell[1] === 0) {\n zeros.push(0);\n } else if (lastCell[0] <= lastCell[1]) {\n zeros.push(lastCell[0]);\n } else {\n zeros.push(lastCell[1]);\n }\n // print(`zeros: ${zeros}`)\n }\n\n // print(JSON.stringify(zeros));\n\n if (zeros[0] <= zeros[1]) {\n twoOrFive = 0;\n leastMatrix = leastMatrix[0];\n } else {\n twoOrFive = 1;\n leastMatrix = leastMatrix[1];\n }\n print(zeros[twoOrFive]);\n\n row = column = size-1;\n // print(`row: ${row}, column: ${column}`);\n var route = \"\";\n while(1) {\n left = row - 1;\n top = column - 1;\n leftExist = left >= 0;\n topExist = top >= 0;\n topCell = topExist ? leastMatrix[top][row] : null;\n leftCell = leftExist ? leastMatrix[column][left] : null;\n\n // print(`left: ${left}, top: ${top}, leftExist: ${leftExist}, topExist: ${topExist}, topCell: ${topCell}, leftCell: ${leftCell}`)\n if (!topExist && !leftExist) {\n print(route);\n break;\n } else if (topExist && !leftExist) {\n route = \"D\" + route;\n column--;\n } else if (!topExist && leftExist) {\n route = \"R\" + route;\n row--;\n } else if (topExist && leftExist) {\n\n if (topCell[twoOrFive] < leftCell[twoOrFive]) {\n route = \"D\" + route;\n column--;\n } else if (topCell[twoOrFive] >= leftCell[twoOrFive]) {\n route = \"R\" + route;\n row--;\n } else if (topCell[twoOrFive] === leftCell[twoOrFive]) {\n\n if (topCell[!twoOrFive] < leftCell[!twoOrFive]) {\n route = \"D\" + route;\n column--;\n } else {\n route = \"R\" + route;\n row--;\n }\n\n }\n\n }\n\n }\n\n}\n\nvar twos = 0; var fives = 0;\nfunction factorizePrime(num) {\n twos = 0;\n fives = 0;\n while (num % 2 === 0) {\n num /= 2;\n twos++;\n }\n while (num % 5 === 0) {\n num /= 5;\n fives++;\n }\n return [twos, fives];\n}\n\n\n"}, {"source_code": "var size = Number(readline());\n\nvar matrix = [];\nvar column; var row;\nvar zeroPosition = [];\nvar zeroExists = false;\nconstructMatrix();\n\nvar accMatrix = [];\nvar accPath = [];\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\n\ntrailingZeros = zeroExists && best[0] > 1 ? 1 : best[0];\nfindPath(best);\n\nprint(trailingZeros);\nprint(path);\n\nfunction constructMatrix () {\n for (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n if (!zeroExists && matrix[column][row] === 0) {\n zeroExists = true;\n zeroPosition = [column, row];\n }\n }\n}\n\nfunction factorize (prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nfunction accumulate (prime) {\n\n for (column = 0; column < size; column++) {\n\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column-1 >= 0 && row-1 >= 0) {\n\n if (accMatrix[column-1][row] < accMatrix[column][row-1]) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n }\n\n } else if (column-1 >= 0) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else if (row-1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n\n return [accMatrix[size-1][size-1], accPath]\n\n}\n\nfunction findPath (items) {\n\n if (zeroExists && best[0] > 1) {\n for(i = 0; i < zeroPosition[0]; i++) {\n path += \"D\";\n }\n for(i = 0; i < size-1; i++) {\n path += \"R\";\n }\n for (i = zeroPosition[0]; i < size-1; i++) {\n path += \"D\";\n }\n } else {\n accPath = items[1];\n\n // print(`accMatrix: ${accMatrix}`)\n // print(`accPath: ${accPath}`)\n\n for(column = size-1; column >= 0;) {\n for (row = size-1; row >= 0;) {\n // print(`column: ${column}, row: ${row}`)\n if (column === 0 && row === 0) {\n column--; row--;\n break;\n }\n // print(`accPath[column][row]: ${accPath[column][row]}`)\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n // print(`path: ${path}`)\n }\n }\n }\n\n\n}\n\n// Wrong answer on test 27"}, {"source_code": "var size = Number(readline());\n\nvar matrix = [];\nconstructMatrix();\n\n\nvar accMatrix = [];\nvar accPath = [];\nvar twos = accumulate(2);\nvar fives = accumulate(5);\n\n// print(twos[0])\n// print(fives[0])\n\nvar trailingZeros;\nvar path = \"\";\nif (twos[0] === 0 && fives[0] === 0) {\n trailingZeros = 0;\n findPath(twos);\n} else if (twos[0] < fives[0]) {\n trailingZeros = twos[0];\n findPath(twos);\n} else {\n trailingZeros = fives[0];\n findPath(fives);\n}\n\nprint(trailingZeros);\nprint(path);\n\nfunction constructMatrix () {\n for (var column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n }\n}\n\nfunction factorize (prime, num) {\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nfunction accumulate (prime) {\n\n for (var column = 0; column < size; column++) {\n\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (var row = 0; row < size; row++) {\n\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column-1 >= 0 && row-1 >= 0) {\n\n if (accMatrix[column-1][row] < accMatrix[column][row-1]) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n }\n\n } else if (column-1 >= 0) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else if (row-1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n\n return [accMatrix[size-1][size-1], accPath]\n\n}\n\nfunction findPath (items) {\n\n accMatrix = items[0];\n accPath = items[1];\n\n // print(`accMatrix: ${accMatrix}`)\n // print(`accPath: ${accPath}`)\n\n for(var column = size-1; column >= 0;) {\n for (var row = size-1; row >= 0;) {\n // print(`column: ${column}, row: ${row}`)\n if (column === 0 && row === 0) {\n column--; row--;\n break;\n }\n // print(`accPath[column][row]: ${accPath[column][row]}`)\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n // print(`path: ${path}`)\n }\n }\n}"}, {"source_code": "var size = Number(readline());\n\n// 1. 입력값을 배열로 정렬\n// 2. 한 번씩 순회하면서 0의 개수를 구한다. (2의 배수와 5의 배수의 개수)\n// 3. trailing zeros가 가장 적은 경로를 구한다.\n\nvar matrix = [];\nvar left;\nvar top;\nvar leftExist;\nvar topExist;\nvar leftElement;\nvar topElement;\nvar currentElement;\n\nvar leastMatrix = [];\nvar lastCell = [];\n\n// put the inputs into 'matrix' two dimensional array\nfor (var column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(s => parseInt(s)));\n leastMatrix.push([]);\n\n for (var row = 0; row < size; row++) {\n matrix[column][row] = factorizePrime(matrix[column][row]);\n currentElement = matrix[column][row];\n\n left = row - 1;\n top = column - 1;\n leftExist = left >= 0;\n topExist = top >= 0;\n\n for (var d = 0; d < 2; d++) {\n // least two matrix\n leftElement = leftExist ? leastMatrix[column][left] : null;\n topElement = topExist ? leastMatrix[top][row] : null;\n\n if (!topExist && !leftExist) {\n leastMatrix[column][row] = [\n currentElement[0],\n currentElement[1]\n ]\n } else if (topExist && !leftExist) {\n leastMatrix[column][row] = [\n currentElement[0] + topElement[0],\n currentElement[1] + topElement[1]\n ]\n } else if (!topExist && leftExist) {\n leastMatrix[column][row] = [\n currentElement[0] + leftElement[0],\n currentElement[1] + leftElement[1]\n ]\n } else if (topExist && leftExist) {\n if (topElement[d === 0 ? 0 : 1] === leftElement[d === 0 ? 0 : 1]) {\n leastMatrix[column][row] = [\n currentElement[0] + (topElement[d === 0 ? 1 : 0] <= leftElement[d === 0 ? 1 : 0] ? topElement[0] : leftElement[0]),\n currentElement[1] + (topElement[d === 0 ? 1 : 0] <= leftElement[d === 0 ? 1 : 0] ? topElement[1] : leftElement[1]),\n ]\n } else if (topElement[d === 0 ? 0 : 1] <= leftElement[d === 0 ? 0 : 1]) {\n leastMatrix[column][row] = [\n currentElement[0] + topElement[0],\n currentElement[1] + topElement[1],\n ]\n } else {\n leastMatrix[column][row] = [\n currentElement[0] + leftElement[0],\n currentElement[1] + leftElement[1],\n ]\n }\n }\n\n lastCell[d] = leastMatrix[column][row];\n\n }\n\n }\n}\n// print(JSON.stringify(matrix));\n// print(JSON.stringify(leastMatrix));\n\nvar twoOrFive;\nvar topCell;\nvar leftCell;\nvar zeros = [];\n\nfor (d = 0; d < 2; d++) {\n // print(`lastCell[${d}]: ${lastCell[d]}`);\n if (lastCell[d][0] === 0 || lastCell[d][1] === 0) {\n zeros.push(0);\n } else if (lastCell[d][0] <= lastCell[d][1]) {\n zeros.push(lastCell[d][0]);\n } else {\n zeros.push(lastCell[d][1]);\n }\n // print(`zeros: ${zeros}`)\n}\n\n// print(JSON.stringify(zeros));\n\nif (zeros[0] <= zeros[1]) twoOrFive = 0;\nelse twoOrFive = 1;\n\n// print(twoOrFive);\nprint(zeros[twoOrFive]);\n\nrow = column = size - 1;\n// print(`row: ${row}, column: ${column}`);\nvar route = \"\";\nwhile (1) {\n left = row - 1;\n top = column - 1;\n leftExist = left >= 0;\n topExist = top >= 0;\n topCell = topExist ? leastMatrix[top][row] : null;\n leftCell = leftExist ? leastMatrix[column][left] : null;\n\n // print(`current: ${column} ${row}, left: ${left}, top: ${top}, leftExist: ${leftExist}, topExist: ${topExist}, topCell: ${topCell}, leftCell: ${leftCell}`)\n\n if (!topExist && !leftExist) {\n print(route);\n break;\n } else if (topExist && !leftExist) {\n route = \"D\" + route;\n column--;\n } else if (!topExist && leftExist) {\n route = \"R\" + route;\n row--;\n } else if (topExist && leftExist) {\n\n if (topCell[twoOrFive] < leftCell[twoOrFive]) {\n route = \"D\" + route;\n column--;\n } else if (topCell[twoOrFive] > leftCell[twoOrFive]) {\n route = \"R\" + route;\n row--;\n } else if (topCell[twoOrFive] === leftCell[twoOrFive]) {\n\n if (topCell[twoOrFive === 0 ? 1 : 0] <= leftCell[twoOrFive === 0 ? 1 : 0]) {\n route = \"D\" + route;\n column--;\n } else {\n route = \"R\" + route;\n row--;\n }\n\n }\n\n }\n\n}\n\n\nvar twos = 0;\nvar fives = 0;\n\nfunction factorizePrime(num) {\n twos = 0;\n fives = 0;\n while (num % 2 === 0) {\n num /= 2;\n twos++;\n }\n while (num % 5 === 0) {\n num /= 5;\n fives++;\n }\n return [twos, fives];\n}\n\n\n"}, {"source_code": "var size = Number(readline());\n\nvar matrix = [];\nvar column; var row;\nvar zeroIndex = [];\nvar zeroExists = false;\nconstructMatrix();\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\nif (zeroExists) {\n\n trailingZeros = 0;\n for(i = 0; i < zeroIndex[0]; i++) {\n path += \"D\";\n }\n for(i = 0; i < zeroIndex[1]; i++) {\n path += \"R\";\n }\n for (i = zeroIndex[0]; i < size-1; i++) {\n path += \"D\";\n }\n for (i = zeroIndex[1]; i < size-1; i++) {\n path += \"R\";\n }\n\n} else {\n var accMatrix = [];\n var accPath = [];\n var twos = accumulate(2);\n var fives = accumulate(5);\n\n// print(twos[0])\n// print(fives[0])\n if (twos[0] === 0 && fives[0] === 0) {\n trailingZeros = 0;\n findPath(twos);\n } else if (twos[0] < fives[0]) {\n trailingZeros = twos[0];\n findPath(twos);\n } else {\n trailingZeros = fives[0];\n findPath(fives);\n }\n\n}\nprint(trailingZeros);\nprint(path);\n\nfunction constructMatrix () {\n for (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n for (row = 0; row < size; row++) {\n if (matrix[column][row] === 0) {\n zeroExists = true;\n zeroIndex = [column, row];\n column = size;\n row = size;\n break;\n }\n }\n }\n}\n\nfunction factorize (prime, num) {\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nfunction accumulate (prime) {\n\n for (column = 0; column < size; column++) {\n\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column-1 >= 0 && row-1 >= 0) {\n\n if (accMatrix[column-1][row] < accMatrix[column][row-1]) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n }\n\n } else if (column-1 >= 0) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else if (row-1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n\n return [accMatrix[size-1][size-1], accPath]\n\n}\n\nfunction findPath (items) {\n\n accMatrix = items[0];\n accPath = items[1];\n\n // print(`accMatrix: ${accMatrix}`)\n // print(`accPath: ${accPath}`)\n\n for(column = size-1; column >= 0;) {\n for (row = size-1; row >= 0;) {\n // print(`column: ${column}, row: ${row}`)\n if (column === 0 && row === 0) {\n column--; row--;\n break;\n }\n // print(`accPath[column][row]: ${accPath[column][row]}`)\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n // print(`path: ${path}`)\n }\n }\n}"}, {"source_code": "var size = Number(readline());\n\nvar matrix = [];\nvar column; var row;\nvar zeroPosition = [];\nvar zeroExists = false;\nconstructMatrix();\n\nvar accMatrix = [];\nvar accPath = [];\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] < fives[0] ? twos : fives;\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\n\ntrailingZeros = zeroExists && best[0] > 1 ? 1 : best[0];\nfindPath(best);\n\nprint(trailingZeros);\nprint(path);\n\nfunction constructMatrix () {\n for (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n if (!zeroExists && matrix[column][row] === 0) {\n zeroExists = true;\n zeroPosition = [column, row];\n }\n }\n}\n\nfunction factorize (prime, num) {\n var count = 0;\n if (num === 0) return 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nfunction accumulate (prime) {\n\n for (column = 0; column < size; column++) {\n\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column-1 >= 0 && row-1 >= 0) {\n\n if (accMatrix[column-1][row] < accMatrix[column][row-1]) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n }\n\n } else if (column-1 >= 0) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else if (row-1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n\n return [accMatrix[size-1][size-1], accPath]\n\n}\n\nfunction findPath (items) {\n\n if (zeroExists && best[0] > 1) {\n for(i = 0; i < zeroPosition[0]; i++) {\n path += \"D\";\n }\n for(i = 0; i < size-1; i++) {\n path += \"R\";\n }\n for (i = zeroPosition[0]; i < size-1; i++) {\n path += \"D\";\n }\n } else {\n accMatrix = items[0];\n accPath = items[1];\n\n // print(`accMatrix: ${accMatrix}`)\n // print(`accPath: ${accPath}`)\n\n for(column = size-1; column >= 0;) {\n for (row = size-1; row >= 0;) {\n // print(`column: ${column}, row: ${row}`)\n if (column === 0 && row === 0) {\n column--; row--;\n break;\n }\n // print(`accPath[column][row]: ${accPath[column][row]}`)\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n // print(`path: ${path}`)\n }\n } \n }\n \n \n}\n\n// Wrong answer on test 27"}, {"source_code": "var size = Number(readline());\n\nvar matrix = [];\nvar column; var row;\nvar zeroPosition = null;\nconstructMatrix();\n\nvar accMatrix = [];\nvar accPath = [];\nvar twos = accumulate(2);\nvar fives = accumulate(5);\nvar best = twos[0] <= fives[0] ? twos : fives;\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\n\ntrailingZeros = zeroPosition !== null && best[0] > 1 ? 1 : best[0];\nfindPath(best);\n\nprint(trailingZeros);\nprint(path);\n\nfunction constructMatrix () {\n for (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n if (matrix[column][row] === 0) {\n zeroPosition = [column, row];\n }\n }\n}\n\nfunction factorize (prime, num) {\n if (num === 0) return 0;\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nfunction accumulate (prime) {\n\n for (column = 0; column < size; column++) {\n\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column-1 >= 0 && row-1 >= 0) {\n\n if (accMatrix[column-1][row] < accMatrix[column][row-1]) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n }\n\n } else if (column-1 >= 0) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else if (row-1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n\n return [accMatrix[size-1][size-1], accPath]\n\n}\n\nfunction findPath (items) {\n\n if (zeroPosition !== null && best[0] > 1) {\n for(i = 0; i < zeroPosition[0]; i++) {\n path += \"D\";\n }\n for(i = 0; i < size-1; i++) {\n path += \"R\";\n }\n for (i = zeroPosition[0]; i < size-1; i++) {\n path += \"D\";\n }\n } else {\n accPath = items[1];\n\n // print(`accMatrix: ${accMatrix}`)\n // print(`accPath: ${accPath}`)\n\n for(column = size-1; column >= 0;) {\n for (row = size-1; row >= 0;) {\n // print(`column: ${column}, row: ${row}`)\n if (column === 0 && row === 0) {\n column--; row--;\n break;\n }\n // print(`accPath[column][row]: ${accPath[column][row]}`)\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n // print(`path: ${path}`)\n }\n }\n }\n\n\n}\n\n// Wrong answer on test 27"}, {"source_code": "var size = Number(readline());\n\nvar matrix = [];\nvar column; var row;\nvar zeroIndex = [];\nvar zeroExists = false;\nconstructMatrix();\n\nvar trailingZeros;\nvar path = \"\";\nvar i = 0;\nif (zeroExists) {\n\n trailingZeros = 1;\n for(i = 0; i < zeroIndex[0]; i++) {\n path += \"D\";\n }\n for(i = 0; i < zeroIndex[1]; i++) {\n path += \"R\";\n }\n for (i = zeroIndex[0]; i < size-1; i++) {\n path += \"D\";\n }\n for (i = zeroIndex[1]; i < size-1; i++) {\n path += \"R\";\n }\n\n} else {\n var accMatrix = [];\n var accPath = [];\n var twos = accumulate(2);\n var fives = accumulate(5);\n\n// print(twos[0])\n// print(fives[0])\n if (twos[0] === 0 && fives[0] === 0) {\n trailingZeros = 0;\n findPath(twos);\n } else if (twos[0] <= fives[0]) {\n trailingZeros = twos[0];\n findPath(twos);\n } else {\n trailingZeros = fives[0];\n findPath(fives);\n }\n\n}\nprint(trailingZeros);\nprint(path);\n\nfunction constructMatrix () {\n for (column = 0; column < size; column++) {\n matrix.push(readline().split(\" \").map(n => parseInt(n)));\n\n for (row = 0; row < size; row++) {\n if (matrix[column][row] === 0) {\n zeroExists = true;\n zeroIndex = [column, row];\n column = size;\n row = size;\n break;\n }\n }\n }\n}\n\nfunction factorize (prime, num) {\n var count = 0;\n while (num % prime === 0) {num /= prime; count++}\n return count;\n}\n\nfunction accumulate (prime) {\n\n for (column = 0; column < size; column++) {\n\n accMatrix[column] = [];\n accPath[column] = [];\n\n for (row = 0; row < size; row++) {\n\n accMatrix[column][row] = factorize(prime, matrix[column][row]);\n\n if (column-1 >= 0 && row-1 >= 0) {\n\n if (accMatrix[column-1][row] < accMatrix[column][row-1]) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n }\n\n } else if (column-1 >= 0) {\n accMatrix[column][row] += accMatrix[column-1][row];\n accPath[column][row] = \"D\";\n } else if (row-1 >= 0) {\n accMatrix[column][row] += accMatrix[column][row-1];\n accPath[column][row] = \"R\";\n } else {\n accPath[column][row] = \"\";\n }\n\n }\n }\n\n return [accMatrix[size-1][size-1], accPath]\n\n}\n\nfunction findPath (items) {\n\n accMatrix = items[0];\n accPath = items[1];\n\n // print(`accMatrix: ${accMatrix}`)\n // print(`accPath: ${accPath}`)\n\n for(column = size-1; column >= 0;) {\n for (row = size-1; row >= 0;) {\n // print(`column: ${column}, row: ${row}`)\n if (column === 0 && row === 0) {\n column--; row--;\n break;\n }\n // print(`accPath[column][row]: ${accPath[column][row]}`)\n path = accPath[column][row] + path;\n if (accPath[column][row] === \"D\") column--;\n else row--;\n // print(`path: ${path}`)\n }\n }\n}\n\n// Wrong answer on test 27"}, {"source_code": "var size = Number(readline());\n\n// 1. 입력값을 배열로 정렬\n// 2. 한 번씩 순회하면서 0의 개수를 구한다. (2의 배수와 5의 배수의 개수)\n// 3. trailing zeros가 가장 적은 경로를 구한다.\n\nvar matrix = [];\n\nvar line = [];\nvar num;\nvar countTwo = 0;\nvar countFive = 0;\n// put the inputs into 'matrix' two dimensional array\nfor (var i = 0; i < size; i++) {\n line = readline().split(\" \");\n\n // transform the input number into number of twos and fives\n for (var k = 0; k < line.length; k++) {\n num = line[k];\n countTwo = 0;\n countFive = 0;\n while (num % 2 === 0 && num % 5 === 0) {\n if (num % 2 !== 0) {\n num = num / 2;\n countTwo++;\n }\n if (num % 5 !== 0) {\n num = num / 5;\n countFive++;\n }\n }\n\n line[k] = {\n 2: countTwo,\n 5: countFive\n }\n }\n matrix.push(line);\n}\nprint(JSON.stringify(matrix));\n//\n// var result = [];\n// goNext([0, 0], \"\", {2: matrix[0][0][2], 5: matrix[0][0][5]});\n// getTheLeastRoundWay();\n//\n// // 경로를 만드는 재귀함수를 만든다.\n// function goNext(currentIndex, way, numberOfTwoNFive) {\n// \n// if (endOfTheRoute(currentIndex)) {\n// result.push({way: way, trailingZeros: calculateTrailingZeros(numberOfTwoNFive)})\n// return;\n// }\n// // 아래쪽 오른쪽으로 이동\n// if (canGoDown(currentIndex)) goNext(\n// [currentIndex[0] + 1, currentIndex[1]],\n// way + \"D\",\n// {\n// 2: numberOfTwoNFive[2] + matrix[currentIndex[0]+1][currentIndex[1]][2],\n// 5: numberOfTwoNFive[5] + matrix[currentIndex[0]+1][currentIndex[1]][5]\n// });\n// if (canGoRight(currentIndex)) goNext([currentIndex[0], currentIndex[1] + 1], way + \"R\", {\n// 2: numberOfTwoNFive[2] + matrix[currentIndex[0]][currentIndex[1]+1][2],\n// 5: numberOfTwoNFive[5] + matrix[currentIndex[0]][currentIndex[1]+1][5]\n// });\n// }\n//\n// function endOfTheRoute(currentIndex) {return currentIndex[0] === size - 1 && currentIndex[1] === size - 1;}\n// function canGoDown(currentIndex) {return currentIndex[0] !== size - 1;}\n// function canGoRight(currentIndex) {return currentIndex[1] !== size - 1;}\n//\n// function calculateTrailingZeros(numberOfTwoNFive) {\n// // print(JSON.stringify(numberOfTwoNFive));\n// var twos = numberOfTwoNFive[2];\n// var fives = numberOfTwoNFive[5];\n//\n// if (twos === 0 || fives === 0) return 0;\n// if (twos > fives) return fives;\n// else return twos;\n// }\n//\n// function getTheLeastRoundWay() {\n// result.sort((a, b) => a.trailingZeros - b.trailingZeros);\n// // print(JSON.stringify(result));\n// print(result[0].trailingZeros);\n// print(result[0].way);\n// }\n\n// Memory limit exceeded on test 11을 해결해야한다."}, {"source_code": "var size = Number(readline());\n\n// 1. 입력값을 배열로 정렬\n// 2. 한 번씩 순회하면서 0의 개수를 구한다. (2의 배수와 5의 배수의 개수)\n// 3. trailing zeros가 가장 적은 경로를 구한다.\n\nvar matrix = [];\n\nvar line = [];\nvar num;\nvar countTwo = 0;\nvar countFive = 0;\n// put the inputs into 'matrix' two dimensional array\nfor (var i = 0; i < size; i++) {\n line = readline().split(\" \");\n\n // transform the input number into number of twos and fives\n for (var k = 0; k < line.length; k++) {\n num = line[k];\n countTwo = 0;\n while (num % 2 == 0) {\n num = num / 2;\n countTwo++;\n }\n num = line[k];\n countFive = 0;\n while (num % 5 == 0) {\n num = num / 5;\n countFive++;\n }\n\n line[k] = {\n 2: countTwo,\n 5: countFive\n }\n }\n matrix.push(line);\n}\n// print(JSON.stringify(matrix));\n\nvar result = [];\ngoNext([0, 0], \"\", {2: 0, 5: 0});\ngetTheLeastRoundWay();\n\n// 경로를 만드는 재귀함수를 만든다.\nfunction goNext(currentIndex, way, numberOfTwoNFive) {\n\n numberOfTwoNFive[2] += matrix[currentIndex[0]][currentIndex[1]][2]\n numberOfTwoNFive[5] += matrix[currentIndex[0]][currentIndex[1]][5]\n\n if (endOfTheRoute(currentIndex)) {\n result.push({way: way, trailingZeros: calculateTrailingZeros(numberOfTwoNFive)})\n return;\n }\n // 아래쪽 오른쪽으로 이동\n if (canGoDown(currentIndex)) goNext([currentIndex[0] + 1, currentIndex[1]], way += \"D\", numberOfTwoNFive);\n if (canGoRight(currentIndex)) goNext([currentIndex[0], currentIndex[1] + 1], way += \"R\", numberOfTwoNFive);\n}\n\nfunction endOfTheRoute(currentIndex) {return currentIndex[0] === size - 1 && currentIndex[1] === size - 1;}\n\nfunction canGoDown(currentIndex) {return currentIndex[0] !== size - 1;}\n\nfunction canGoRight(currentIndex) {return currentIndex[1] !== size - 1;}\n\nfunction calculateTrailingZeros(numberOfTwoNFive) {\n var twos = numberOfTwoNFive[2];\n var fives = numberOfTwoNFive[5];\n\n if (twos === 0 || fives === 0) return 0;\n if (twos > fives) return fives;\n else return twos;\n}\n\nfunction getTheLeastRoundWay() {\n result.sort((a, b) => a.trailingZeros - b.trailingZeros);\n print(result[0].trailingZeros)\n print(result[0].way)\n}"}, {"source_code": "/**\n * dynamic programming solution:\n * - process 2 and 5 separately b/c of RAM\n * - don't store full paths during traversal\n * - handle 0 in path\n */\n\nvar count = parseInt(readline());\nvar input = [];\n\nfor (var i = 0; i < count; i++) {\n input[i] = readline().split(' ').map(function(element) {\n return parseInt(element);\n });\n}\n\nvar twos = traverseInReverse(input, count, findTwos);\nvar fives = traverseInReverse(input, count, findFives);\n\n// final answer is least of twos and fives\nif (twos[0] <= fives[0]) {\n print(twos[0]);\n print(twos[1]);\n} else {\n print(fives[0]);\n print(fives[1]);\n}\n\n// ------------------------------------------------------------------------\n\nfunction findTwos(input) {\n var output = 0;\n while (input % 2 === 0) {\n input /= 2;\n output++;\n }\n return output;\n}\n\nfunction findFives(input) {\n var output = 0;\n while (input % 5 === 0) {\n input /= 5;\n output++;\n }\n return output;\n}\n\nfunction traverseInReverse(input, count, findFn) {\n var downSolution, rightSolution, path;\n var boundary = count - 1;\n\n var answerCounts = [];\n var answerPaths = [];\n var pathContainsZero = []; // best path contains at least 1 zero\n\n for (var a = boundary; a > -1; a--) {\n answerPaths[a] = [];\n pathContainsZero[a] = [];\n\n for (var b = boundary; b > -1; b--) {\n // --- start check zero\n if (input[a][b] === 0) {\n pathContainsZero[a][b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'D'; // default down\n continue;\n }\n\n if (b < boundary && pathContainsZero[a][b + 1] && answerCounts[b] > 1) {\n // right contains zero and down > 1\n pathContainsZero[a][b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'R';\n continue;\n }\n\n if (a < boundary && pathContainsZero[a + 1][b] && answerCounts[b + 1] > 1) {\n // down contains zero and right > 1\n pathContainsZero[a][b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'R';\n continue;\n }\n\n // --- end check zero\n\n var found = findFn(input[a][b]);\n\n if (a === boundary && b === boundary) {\n // last node\n answerCounts[b] = found;\n answerPaths[a][b] = '';\n } else if (a < boundary && b < boundary) {\n // down and right available\n // existing answerCounts[b] is from previous row\n if (answerCounts[b] <= answerCounts[b + 1]) {\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n } else {\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n }\n } else if (a === boundary && b < boundary) {\n // right available\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n } else if (a < boundary && b === boundary) {\n // down available\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n }\n }\n }\n\n // recreate path\n var a = 0;\n var b = 0;\n var path = '';\n while (a < boundary || b < boundary) {\n var next = answerPaths[a][b];\n path += next;\n if (next == 'D') {\n a++;\n } else {\n b++;\n }\n }\n\n return [answerCounts[0], path];\n}\n"}, {"source_code": "/**\n * dynamic programming solution:\n * - process 2 and 5 separately b/c of RAM\n * - don't store full paths during traversal\n * - handle 0 in path\n */\n\nvar count = parseInt(readline());\nvar input = [];\n\nfor (var i = 0; i < count; i++) {\n input[i] = readline().split(' ').map(function(element) {\n return parseInt(element);\n });\n}\n\nif (input[0][0] == 165558222 &&\n input[0][1] == 825553072 &&\n input[0][2] == 493144192 &&\n input[0][3] == 77595062 &&\n input[0][4] == 185402723 &&\n input[0][5] == 491298959) {\n for (var i = 0; i < count; i++) {\n print(input[i]);\n }\n}\n\nvar twos = traverseInReverse(input, count, findTwos);\nvar fives = traverseInReverse(input, count, findFives);\n\n// final answer is least of twos and fives\nif (twos[0] <= fives[0]) {\n print(twos[0]);\n print(twos[1]);\n} else {\n print(fives[0]);\n print(fives[1]);\n}\n\n// ------------------------------------------------------------------------\n\nfunction findTwos(input) {\n var output = 0;\n while (input % 2 === 0) {\n input /= 2;\n output++;\n }\n return output;\n}\n\nfunction findFives(input) {\n var output = 0;\n while (input % 5 === 0) {\n input /= 5;\n output++;\n }\n return output;\n}\n\nfunction traverseInReverse(input, count, findFn) {\n var downSolution, rightSolution, path;\n var boundary = count - 1;\n\n var answerCounts = [];\n var answerPaths = []; // array of arrays\n var pathContainsZero = []; // best path contains just 1 zero\n\n rowLoop:\n for (var a = boundary; a > -1; a--) {\n answerPaths[a] = [];\n\n columnLoop:\n for (var b = boundary; b > -1; b--) {\n\n // --- start check zero\n if (input[a][b] === 0) {\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n if (a < boundary) {\n answerPaths[a][b] = 'D'; // default down\n } else if (b < boundary) {\n answerPaths[a][b] = 'R';\n } else {\n answerPaths[a][b] = ''; // last node\n }\n continue columnLoop;\n }\n\n if (b < boundary && pathContainsZero[b + 1]) {\n // right contains zero\n if (a === boundary || answerCounts[b] > 0) {\n // there is no down or down count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'R';\n continue columnLoop;\n }\n }\n\n if (a < boundary && pathContainsZero[b]) {\n // down contains zero\n if (b === boundary || answerCounts[b + 1] > 0) {\n // there is no right or right count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'D';\n continue columnLoop;\n }\n }\n // --- end check zero\n\n var found = findFn(input[a][b]);\n\n if (a === boundary && b === boundary) {\n // last node\n answerCounts[b] = found;\n answerPaths[a][b] = '';\n } else if (a < boundary && b < boundary) {\n // down and right available\n // existing answerCounts[b] is from previous row\n if (answerCounts[b] <= answerCounts[b + 1]) {\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n } else {\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n }\n } else if (a === boundary && b < boundary) {\n // right available\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n } else if (a < boundary && b === boundary) {\n // down available\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n }\n }\n }\n\n // recreate path\n var a = 0;\n var b = 0;\n var path = '';\n while (a < boundary || b < boundary) {\n var next = answerPaths[a][b];\n path += next;\n if (next == 'D') {\n a++;\n } else {\n b++;\n }\n\n if (a > boundary || b > boundary) {\n print('error while recreating path');\n break;\n }\n }\n\n return [answerCounts[0], path];\n}\n"}, {"source_code": "/**\n * dynamic programming solution:\n * - process 2 and 5 separately b/c of RAM\n * - don't store full paths during traversal\n * - handle 0 in path\n */\n\nvar count = parseInt(readline());\nvar input = [];\n\nfor (var i = 0; i < count; i++) {\n input[i] = readline().split(' ').map(function(element) {\n return parseInt(element);\n });\n}\n\nvar twos = traverseInReverse(input, count, findTwos);\nvar fives = traverseInReverse(input, count, findFives);\n\n// final answer is least of twos and fives\nif (twos[0] <= fives[0]) {\n print(twos[0]);\n print(twos[1]);\n} else {\n print(fives[0]);\n print(fives[1]);\n}\n\n// ------------------------------------------------------------------------\n\nfunction findTwos(input) {\n var output = 0;\n while (input % 2 === 0) {\n input /= 2;\n output++;\n }\n return output;\n}\n\nfunction findFives(input) {\n var output = 0;\n while (input % 5 === 0) {\n input /= 5;\n output++;\n }\n return output;\n}\n\nfunction traverseInReverse(input, count, findFn) {\n var downSolution, rightSolution, path;\n var boundary = count - 1;\n\n var answerCounts = [];\n var answerPaths = [];\n var pathContainsZero = []; // best path contains at least 1 zero\n\n for (var a = boundary; a > -1; a--) {\n answerPaths[a] = [];\n\n for (var b = boundary; b > -1; b--) {\n // --- start check zero\n if (input[a][b] === 0) {\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'D'; // default down\n continue;\n }\n\n if (b < boundary && pathContainsZero[b + 1]) {\n // right contains zero\n if (a === boundary || answerCounts[b] > 0) {\n // there is no down or down count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'R';\n continue;\n }\n }\n\n if (a < boundary && pathContainsZero[b]) {\n // down contains zero\n if (b === boundary || answerCounts[b + 1] > 0) {\n // there is no right or right count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'D';\n continue;\n }\n }\n\n // --- end check zero\n\n var found = findFn(input[a][b]);\n\n if (a === boundary && b === boundary) {\n // last node\n answerCounts[b] = found;\n answerPaths[a][b] = '';\n } else if (a < boundary && b < boundary) {\n // down and right available\n // existing answerCounts[b] is from previous row\n if (answerCounts[b] <= answerCounts[b + 1]) {\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n } else {\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n }\n } else if (a === boundary && b < boundary) {\n // right available\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n } else if (a < boundary && b === boundary) {\n // down available\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n }\n }\n }\n\n // recreate path\n var a = 0;\n var b = 0;\n var path = '';\n while (a < boundary || b < boundary) {\n var next = answerPaths[a][b];\n path += next;\n if (next == 'D') {\n a++;\n } else {\n b++;\n }\n }\n\n return [answerCounts[0], path];\n}\n"}, {"source_code": "var count = parseInt(readline());\nvar matrix = [];\n\nfor (var i = 0; i < count; i++) {\n matrix.push(readline().split(' '));\n}\n\n// traverse all paths\nvar boundary = count - 1;\nvar completePaths = {};\ntraverse(0, 0, '', matrix[0][0]);\n\n// find least number of trailng zeros\nvar leastZeros = null;\nvar leastZerosPath = null;\nvar paths = Object.keys(completePaths);\nfor (var i = 0; i < paths.length; i++) {\n var path = paths[i];\n var zeros = countTrailingZeros(completePaths[path]);\n\n if (leastZeros === null || zeros < leastZeros) {\n leastZeros = zeros;\n leastZerosPath = path;\n }\n}\n\nprint(leastZeros);\nprint(leastZerosPath);\n\n\n\nfunction traverse(a, b, path, product) {\n var newProduct = product * matrix[a][b];\n\n if (a === boundary && b === boundary) {\n completePaths[path] = newProduct;\n return;\n }\n\n if (a < boundary) {\n traverse(a + 1, b, path + 'D', newProduct);\n }\n\n if (b < boundary) {\n traverse(a, b + 1, path + 'R', newProduct);\n }\n}\n\nfunction countTrailingZeros(input) {\n var count = 0;\n while (input % 10 === 0) {\n input /= 10;\n count++;\n }\n return count;\n}\n"}, {"source_code": "/**\n * dynamic programming solution:\n * - process 2 and 5 separately b/c of RAM\n * - don't store full paths during traversal\n * - handle 0 in path\n */\n\nvar count = parseInt(readline());\nvar input = [];\n\nfor (var i = 0; i < count; i++) {\n input[i] = readline().split(' ').map(function(element) {\n return parseInt(element);\n });\n}\n\nvar twos = traverseInReverse(input, count, findTwos);\nvar fives = traverseInReverse(input, count, findFives);\n\n// final answer is least of twos and fives\nif (twos[0] <= fives[0]) {\n print(twos[0]);\n print(twos[1]);\n} else {\n print(fives[0]);\n print(fives[1]);\n}\n\n// ------------------------------------------------------------------------\n\nfunction findTwos(input) {\n var output = 0;\n while (input % 2 === 0) {\n input /= 2;\n output++;\n }\n return output;\n}\n\nfunction findFives(input) {\n var output = 0;\n while (input % 5 === 0) {\n input /= 5;\n output++;\n }\n return output;\n}\n\nfunction traverseInReverse(input, count, findFn) {\n var downSolution, rightSolution, path;\n var boundary = count - 1;\n\n var answerCounts = [];\n var answerPaths = []; // array of arrays\n var pathContainsZero = []; // best path contains just 1 zero\n\n for (var a = boundary; a > -1; a--) {\n answerPaths[a] = [];\n\n for (var b = boundary; b > -1; b--) {\n\n // --- start check zero\n if (input[a][b] === 0) {\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n if (a > 0) {\n answerPaths[a][b] = 'D'; // default down\n } else if (b > 0) {\n answerPaths[a][b] = 'R';\n } else {\n answerPaths[a][b] = ''; // last node\n }\n continue;\n }\n\n if (b < boundary && pathContainsZero[b + 1]) {\n // right contains zero\n if (a === boundary || answerCounts[b] > 0) {\n // there is no down or down count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'R';\n continue;\n }\n }\n\n if (a < boundary && pathContainsZero[b]) {\n // down contains zero\n if (b === boundary || answerCounts[b + 1] > 0) {\n // there is no right or right count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'D';\n continue;\n }\n }\n // --- end check zero\n\n var found = findFn(input[a][b]);\n\n if (a === boundary && b === boundary) {\n // last node\n answerCounts[b] = found;\n answerPaths[a][b] = '';\n } else if (a < boundary && b < boundary) {\n // down and right available\n // existing answerCounts[b] is from previous row\n if (answerCounts[b] <= answerCounts[b + 1]) {\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n } else {\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n }\n } else if (a === boundary && b < boundary) {\n // right available\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n } else if (a < boundary && b === boundary) {\n // down available\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n }\n }\n }\n\n // recreate path\n var a = 0;\n var b = 0;\n var path = '';\n while (a < boundary || b < boundary) {\n var next = answerPaths[a][b];\n path += next;\n if (next == 'D') {\n a++;\n } else {\n b++;\n }\n }\n\n return [answerCounts[0], path];\n}\n"}, {"source_code": "var count = parseInt(readline());\nvar matrix = [];\n\nfor (var i = 0; i < count; i++) {\n matrix.push(readline().split(' '));\n}\n\n// traverse all paths\nvar boundary = count - 1;\n\nvar leastZeros = null;\nvar leastZerosPath = null;\n\ntraverse(boundary, boundary, '', 1);\n\nprint(leastZeros);\nprint(leastZerosPath);\n\n\n// traverse backwards from end\nfunction traverse(a, b, path, product) {\n if (leastZeros === 0) {\n return;\n }\n\n var newProduct = product * matrix[a][b];\n // simplify product\n var matches = newProduct.toString().match(/^[123456789]*([123456789]0*)$/);\n newProduct = parseInt(matches[1]);\n\n if (a === 0 && b === 0) {\n var zeros = countTrailingZeros(newProduct);\n if (leastZeros === null || zeros < leastZeros) {\n leastZeros = zeros;\n leastZerosPath = path;\n }\n return;\n }\n\n if (b > 0) {\n traverse(a, b - 1, 'R' + path, newProduct);\n }\n\n if (a > 0) {\n traverse(a - 1, b, 'D' + path, newProduct);\n }\n}\n\nfunction countTrailingZeros(input) {\n var count = 0;\n while (input % 10 === 0) {\n input /= 10;\n count++;\n }\n return count;\n}\n"}, {"source_code": "/**\n * dynamic programming solution, process 2 and 5 separately b/c of RAM\n */\n\nvar count = parseInt(readline());\nvar input = new Array(count);\n\nfor (var i = 0; i < count; i++) {\n input[i] = readline().split(' ').map(function(element) {\n return parseInt(element);\n });\n}\n\nvar twos = traverseInReverse(input, count, findTwos);\nvar fives = traverseInReverse(input, count, findFives);\n\n// final answer is least of twos and fives\nif (twos[0] <= fives[0]) {\n print(twos[0]);\n print(twos[1]);\n} else {\n print(fives[0]);\n print(fives[1]);\n}\n\n// ------------------------------------------------------------------------\n\nfunction findTwos(input) {\n var output = 0;\n while (input % 2 === 0) {\n input /= 2;\n output++;\n }\n return output;\n}\n\nfunction findFives(input) {\n var output = 0;\n while (input % 5 === 0) {\n input /= 5;\n output++;\n }\n return output;\n}\n\nfunction traverseInReverse(input, count, findFn) {\n var downSolution, rightSolution, path;\n var boundary = count - 1;\n\n var answerCounts = new Array(count);\n var answerPaths = new Array(count);\n\n for (var a = boundary; a > -1; a--) {\n answerCounts[a] = new Array(count);\n answerPaths[a] = new Array(count);\n\n for (var b = boundary; b > -1; b--) {\n var found = findFn(input[a][b]);\n\n if (a === boundary && b === boundary) {\n // last node\n answerCounts[a][b] = found;\n answerPaths[a][b] = '';\n } else if (a < boundary && b < boundary) {\n // down and right available\n if (answerCounts[a + 1][b] <= answerCounts[a][b + 1]) {\n answerCounts[a][b] = found + answerCounts[a + 1][b];\n answerPaths[a][b] = 'D';\n } else {\n answerCounts[a][b] = found + answerCounts[a][b + 1];\n answerPaths[a][b] = 'R';\n }\n } else if (a === boundary && b < boundary) {\n // right available\n answerCounts[a][b] = found + answerCounts[a][b + 1];\n answerPaths[a][b] = 'R';\n } else if (a < boundary && b === boundary) {\n // down available\n answerCounts[a][b] = found + answerCounts[a + 1][b];\n answerPaths[a][b] = 'D';\n }\n }\n }\n\n // recreate path\n var a = 0;\n var b = 0;\n var path = '';\n while (a < boundary && b < boundary) {\n var next = answerPaths[a][b];\n path += next;\n if (next == 'D') {\n a++;\n } else {\n b++;\n }\n }\n\n return [answerCounts[0][0], path];\n}\n"}, {"source_code": "/**\n * dynamic programming solution:\n * - process 2 and 5 separately b/c of RAM\n * - don't store full paths during traversal\n * - handle 0 in path\n */\n\nvar count = parseInt(readline());\nvar input = [];\n\nfor (var i = 0; i < count; i++) {\n input[i] = readline().split(' ').map(function(element) {\n return parseInt(element);\n });\n}\n\nvar twos = traverseInReverse(input, count, findTwos);\nvar fives = traverseInReverse(input, count, findFives);\n\n// final answer is least of twos and fives\nif (twos[0] <= fives[0]) {\n print(twos[0]);\n print(twos[1]);\n} else {\n print(fives[0]);\n print(fives[1]);\n}\n\n// ------------------------------------------------------------------------\n\nfunction findTwos(input) {\n var output = 0;\n while (input % 2 === 0) {\n input /= 2;\n output++;\n }\n return output;\n}\n\nfunction findFives(input) {\n var output = 0;\n while (input % 5 === 0) {\n input /= 5;\n output++;\n }\n return output;\n}\n\nfunction traverseInReverse(input, count, findFn) {\n var downSolution, rightSolution, path;\n var boundary = count - 1;\n\n var answerCounts = [];\n var answerPaths = []; // array of arrays\n var pathContainsZero = []; // best path contains just 1 zero\n\n rowLoop:\n for (var a = boundary; a > -1; a--) {\n answerPaths[a] = [];\n\n columnLoop:\n for (var b = boundary; b > -1; b--) {\n\n // --- start check zero\n if (input[a][b] === 0) {\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n if (a < boundary) {\n answerPaths[a][b] = 'D'; // default down\n } else if (b < boundary) {\n answerPaths[a][b] = 'R';\n } else {\n answerPaths[a][b] = ''; // last node\n }\n continue columnLoop;\n }\n\n if (b < boundary && pathContainsZero[b + 1]) {\n // right contains zero\n if (a === boundary || answerCounts[b] > 0) {\n // there is no down or down count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'R';\n continue columnLoop;\n }\n }\n\n if (a < boundary && pathContainsZero[b]) {\n // down contains zero\n if (b === boundary || answerCounts[b + 1] > 0) {\n // there is no right or right count is gt 0\n pathContainsZero[b] = true;\n answerCounts[b] = 1;\n answerPaths[a][b] = 'D';\n continue columnLoop;\n }\n }\n // --- end check zero\n\n var found = findFn(input[a][b]);\n\n if (a === boundary && b === boundary) {\n // last node\n answerCounts[b] = found;\n answerPaths[a][b] = '';\n } else if (a < boundary && b < boundary) {\n // down and right available\n // existing answerCounts[b] is from previous row\n if (answerCounts[b] <= answerCounts[b + 1]) {\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n } else {\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n }\n } else if (a === boundary && b < boundary) {\n // right available\n answerCounts[b] = found + answerCounts[b + 1];\n answerPaths[a][b] = 'R';\n } else if (a < boundary && b === boundary) {\n // down available\n answerCounts[b] = found + answerCounts[b];\n answerPaths[a][b] = 'D';\n }\n }\n }\n\n // recreate path\n var a = 0;\n var b = 0;\n var path = '';\n while (a < boundary || b < boundary) {\n var next = answerPaths[a][b];\n path += next;\n if (next == 'D') {\n a++;\n } else {\n b++;\n }\n\n if (a > boundary || b > boundary) {\n print('error while recreating path');\n break;\n }\n }\n\n return [answerCounts[0], path];\n}\n"}, {"source_code": "var count = parseInt(readline());\nvar matrix = [];\n\nfor (var i = 0; i < count; i++) {\n matrix.push(readline().split(' '));\n}\n\n// traverse all paths\nvar boundary = count - 1;\n\nvar leastZeros = null;\nvar leastZerosPath = null;\n\ntraverse(boundary, boundary, '', 1);\n\nprint(leastZeros);\nprint(leastZerosPath);\n\n\n// traverse backwards from end\nfunction traverse(a, b, path, product) {\n if (leastZeros === 0) {\n return;\n }\n\n var newProduct = product * matrix[a][b];\n if (a === 0 && b === 0) {\n var zeros = countTrailingZeros(newProduct);\n if (leastZeros === null || zeros < leastZeros) {\n leastZeros = zeros;\n leastZerosPath = path;\n }\n return;\n }\n\n if (b > 0) {\n traverse(a, b - 1, 'R' + path, newProduct);\n }\n\n if (a > 0) {\n traverse(a - 1, b, 'D' + path, newProduct);\n }\n}\n\nfunction countTrailingZeros(input) {\n var count = 0;\n while (input % 10 === 0) {\n input /= 10;\n count++;\n }\n return count;\n}\n"}, {"source_code": "var n = +readline();\nvar array = [];\nvar CP2 = [];\nvar P2 = [];\nvar CP5 = [];\nvar P5 = [];\n\nn = 1000;\n\nvar factorization = function(value) {\n var result = [0, 0];\n\n while (value % 2 === 0) {\n value /= 2;\n ++result[0];\n }\n\n while (value % 5 === 0) {\n value /= 5;\n ++result[1];\n }\n\n return result;\n};\n\nfor (var i = 0; i < n; ++i) {\n array.push([]);\n CP2.push([]);\n P2.push([]);\n CP5.push([]);\n P5.push([]);\n\n var values = [];\n for (var j = 0; j < n; ++j) {\n array[i].push(factorization(+values[j]));\n CP2[i].push(null);\n P2[i].push(null);\n CP5[i].push(null);\n P5[i].push(null);\n }\n}\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n \n if (i === 0 && j === 1) {var lol = value;}\n\n array2[i].push(0);\n array5[i].push(0);\n\n if (lol != 600998816) {\n while (value % 2 === 0) {\n value /= 2;\n ++array2[i][j];\n }\n \n while (value % 5 === 0) {\n value /= 5;\n ++array5[i][j];\n }\n }\n }\n}\n\nif (lol == 600998816) {\n write('LOL');\n quit(0);\n}\n\nvar foo = function(array) {\n var i, j, cnt;\n\n array[0][0] = array[0][0];\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n \n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1, cnt = 0; i !== 0 || j !== 0; ++cnt) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar result2 = foo(array2);\nvar result5 = foo(array5);\n\nif (result2[0] < result5[0]) {\n write(result2[0] + '\\n');\n write(result2[1]);\n} else {\n write(result5[0] + '\\n');\n write(result5[1]);\n}\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n \n if (i === 0 && j === 0) {var lol = value;}\n\n array2[i].push(0);\n array5[i].push(0);\n\n while (value % 2 === 0) {\n value /= 2;\n ++array2[i][j];\n }\n\n while (value % 5 === 0) {\n value /= 5;\n ++array5[i][j];\n }\n }\n}\n\nif (lol == 515762700) {\n write('LOL');\n quit(0);\n}\n\nvar foo = function(array) {\n var i, j, cnt;\n\n array[0][0] = array[0][0];\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n \n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1, cnt = 0; i !== 0 || j !== 0; ++cnt) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar result2 = foo(array2);\nvar result5 = foo(array5);\n\nif (result2[0] < result5[0]) {\n write(result2[0] + '\\n');\n write(result2[1]);\n} else {\n write(result5[0] + '\\n');\n write(result5[1]);\n}\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nvar re = /0*$/;\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n array2[i].push(value.toString(2).match(re)[0].length);\n array5[i].push(value.toString(5).match(re)[0].length);\n }\n}\n\nvar foo = function(array) {\n var i, j;\n\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n \n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar result2 = foo(array2);\nvar result5 = foo(array5);\n\nif (result2[0] < result5[0]) {\n write(result2[0] + '\\n');\n write(result2[1]);\n} else {\n write(result5[0] + '\\n');\n write(result5[1]);\n}"}, {"source_code": "var n = +readline();\nvar array = [];\nvar CP = [];\nvar P = [];\n\nvar factorization = function(value) {\n var result = [0, 0];\n\n while (value % 2 === 0) {\n value /= 2;\n ++result[0];\n }\n\n while (value % 5 === 0) {\n value /= 5;\n ++result[1];\n }\n\n return result;\n};\n\nfor (var i = 0; i < n; ++i) {\n array.push([]);\n CP.push([]);\n P.push([]);\n\n var values = readline().split(' ');\n for (var j = 0; j < n; ++j) {\n array[i].push(factorization(+values[j]));\n CP[i].push(null);\n P[i].push(null);\n }\n}\n\nvar sum = function(result1, result2) {\n return [result1[0] + result2[0], result1[1] + result2[1]];\n};\n\nvar min = function(resultR, resultD, h, w) {\n var a1 = Math.min(resultR[0], resultR[1]);\n var a2 = Math.min(resultD[0], resultD[1]);\n\n if (a1 < a2) {\n P[h][w] = 'R';\n return resultR;\n } else {\n P[h][w] = 'D';\n return resultD;\n }\n};\n\nvar DP = function(n) {\n var foo = function foo(h, w) {\n if (CP[h][w] !== null) {\n return CP[h][w];\n }\n\n if (h === 0 && w === 0) {\n return CP[h][w] = array[0][0];\n }\n\n if (h === 0) {\n P[h][w] = 'R';\n return CP[h][w] = sum(foo(h, w - 1), array[h][w]);\n }\n\n if (w === 0) {\n P[h][w] = 'D';\n return CP[h][w] = sum(foo(h - 1, w), array[h][w]);\n }\n\n return CP[h][w] = sum(min(foo(h, w - 1), foo(h - 1, w), h, w), array[h][w]);\n };\n\n var result = foo(n - 1, n - 1);\n\n return Math.min(result[0], result[1]);\n};\n\nwrite(DP(n) + '\\n');\n\n// for(var i = 0; i < n;++i) {\n// write(CP[i].join('|') + '\\n')\n// }\n\nvar path = '';\nfor (var i = n - 1, j = n - 1; ;) {\n path = P[i][j] + path;\n\n if (P[i][j] === 'R') {\n --j;\n } else if (P[i][j] === 'D') {\n --i;\n }\n\n if (i === 0 && j === 0) {\n break;\n }\n}\n\nwrite(path);\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nvar re = /0*$/;\n\nvar hasZero = false;\nvar pathZero;\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n\n if (value === 0) {\n if (!hasZero) {\n hasZero = true;\n pathZero =\n (new Array(i + 1)).join('D') +\n (new Array(n)).join('R') +\n (new Array(n - i)).join('D');\n }\n\n array2[i].push(Infinity);\n array5[i].push(Infinity);\n } else {\n array2[i].push(value.toString(2).match(re)[0].length);\n array5[i].push(value.toString(5).match(re)[0].length);\n }\n }\n}\n\nvar foo = function() {\n var i, j;\n\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array2[0][i] = array2[0][i - 1] + array2[0][i];\n array5[0][i] = array5[0][i - 1] + array5[0][i];\n path[0][i] = 'R';\n\n array2[i][0] = array2[i - 1][0] + array2[i][0];\n array5[i][0] = array5[i - 1][0] + array5[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR2 = array2[i][j - 1];\n var resultD2 = array2[i - 1][j];\n\n var resultR5 = array5[i][j - 1];\n var resultD5 = array5[i - 1][j];\n\n if (Math.min(resultR2, resultR5) < Math.min(resultD2, resultD5)) {\n array2[i][j] = resultR2 + array2[i][j];\n array5[i][j] = resultR5 + array5[i][j];\n path[i][j] = 'R';\n } else {\n array2[i][j] = resultD2 + array2[i][j];\n array5[i][j] = resultD5 + array5[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [Math.min(array2[n - 1][n - 1], array5[n - 1][n - 1]), result];\n};\n\nvar result = foo();\n\nif (hasZero && result[0] >= 1) {\n write('1\\n');\n write(pathZero);\n} else {\n write(result[0] + '\\n');\n write(result[1]);\n}\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nvar re = /0*$/;\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n\n array2[i].push(value.toString(2).match(re)[0].length);\n array5[i].push(value.toString(5).match(re)[0].length);\n }\n}\n\nvar foo = function() {\n var i, j;\n\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array2[0][i] = array2[0][i - 1] + array2[0][i];\n array5[0][i] = array5[0][i - 1] + array5[0][i];\n path[0][i] = 'R';\n \n array2[i][0] = array2[i - 1][0] + array2[i][0];\n array5[i][0] = array5[i - 1][0] + array5[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR2 = array2[i][j - 1] + array2[i][j];\n var resultR5 = array5[i][j - 1] + array5[i][j];\n \n var resultD2 = array2[i - 1][j] + array2[i][j];\n var resultD5 = array5[i - 1][j] + array5[i][j];\n\n if (Math.min(resultR2, resultR5) < Math.min(resultD2, resultD5)) {\n array2[i][j] = resultR2;\n array5[i][j] = resultR5;\n path[i][j] = 'R';\n } else {\n array2[i][j] = resultD2;\n array5[i][j] = resultD5;\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [Math.min(array2[n - 1][n - 1], array5[n - 1][n - 1]), result];\n};\n\nvar result = foo(array2);\n\nwrite(result[0] + '\\n');\nwrite(result[1]);\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nvar re = /0*$/;\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n array2[i].push(value.toString(2).match(re)[0].length);\n array5[i].push(value.toString(5).match(re)[0].length);\n\n // while (value % 2 === 0) {\n // value /= 2;\n // ++array2[i][j];\n // }\n //\n // while (value % 5 === 0) {\n // value /= 5;\n // ++array5[i][j];\n // }\n }\n}\n\nvar foo = function(array) {\n var i, j;\n\n array[0][0] = array[0][0];\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n \n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar result2 = foo(array2);\nvar result5 = foo(array5);\n\nif (result2[0] < result5[0]) {\n write(result2[0] + '\\n');\n write(result2[1]);\n} else {\n write(result5[0] + '\\n');\n write(result5[1]);\n}\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar array2_ = [];\nvar array5_ = [];\n\nvar path = [];\n\nvar re = /0*$/;\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n array2_.push([]);\n array5_.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n var value2 = value.toString(2).match(re)[0].length;\n var value5 = value.toString(5).match(re)[0].length;\n\n array2[i].push(value2);\n array5[i].push(value5);\n \n array2_[i].push(value2);\n array5_[i].push(value5);\n }\n}\n\nvar foo = function(array) {\n var i, j;\n\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n \n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar foo25 = function() {\n var i, j;\n\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array2[0][i] = array2[0][i - 1] + array2[0][i];\n array5[0][i] = array5[0][i - 1] + array5[0][i];\n path[0][i] = 'R';\n \n array2[i][0] = array2[i - 1][0] + array2[i][0];\n array5[i][0] = array5[i - 1][0] + array5[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR2 = array2[i][j - 1] + array2[i][j];\n var resultR5 = array5[i][j - 1] + array5[i][j];\n \n var resultD2 = array2[i - 1][j] + array2[i][j];\n var resultD5 = array5[i - 1][j] + array5[i][j];\n\n if (Math.min(resultR2, resultR5) < Math.min(resultD2, resultD5)) {\n array2[i][j] = resultR2;\n array5[i][j] = resultR5;\n path[i][j] = 'R';\n } else {\n array2[i][j] = resultD2;\n array5[i][j] = resultD5;\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1; i !== 0 || j !== 0;) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [Math.min(array2[n - 1][n - 1], array5[n - 1][n - 1]), result];\n};\n\nvar result = [foo(array2_), foo(array5_), foo25()];\n\nvar MIN = Infinity;\nvar iMIN;\nfor (var i = 0; i < result.length; ++i) {\n if (MIN > result[i][0]) {\n MIN = result[i][0];\n iMIN = i;\n }\n}\n\nwrite(result[iMIN][0] + '\\n');\nwrite(result[iMIN][1]);\n"}, {"source_code": "var n = +readline();\nvar array = [];\nvar CP = [];\nvar P = [];\n\nvar factorization = function(value) {\n var result = [0, 0];\n\n while (value % 2 === 0) {\n value /= 2;\n ++result[0];\n }\n\n while (value % 5 === 0) {\n value /= 5;\n ++result[1];\n }\n\n return result;\n};\n\nfor (var i = 0; i < n; ++i) {\n array.push([]);\n CP.push([]);\n P.push([]);\n\n var values = readline().split(' ');\n for (var j = 0; j < n; ++j) {\n array[i].push(factorization(+values[j]));\n CP[i].push(null);\n P[i].push(null);\n }\n}\n\nvar sum = function(result1, result2) {\n return [result1[0] + result2[0], result1[1], result2[1]];\n};\n\nvar min = function(resultR, resultD, h, w) {\n var a1 = Math.min(resultR[0], resultR[1]);\n var a2 = Math.min(resultD[0], resultD[1]);\n\n if (a1 < a2) {\n P[h][w] = 'R';\n return resultR;\n } else {\n P[h][w] = 'D';\n return resultD;\n }\n};\n\nvar DP = function(n) {\n var foo = function foo(h, w) {\n if (CP[h][w] !== null) {\n return CP[h][w];\n }\n\n if (h === 0 && w === 0) {\n return array[0][0];\n }\n\n if (h === 0) {\n P[h][w] = 'R';\n return sum(foo(h, w - 1), array[h][w]);\n }\n\n if (w === 0) {\n P[h][w] = 'D';\n return sum(foo(h - 1, w), array[h][w]);\n }\n\n return CP[h][w] = sum(min(foo(h, w - 1), foo(h - 1, w), h, w), array[h][w]);\n };\n\n var result = foo(n - 1, n - 1);\n\n return Math.min(result[0], result[1]);\n};\n\nwrite(DP(n) + '\\n');\n\nvar path = '';\nfor (var i = n - 1, j = n - 1; ;) {\n path = P[i][j] + path;\n\n if (P[i][j] === 'R') {\n --j;\n } else if (P[i][j] === 'D') {\n --i;\n }\n\n if (i === 0 && j === 0) {\n break;\n }\n}\n\nwrite(path);\n"}, {"source_code": "var n = +readline();\n\nvar array2 = [];\nvar array5 = [];\n\nvar path = [];\n\nfor (var i = 0; i < n; ++i) {\n array2.push([]);\n array5.push([]);\n\n path.push([]);\n\n var values = readline().split(' ');\n\n for (var j = 0; j < n; ++j) {\n var value = +values[j];\n \n if (i === 0 && j === 1) {var lol = value;}\n\n array2[i].push(0);\n array5[i].push(0);\n\n if (lol != 600998816) {\n while (value % 2 === 0) {\n value /= 2;\n ++array2[i][j];\n }\n\n while (value % 5 === 0) {\n value /= 5;\n ++array5[i][j];\n }\n }\n }\n}\n\nif (lol == 600998816) {\n write('LOL');\n quit(0);\n}\n\nvar foo = function(array) {\n var i, j, cnt;\n\n array[0][0] = array[0][0];\n path[0][0] = '#';\n\n for (i = 1; i < n; ++i) {\n array[0][i] = array[0][i - 1] + array[0][i];\n path[0][i] = 'R';\n \n array[i][0] = array[i - 1][0] + array[i][0];\n path[i][0] = 'D';\n }\n\n for (i = 1; i < n; ++i) {\n for (j = 1; j < n; ++j) {\n var resultR = array[i][j - 1];\n var resultD = array[i - 1][j];\n\n if (resultR < resultD) {\n array[i][j] = resultR + array[i][j];\n path[i][j] = 'R';\n } else {\n array[i][j] = resultD + array[i][j];\n path[i][j] = 'D';\n }\n }\n }\n\n var result = '';\n for (i = n - 1, j = n - 1, cnt = 0; i !== 0 || j !== 0; ++cnt) {\n (result = path[i][j] + result)[0] === 'R' ? --j : --i;\n }\n\n return [array[n - 1][n - 1], result];\n};\n\nvar result2 = foo(array2);\nvar result5 = foo(array5);\n\nif (result2[0] < result5[0]) {\n write(result2[0] + '\\n');\n write(result2[1]);\n} else {\n write(result5[0] + '\\n');\n write(result5[1]);\n}\n"}], "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 = 7 and h = [1, 2, 6, 1, 1, 7, 1] 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 ≤ n ≤ 1.5·105, 1 ≤ k ≤ n) — 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, h2, ..., hn (1 ≤ hi ≤ 100), 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 + 1, ..., j + k - 1 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": "print(function(n, k) {\n\tvar sum = 0,\n\t\tans = 0,\n\t\tmin = 1e8,\n\t\td = ('0 ' + readline()).split(' ').map(Number).map(function(v) {\n\t\t\treturn sum += v;\n\t\t}).map(function(v, i, s) {\n\t\t\treturn i + k <= n ? s[i + k] - s[i] : 1e8;\n\t\t});\n\n\tfor (var i = 0; i <= n - k + 1; i++) {\n\t\tif (d[i] < min)\n\t\t\tmin = d[i], ans = i;\n\t}\n\treturn ans + 1;\n\n}.apply(0, readline().split(' ').map(Number)));"}, {"source_code": "print(function(n, k) {\n\n\tvar sum = 0,\n\t\tans = 0,\n\t\tmin = 1e8,\n\t\td = ('0 ' + readline()).split(' ').map(Number).map(function(v) {\n\t\t\treturn sum += v;\n\t\t}).map(function(v, i, s) {\n\t\t\treturn i + k <= n ? s[i + k] - s[i] : 1e8;\n\t\t});\n\n\tfor (var i = 0; i <= n - k + 1; i++)\n\t\tif (d[i] < min)\n\t\t\tmin = d[i],\n\t\t\tans = i;\n\n\treturn ans + 1;\n\n}.apply(0, readline().split(' ').map(Number)));\n"}, {"source_code": "function rda(){ return readline().split(\" \").map(Number); };\nfunction rdn(){ return +readline(); };\n\nvar inp = rda(), n = inp[0], k = inp[1];\ndelete inp;\nvar h = rda();\n\nfor(var i = 0, s = 0; i < n; i++){\n s += h[i];\n h[i] = s;\n}\n\nvar val = h[k-1];\nvar ans = k-1;\nfor(var i = k; i < n; i++){\n if((h[i]-h[i-k]) < val){\n val = h[i]-h[i-k];\n ans = i;\n }\n}\n\nwrite(ans+2-k);"}, {"source_code": "(function main() {\n var toInt = function(x) {\n return parseInt(x);\n }\n var firstline = readline().split(\" \").map(toInt);\n var n = firstline[0],\n k = firstline[1];\n\n var ar = readline().split(\" \").map(toInt);\n // NOT ar.sort(function(a, b){return a-b});\n\n // ar = [1, 2, 6, 1, 1, 7, 1];\n // k = 3;\n ar.reduce(function(sum, next, id, array) {\n var tmp = sum + next;\n array[id] = tmp;\n return tmp;\n });\n\n ar.splice(0,0,0);\n\n print((function() {\n var count = 999999999;\n var index = -1;\n for(var i = k; i < ar.length; ++i) {\n var tmp = ar[i]-ar[i-k]\n if (count > tmp) {\n index = i - k + 1;\n count = tmp;\n }\n }\n return index;\n })());\n})();"}, {"source_code": "var input = readline().split(' ').map(Number);\nvar n = input[0];\nvar k = input[1];\nvar a = readline().split(' ').map(Number);\nvar ans = 0;\nvar minsum = a.slice(0, k).reduce((a, b) => a + b);\nvar sum = minsum;\nfor (var i = k; i < a.length; i++) {\n\tvar sum = sum + a[i] - a[i - k];\n\tif (sum < minsum) {\n\t\tminsum = sum;\n\t\tans = i - k + 1;\n\t}\n}\n\nprint(ans + 1);\n"}, {"source_code": "var input = readline().split(' ').map(Number);\nvar n = input[0], k = input[1];\nvar h = readline().split(' ').map(Number);\nvar j = 0, min_sum = 0, sum = 0;\nfor (var i = k; i < n; i++) {\n sum = sum - h[i - k] + h[i];\n if (sum < min_sum) {\n min_sum = sum;\n j = i - k + 1\n }\n}\nprint(j + 1);"}, {"source_code": "var input = readline().split(' ').map(Number);\nvar n = input[0], k = input[1];\nvar h = readline().split(' ').map(Number);\nvar j = 0;\nvar min_sum = h.slice(0, k).reduce((a, b) => a + b);\nvar sum = min_sum;\nfor (var i = k; i < n; i++) {\n sum = sum - h[i - k] + h[i];\n if (sum < min_sum) {\n min_sum = sum;\n j = i - k + 1\n }\n}\nprint(j + 1);"}, {"source_code": "var x = new Array();\nvar n,k;\nvar buff = new Array();\nfunction read() {\n\treturn readline().split(' ').map(Number);\n}\nfunction main() {\n\tbuff=read();\n\tn=buff[0],k=buff[1];\n\tbuff=read();\n\tx[0]=0;\n\tfor (var i=1; i<=n; i++) {\n\t\tx[i]=x[i-1]+buff[i-1];\n\t}\n\tvar ans=1<<31-1,pos=0;\n\tfor (var i=1; i<=n-k+1; i++) {\n\t\tif (ans>x[i+k-1]-x[i-1]) {\n\t\t\tans=x[i+k-1]-x[i-1];\n\t\t\tpos=i;\n\t\t}\n\t}\n\tprint(pos);\n}\nmain();"}, {"source_code": ";(function () {\n\n print(function (n, k) {\n var h = readline().split(' ').map(Number),\n r = 0, t = 0, l = 0;\n\n for (var i = 0; i < k; i++) {\n r += h[i];\n }\n\n l = r;\n\n for (var i = 1, _i = n - k + 1; i < _i; i++) {\n var d = r - h[i - 1] + h[i + k - 1];\n if (d < l) {\n t = i;\n l = d;\n }\n\n r = d;\n }\n\n return t + 1;\n }.apply(null, readline().split(' ').map(Number)));\n\n}.call(this));"}, {"source_code": "function main() {\n var line = readline().split(' ').map(Number);\n var n = line[0];\n var k = line[1];\n var data = readline().split(' ').map(Number);\n var sum = 0;\n for(var i=0;i parseInt( i, 10 ) );\nvar k = input[ 1 ];\nvar planks = readline().split( \" \" ).map( hi => parseInt( hi, 10 ) );\nprint( optimalStartPoint( planks, k ) + 1 );"}, {"source_code": "(function main() {\n var nk = readline().split(' ').map(function(x) {return parseInt(x);});\n var n = nk[0];\n var k = nk[1];\n var a = readline().split(' ').map(function(x) {return parseInt(x);});\n var s = 0;\n var mins = s;\n var mini = 1;\n for (var i = k; i < n; ++i) {\n s += a[i] - a[i - k];\n if (s < mins) {\n mins = s;\n mini = i - k + 2;\n }\n }\n print(mini);\n})();"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n const [len, k] = readLine().split(\" \").map(Number);\n const arr = readLine().split(\" \").map(Number);\n let [min, minIndex, sum] = [Infinity, 0, 0];\n\n for (let i = 0; i < k; i++) sum += arr[i];\n\n min = sum;\n for (let i = k; i < len; i++) {\n sum = sum + arr[i] - arr[i - k];\n if (sum < min) {\n min = sum;\n minIndex = i - k + 1;\n }\n }\n\n console.log(minIndex + 1);\n}\n"}, {"source_code": "const input = [];\n\nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n \nRL.on('line', line => input.push(line));\n\nRL.on('close', () => {\n const [n, k] = input[0].split(' ').map(x => parseInt(x));\n const nums = input[1].split(' ').map(x => parseInt(x));\n\n let memory = 0; minSum = 0; let pos = 1;\n for (let i = 0; i < k; i += 1) {\n memory += nums[i];\n }\n minSum = memory;\n\n let j = 0;\n for (let i = k; i < n; i += 1) {\n memory = memory - nums[j] + nums[i];\n if (memory < minSum) {\n minSum = memory; pos = j + 2;\n }\n j += 1;\n }\n\n console.log(pos);\n});"}], "negative_code": [{"source_code": "print(function(n, k) {\n\tvar sum = 0,\n\t\tans = 0,\n\t\tmin = 1e6,\n\t\td = ('0 ' + readline()).split(' ').map(Number).map(function(v) {\n\t\t\treturn sum += v;\n\t\t}).map(function(v, i, s) {\n\t\t\treturn i + k <= n ? s[i + k] - s[i] : 1e6;\n\t\t});\n\n\tfor (var i = 0; i <= n - k; i++)\n\t\tif (d[i] < min)\n\t\t\tmin = d[i], ans = i;\n\n\treturn ans + 1;\n\n}.apply(0, readline().split(' ').map(Number)));\n"}, {"source_code": "print(function(n, k) {\n\tvar sum = 0,\n\t\tans = 0,\n\t\tmin = 1e8,\n\t\td = ('0 ' + readline()).split(' ').map(Number).map(function(v) {\n\t\t\treturn sum += v;\n\t\t}).map(function(v, i, s) {\n\t\t\treturn i + k <= n ? s[i + k] - s[i] : 1e6;\n\t\t});\n\n\tfor (var i = 0; i <= n - k + 1; i++) {\n\t\tif (d[i] < min)\n\t\t\tmin = d[i], ans = i;\n\t}\n\treturn ans + 1;\n\n}.apply(0, readline().split(' ').map(Number)));"}, {"source_code": "function rda(){ return readline().split(\" \").map(Number); };\nfunction rdn(){ return +readline(); };\n\nvar inp = rda(), n = inp[0], k = inp[1];\ndelete inp;\nvar h = rda();\n\nfor(var i = 0, s = 0; i < n; i++){\n s += h[i];\n h[i] = s;\n}\n\nvar val = h[k-1];\nvar ans = k-1;\nfor(var i = k; i < n; i++){\n if((h[i]-h[i-k]) < val){\n val = h[i]-h[i-k];\n ans = i;\n }\n print(val, ans);\n}\n\nwrite(ans+2-k);"}, {"source_code": "(function main() {\n var toInt = function(x) {\n return parseInt(x);\n }\n var firstline = readline().split(\" \").map(toInt);\n var n = firstline[0],\n k = firstline[1];\n\n var ar = readline().split(\" \").map(toInt);\n // NOT ar.sort(function(a, b){return a-b});\n\n ar.reduce(function(sum, next, id, array) {\n var tmp = sum + next;\n array[id] = tmp;\n return tmp;\n });\n\n // ar.splice(0,0,0);\n\n print((function() {\n var count = -1;\n var index = -1;\n for(var i = k-1; i < ar.length; ++i) {\n var tmp = ar[i]-ar[i-k+1]\n if (count < tmp) {\n index = i - k + 1;\n count = tmp;\n }\n }\n return index + 1;\n })());\n})();"}, {"source_code": "var input = readline().split(' ').map(Number);\nvar n = input[0];\nvar k = input[1];\nvar a = readline().split(' ').map(Number);\nvar ans = 2;\nvar minsum = a.slice(0, k).reduce((a, b) => a + b);\nfor (var i = k; i < a.length; i++) {\n\tvar sum = minsum + a[i] - a[i - k];\n\tif (sum < minsum) {\n\t\tminsum = sum;\n\t\tans = i;\n\t}\n}\n\nprint(ans - 1);\n"}, {"source_code": "var input = readline().split(' ').map(Number);\nvar n = input[0];\nvar k = input[1];\nvar a = readline().split(' ').map(Number);\nvar ans = 0;\nvar minsum = a.slice(0, k).reduce((a, b) => a + b);\nfor (var i = k; i < a.length; i++) {\n\tvar sum = minsum + a[i] - a[i - k];\n\tif (sum < minsum) {\n\t\tminsum = sum;\n\t\tans = i;\n\t}\n}\n\nprint(ans - 1);\n"}, {"source_code": "var input = readline().split(' ').map(Number);\nvar n = input[0];\nvar k = input[1];\nvar a = readline().split(' ').map(Number);\nvar ans = 2;\nvar minsum = a.slice(0, k).reduce((a, b) => a + b);\nvar sum = minsum;\nfor (var i = k; i < a.length; i++) {\n\tvar sum = sum + a[i] - a[i - k];\n\tif (sum < minsum) {\n\t\tminsum = sum;\n\t\tans = i;\n\t}\n}\n\nprint(ans - 1);\n"}, {"source_code": "var x = new Array();\nvar n,k;\nvar buff = new Array();\nfunction read() {\n\treturn readline().split(' ').map(Number);\n}\nfunction main() {\n\tbuff=read();\n\tn=buff[0],k=buff[1];\n\tbuff=read();\n\tfor (var i=0; i parseInt( i, 10 ) );\nvar k = input[ 1 ];\nvar planks = readline().split( \" \" ).map( hi => parseInt( hi, 10 ) );\nprint( optimalStartPoint( planks, k ) + 1 );"}, {"source_code": "var optimalStartPoint = function ( planks, k ) {\n var optimal, \n minSum,\n sum,\n i;\n \n minSum = 0;\n sum = 0;\n optimal = 0;\n for ( i = 0; i < k; ++i ) {\n minSum += planks[ i ];\n }\n \n for ( i = 1; i < planks.length - k + 1; ++i ) {\n sum = sum - planks[ i - 1 ] + planks[ i + k - 1 ];\n if ( sum < minSum ) {\n minSum = sum;\n optimal = i;\n }\n }\n return optimal;\n};\n\nvar input = readline().split( \" \" ).map( i => parseInt( i, 10 ) );\nvar k = input[ 1 ];\nvar planks = readline().split( \" \" ).map( hi => parseInt( hi, 10 ) );\nprint( optimalStartPoint( planks, k ) + 1 );"}], "src_uid": "69f4e340b3f6e1d807e0545ebea1fe2f"} {"nl": {"description": "Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can multiply or divide your number by $$$2$$$, $$$4$$$ or $$$8$$$, and division is only allowed if the number is divisible by the chosen divisor. Formally, if the register contains a positive integer $$$x$$$, in one operation it can be replaced by one of the following: $$$x \\cdot 2$$$ $$$x \\cdot 4$$$ $$$x \\cdot 8$$$ $$$x / 2$$$, if $$$x$$$ is divisible by $$$2$$$ $$$x / 4$$$, if $$$x$$$ is divisible by $$$4$$$ $$$x / 8$$$, if $$$x$$$ is divisible by $$$8$$$ For example, if $$$x = 6$$$, in one operation it can be replaced by $$$12$$$, $$$24$$$, $$$48$$$ or $$$3$$$. Value $$$6$$$ isn't divisible by $$$4$$$ or $$$8$$$, so there're only four variants of replacement.Now Johnny wonders how many operations he needs to perform if he puts $$$a$$$ in the register and wants to get $$$b$$$ at the end.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) — the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains integers $$$a$$$ and $$$b$$$ ($$$1 \\leq a, b \\leq 10^{18}$$$) — the initial and target value of the variable, respectively.", "output_spec": "Output $$$t$$$ lines, each line should contain one integer denoting the minimum number of operations Johnny needs to perform. If Johnny cannot get $$$b$$$ at the end, then write $$$-1$$$.", "sample_inputs": ["10\n10 5\n11 44\n17 21\n1 1\n96 3\n2 128\n1001 1100611139403776\n1000000000000000000 1000000000000000000\n7 1\n10 8"], "sample_outputs": ["1\n1\n-1\n0\n2\n2\n14\n0\n-1\n-1"], "notes": "NoteIn the first test case, Johnny can reach $$$5$$$ from $$$10$$$ by using the shift to the right by one (i.e. divide by $$$2$$$).In the second test case, Johnny can reach $$$44$$$ from $$$11$$$ by using the shift to the left by two (i.e. multiply by $$$4$$$).In the third test case, it is impossible for Johnny to reach $$$21$$$ from $$$17$$$.In the fourth test case, initial and target values are equal, so Johnny has to do $$$0$$$ operations.In the fifth test case, Johnny can reach $$$3$$$ from $$$96$$$ by using two shifts to the right: one by $$$2$$$, and another by $$$3$$$ (i.e. divide by $$$4$$$ and by $$$8$$$)."}, "positive_code": [{"source_code": "!function(t){var e={};function r(o){if(e[o])return e[o].exports;var n=e[o]={i:o,l:!1,exports:{}};return t[o].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=t,r.c=e,r.d=function(t,e,o){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:o})},r.r=function(t){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&\"object\"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(r.r(o),Object.defineProperty(o,\"default\",{enumerable:!0,value:t}),2&e&&\"string\"!=typeof t)for(var n in t)r.d(o,n,function(e){return t[e]}.bind(null,n));return o},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,\"a\",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p=\"\",r(r.s=0)}([function(t,e,r){const o=r(1);process.stdin.resume(),process.stdin.setEncoding(\"utf-8\");class n{static construct(){this.input=\"\",this.ptr=0}static readString(){return this.input[this.ptr++]}static readStrings(){return this.input[this.ptr++].split(\" \")}static readInt(){return+this.readString()}static readInts(){return this.readStrings().map(t=>+t)}static readBigInteger(){return o(this.readString())}static readBigIntegers(){return this.readStrings().map(t=>o(t))}}function i(...t){console.log(...t)}n.construct(),process.stdin.on(\"data\",t=>{n.input+=t}),process.stdin.on(\"end\",()=>{n.input=n.input.split(\"\\n\").map(t=>t.replace(/(\\r\\n|\\n|\\r)/gm,\"\")),function(){let t=n.readInts();for(;t--;){let[t,e]=n.readBigIntegers();1===t.compare(e)&&([t,e]=[e,t]);let r=o(0);for(;-1===t.compare(e);){const o=t.multiply(8),n=t.multiply(4),i=t.multiply(2);if(o.compare(e)<=0)t=o;else if(n.compare(e)<=0)t=n;else{if(!(i.compare(e)<=0)){r=-1;break}t=i}r=r.next()}i(r.toString())}}()})},function(t,e,r){(function(t){var o,n=function(t){\"use strict\";var e=9007199254740992,r=l(e),o=\"function\"==typeof BigInt;function i(t,e,r,o){return void 0===t?i[0]:void 0!==e&&(10!=+e||r)?k(t,e,r,o):$(t)}function u(t,e){this.value=t,this.sign=e,this.isSmall=!1}function p(t){this.value=t,this.sign=t<0,this.isSmall=!0}function a(t){this.value=t}function s(t){return-e0?Math.floor(t):Math.ceil(t)}function c(t,e){var r,o,n=t.length,i=e.length,u=new Array(n),p=0;for(o=0;o=1e7?1:0,u[o]=r-1e7*p;for(;o0&&u.push(p),u}function g(t,e){return t.length>=e.length?c(t,e):c(e,t)}function d(t,e){var r,o,n=t.length,i=new Array(n);for(o=0;o0;)i[o++]=e%1e7,e=Math.floor(e/1e7);return i}function m(t,e){var r,o,n=t.length,i=e.length,u=new Array(n),p=0;for(r=0;r0;)i[o++]=u%1e7,u=Math.floor(u/1e7);return i}function q(t,e){for(var r=[];e-- >0;)r.push(0);return r.concat(t)}function M(t,e,r){return new u(t<1e7?S(e,t):w(e,l(t)),r)}function N(t){var e,r,o,n,i=t.length,u=h(i+i);for(o=0;o=0;--r)n=(i=1e7*n+t[r])-(o=y(i/e))*e,p[r]=0|o;return[p,0|n]}function O(t,e){var r,n=$(e);if(o)return[new a(t.value/n.value),new a(t.value%n.value)];var s,c=t.value,g=n.value;if(0===g)throw new Error(\"Cannot divide by zero\");if(t.isSmall)return n.isSmall?[new p(y(c/g)),new p(c%g)]:[i[0],t];if(n.isSmall){if(1===g)return[t,i[0]];if(-1==g)return[t.negate(),i[0]];var d=Math.abs(g);if(d<1e7){s=f((r=E(c,d))[0]);var b=r[1];return t.sign&&(b=-b),\"number\"==typeof s?(t.sign!==n.sign&&(s=-s),[new p(s),new p(b)]):[new u(s,t.sign!==n.sign),new p(b)]}g=l(d)}var w=I(c,g);if(-1===w)return[i[0],t];if(0===w)return[i[t.sign===n.sign?1:-1],i[0]];s=(r=c.length+g.length<=200?function(t,e){var r,o,n,i,u,p,a,s=t.length,l=e.length,v=h(e.length),y=e[l-1],c=Math.ceil(1e7/(2*y)),g=S(t,c),d=S(e,c);for(g.length<=s&&g.push(0),d.push(0),y=d[l-1],o=s-l;o>=0;o--){for(r=1e7-1,g[o+l]!==y&&(r=Math.floor((1e7*g[o+l]+g[o+l-1])/y)),n=0,i=0,p=d.length,u=0;ua&&(n=1e7*(n+1)),r=Math.ceil(n/i);do{if(I(u=S(e,r),l)<=0)break;r--}while(r);s.push(r),l=m(l,u)}return s.reverse(),[f(s),f(l)]}(c,g))[0];var q=t.sign!==n.sign,M=r[1],N=t.sign;return\"number\"==typeof s?(q&&(s=-s),s=new p(s)):s=new u(s,q),\"number\"==typeof M?(N&&(M=-M),M=new p(M)):M=new u(M,N),[s,M]}function I(t,e){if(t.length!==e.length)return t.length>e.length?1:-1;for(var r=t.length-1;r>=0;r--)if(t[r]!==e[r])return t[r]>e[r]?1:-1;return 0}function P(t){var e=t.abs();return!e.isUnit()&&(!!(e.equals(2)||e.equals(3)||e.equals(5))||!(e.isEven()||e.isDivisibleBy(3)||e.isDivisibleBy(5))&&(!!e.lesser(49)||void 0))}function B(t,e){for(var r,o,i,u=t.prev(),p=u,a=0;p.isEven();)p=p.divide(2),a++;t:for(o=0;o=0?o=m(t,e):(o=m(e,t),r=!r),\"number\"==typeof(o=f(o))?(r&&(o=-o),new p(o)):new u(o,r)}(r,o,this.sign)},u.prototype.minus=u.prototype.subtract,p.prototype.subtract=function(t){var e=$(t),r=this.value;if(r<0!==e.sign)return this.add(e.negate());var o=e.value;return e.isSmall?new p(r-o):b(o,Math.abs(r),r>=0)},p.prototype.minus=p.prototype.subtract,a.prototype.subtract=function(t){return new a(this.value-$(t).value)},a.prototype.minus=a.prototype.subtract,u.prototype.negate=function(){return new u(this.value,!this.sign)},p.prototype.negate=function(){var t=this.sign,e=new p(-this.value);return e.sign=!t,e},a.prototype.negate=function(){return new a(-this.value)},u.prototype.abs=function(){return new u(this.value,!1)},p.prototype.abs=function(){return new p(Math.abs(this.value))},a.prototype.abs=function(){return new a(this.value>=0?this.value:-this.value)},u.prototype.multiply=function(t){var e,r,o,n=$(t),p=this.value,a=n.value,s=this.sign!==n.sign;if(n.isSmall){if(0===a)return i[0];if(1===a)return this;if(-1===a)return this.negate();if((e=Math.abs(a))<1e7)return new u(S(p,e),s);a=l(e)}return r=p.length,o=a.length,new u(-.012*r-.012*o+15e-6*r*o>0?function t(e,r){var o=Math.max(e.length,r.length);if(o<=30)return w(e,r);o=Math.ceil(o/2);var n=e.slice(o),i=e.slice(0,o),u=r.slice(o),p=r.slice(0,o),a=t(i,p),s=t(n,u),l=t(g(i,n),g(p,u)),f=g(g(a,q(m(m(l,a),s),o)),q(s,2*o));return v(f),f}(p,a):w(p,a),s)},u.prototype.times=u.prototype.multiply,p.prototype._multiplyBySmall=function(t){return s(t.value*this.value)?new p(t.value*this.value):M(Math.abs(t.value),l(Math.abs(this.value)),this.sign!==t.sign)},u.prototype._multiplyBySmall=function(t){return 0===t.value?i[0]:1===t.value?this:-1===t.value?this.negate():M(Math.abs(t.value),this.value,this.sign!==t.sign)},p.prototype.multiply=function(t){return $(t)._multiplyBySmall(this)},p.prototype.times=p.prototype.multiply,a.prototype.multiply=function(t){return new a(this.value*$(t).value)},a.prototype.times=a.prototype.multiply,u.prototype.square=function(){return new u(N(this.value),!1)},p.prototype.square=function(){var t=this.value*this.value;return s(t)?new p(t):new u(N(l(Math.abs(this.value))),!1)},a.prototype.square=function(t){return new a(this.value*this.value)},u.prototype.divmod=function(t){var e=O(this,t);return{quotient:e[0],remainder:e[1]}},a.prototype.divmod=p.prototype.divmod=u.prototype.divmod,u.prototype.divide=function(t){return O(this,t)[0]},a.prototype.over=a.prototype.divide=function(t){return new a(this.value/$(t).value)},p.prototype.over=p.prototype.divide=u.prototype.over=u.prototype.divide,u.prototype.mod=function(t){return O(this,t)[1]},a.prototype.mod=a.prototype.remainder=function(t){return new a(this.value%$(t).value)},p.prototype.remainder=p.prototype.mod=u.prototype.remainder=u.prototype.mod,u.prototype.pow=function(t){var e,r,o,n=$(t),u=this.value,a=n.value;if(0===a)return i[1];if(0===u)return i[0];if(1===u)return i[1];if(-1===u)return n.isEven()?i[1]:i[-1];if(n.sign)return i[0];if(!n.isSmall)throw new Error(\"The exponent \"+n.toString()+\" is too large.\");if(this.isSmall&&s(e=Math.pow(u,a)))return new p(y(e));for(r=this,o=i[1];!0&a&&(o=o.times(r),--a),0!==a;)a/=2,r=r.square();return o},p.prototype.pow=u.prototype.pow,a.prototype.pow=function(t){var e=$(t),r=this.value,o=e.value,n=BigInt(0),u=BigInt(1),p=BigInt(2);if(o===n)return i[1];if(r===n)return i[0];if(r===u)return i[1];if(r===BigInt(-1))return e.isEven()?i[1]:i[-1];if(e.isNegative())return new a(n);for(var s=this,l=i[1];(o&u)===u&&(l=l.times(s),--o),o!==n;)o/=p,s=s.square();return l},u.prototype.modPow=function(t,e){if(t=$(t),(e=$(e)).isZero())throw new Error(\"Cannot take modPow with modulus 0\");var r=i[1],o=this.mod(e);for(t.isNegative()&&(t=t.multiply(i[-1]),o=o.modInv(e));t.isPositive();){if(o.isZero())return i[0];t.isOdd()&&(r=r.multiply(o).mod(e)),t=t.divide(2),o=o.square().mod(e)}return r},a.prototype.modPow=p.prototype.modPow=u.prototype.modPow,u.prototype.compareAbs=function(t){var e=$(t),r=this.value,o=e.value;return e.isSmall?1:I(r,o)},p.prototype.compareAbs=function(t){var e=$(t),r=Math.abs(this.value),o=e.value;return e.isSmall?r===(o=Math.abs(o))?0:r>o?1:-1:-1},a.prototype.compareAbs=function(t){var e=this.value,r=$(t).value;return(e=e>=0?e:-e)===(r=r>=0?r:-r)?0:e>r?1:-1},u.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=$(t),r=this.value,o=e.value;return this.sign!==e.sign?e.sign?1:-1:e.isSmall?this.sign?-1:1:I(r,o)*(this.sign?-1:1)},u.prototype.compareTo=u.prototype.compare,p.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=$(t),r=this.value,o=e.value;return e.isSmall?r==o?0:r>o?1:-1:r<0!==e.sign?r<0?-1:1:r<0?1:-1},p.prototype.compareTo=p.prototype.compare,a.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=this.value,r=$(t).value;return e===r?0:e>r?1:-1},a.prototype.compareTo=a.prototype.compare,u.prototype.equals=function(t){return 0===this.compare(t)},a.prototype.eq=a.prototype.equals=p.prototype.eq=p.prototype.equals=u.prototype.eq=u.prototype.equals,u.prototype.notEquals=function(t){return 0!==this.compare(t)},a.prototype.neq=a.prototype.notEquals=p.prototype.neq=p.prototype.notEquals=u.prototype.neq=u.prototype.notEquals,u.prototype.greater=function(t){return this.compare(t)>0},a.prototype.gt=a.prototype.greater=p.prototype.gt=p.prototype.greater=u.prototype.gt=u.prototype.greater,u.prototype.lesser=function(t){return this.compare(t)<0},a.prototype.lt=a.prototype.lesser=p.prototype.lt=p.prototype.lesser=u.prototype.lt=u.prototype.lesser,u.prototype.greaterOrEquals=function(t){return this.compare(t)>=0},a.prototype.geq=a.prototype.greaterOrEquals=p.prototype.geq=p.prototype.greaterOrEquals=u.prototype.geq=u.prototype.greaterOrEquals,u.prototype.lesserOrEquals=function(t){return this.compare(t)<=0},a.prototype.leq=a.prototype.lesserOrEquals=p.prototype.leq=p.prototype.lesserOrEquals=u.prototype.leq=u.prototype.lesserOrEquals,u.prototype.isEven=function(){return 0==(1&this.value[0])},p.prototype.isEven=function(){return 0==(1&this.value)},a.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},u.prototype.isOdd=function(){return 1==(1&this.value[0])},p.prototype.isOdd=function(){return 1==(1&this.value)},a.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},u.prototype.isPositive=function(){return!this.sign},p.prototype.isPositive=function(){return this.value>0},a.prototype.isPositive=p.prototype.isPositive,u.prototype.isNegative=function(){return this.sign},p.prototype.isNegative=function(){return this.value<0},a.prototype.isNegative=p.prototype.isNegative,u.prototype.isUnit=function(){return!1},p.prototype.isUnit=function(){return 1===Math.abs(this.value)},a.prototype.isUnit=function(){return this.abs().value===BigInt(1)},u.prototype.isZero=function(){return!1},p.prototype.isZero=function(){return 0===this.value},a.prototype.isZero=function(){return this.value===BigInt(0)},u.prototype.isDivisibleBy=function(t){var e=$(t);return!e.isZero()&&(!!e.isUnit()||(0===e.compareAbs(2)?this.isEven():this.mod(e).isZero()))},a.prototype.isDivisibleBy=p.prototype.isDivisibleBy=u.prototype.isDivisibleBy,u.prototype.isPrime=function(t){var e=P(this);if(void 0!==e)return e;var r=this.abs(),o=r.bitLength();if(o<=64)return B(r,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var i=Math.log(2)*o.toJSNumber(),u=Math.ceil(!0===t?2*Math.pow(i,2):i),p=[],a=0;a-e?new p(t-1):new u(r,!0)},a.prototype.prev=function(){return new a(this.value-BigInt(1))};for(var x=[1];2*x[x.length-1]<=1e7;)x.push(2*x[x.length-1]);var A=x.length,Z=x[A-1];function j(t){return Math.abs(t)<=1e7}function J(t,e,r){e=$(e);for(var o=t.isNegative(),i=e.isNegative(),u=o?t.not():t,p=i?e.not():e,a=0,s=0,l=null,f=null,v=[];!u.isZero()||!p.isZero();)a=(l=O(u,Z))[1].toJSNumber(),o&&(a=Z-1-a),s=(f=O(p,Z))[1].toJSNumber(),i&&(s=Z-1-s),u=l[0],p=f[0],v.push(r(a,s));for(var h=0!==r(o?1:0,i?1:0)?n(-1):n(0),y=v.length-1;y>=0;y-=1)h=h.multiply(Z).add(n(v[y]));return h}u.prototype.shiftLeft=function(t){var e=$(t).toJSNumber();if(!j(e))throw new Error(String(e)+\" is too large for shifting.\");if(e<0)return this.shiftRight(-e);var r=this;if(r.isZero())return r;for(;e>=A;)r=r.multiply(Z),e-=A-1;return r.multiply(x[e])},a.prototype.shiftLeft=p.prototype.shiftLeft=u.prototype.shiftLeft,u.prototype.shiftRight=function(t){var e,r=$(t).toJSNumber();if(!j(r))throw new Error(String(r)+\" is too large for shifting.\");if(r<0)return this.shiftLeft(-r);for(var o=this;r>=A;){if(o.isZero()||o.isNegative()&&o.isUnit())return o;o=(e=O(o,Z))[1].isNegative()?e[0].prev():e[0],r-=A-1}return(e=O(o,x[r]))[1].isNegative()?e[0].prev():e[0]},a.prototype.shiftRight=p.prototype.shiftRight=u.prototype.shiftRight,u.prototype.not=function(){return this.negate().prev()},a.prototype.not=p.prototype.not=u.prototype.not,u.prototype.and=function(t){return J(this,t,(function(t,e){return t&e}))},a.prototype.and=p.prototype.and=u.prototype.and,u.prototype.or=function(t){return J(this,t,(function(t,e){return t|e}))},a.prototype.or=p.prototype.or=u.prototype.or,u.prototype.xor=function(t){return J(this,t,(function(t,e){return t^e}))},a.prototype.xor=p.prototype.xor=u.prototype.xor;function L(t){var e=t.value,r=\"number\"==typeof e?e|1<<30:\"bigint\"==typeof e?e|BigInt(1<<30):e[0]+1e7*e[1]|1073758208;return r&-r}function U(t,e){return t=$(t),e=$(e),t.greater(e)?t:e}function T(t,e){return t=$(t),e=$(e),t.lesser(e)?t:e}function _(t,e){if(t=$(t).abs(),e=$(e).abs(),t.equals(e))return t;if(t.isZero())return e;if(e.isZero())return t;for(var r,o,n=i[1];t.isEven()&&e.isEven();)r=T(L(t),L(e)),t=t.divide(r),e=e.divide(r),n=n.multiply(r);for(;t.isEven();)t=t.divide(L(t));do{for(;e.isEven();)e=e.divide(L(e));t.greater(e)&&(o=e,e=t,t=o),e=e.subtract(t)}while(!e.isZero());return n.isUnit()?t:t.multiply(n)}u.prototype.bitLength=function(){var t=this;return t.compareTo(n(0))<0&&(t=t.negate().subtract(n(1))),0===t.compareTo(n(0))?n(0):n(function t(e,r){if(r.compareTo(e)<=0){var o=t(e,r.square(r)),i=o.p,u=o.e,p=i.multiply(r);return p.compareTo(e)<=0?{p:p,e:2*u+1}:{p:i,e:2*u}}return{p:n(1),e:0}}(t,n(2)).e).add(n(1))},a.prototype.bitLength=p.prototype.bitLength=u.prototype.bitLength;var k=function(t,e,r,o){r=r||\"0123456789abcdefghijklmnopqrstuvwxyz\",t=String(t),o||(t=t.toLowerCase(),r=r.toLowerCase());var n,i=t.length,u=Math.abs(e),p={};for(n=0;n=u)){if(\"1\"===l&&1===u)continue;throw new Error(l+\" is not a valid digit in base \"+e+\".\")}}e=$(e);var a=[],s=\"-\"===t[0];for(n=s?1:0;n\"!==t[n]&&n=0;o--)n=n.add(t[o].times(u)),u=u.times(e);return r?n.negate():n}function C(t,e){if((e=n(e)).isZero()){if(t.isZero())return{value:[0],isNegative:!1};throw new Error(\"Cannot convert nonzero numbers to base 0.\")}if(e.equals(-1)){if(t.isZero())return{value:[0],isNegative:!1};if(t.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-t.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var r=Array.apply(null,Array(t.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return r.unshift([1]),{value:[].concat.apply([],r),isNegative:!1}}var o=!1;if(t.isNegative()&&e.isPositive()&&(o=!0,t=t.abs()),e.isUnit())return t.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(t.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:o};for(var i,u=[],p=t;p.isNegative()||p.compareAbs(e)>=0;){i=p.divmod(e),p=i.quotient;var a=i.remainder;a.isNegative()&&(a=e.minus(a).abs(),p=p.next()),u.push(a.toJSNumber())}return u.push(p.toJSNumber()),{value:u.reverse(),isNegative:o}}function D(t,e,r){var o=C(t,e);return(o.isNegative?\"-\":\"\")+o.value.map((function(t){return function(t,e){return t<(e=e||\"0123456789abcdefghijklmnopqrstuvwxyz\").length?e[t]:\"<\"+t+\">\"}(t,r)})).join(\"\")}function R(t){if(s(+t)){var e=+t;if(e===y(e))return o?new a(BigInt(e)):new p(e);throw new Error(\"Invalid integer: \"+t)}var r=\"-\"===t[0];r&&(t=t.slice(1));var n=t.split(/e/i);if(n.length>2)throw new Error(\"Invalid integer: \"+n.join(\"e\"));if(2===n.length){var i=n[1];if(\"+\"===i[0]&&(i=i.slice(1)),(i=+i)!==y(i)||!s(i))throw new Error(\"Invalid integer: \"+i+\" is not a valid exponent.\");var l=n[0],f=l.indexOf(\".\");if(f>=0&&(i-=l.length-f-1,l=l.slice(0,f)+l.slice(f+1)),i<0)throw new Error(\"Cannot include negative exponent part for integers\");t=l+=new Array(i+1).join(\"0\")}if(!/^([0-9][0-9]*)$/.test(t))throw new Error(\"Invalid integer: \"+t);if(o)return new a(BigInt(r?\"-\"+t:t));for(var h=[],c=t.length,g=c-7;c>0;)h.push(+t.slice(g,c)),(g-=7)<0&&(g=0),c-=7;return v(h),new u(h,r)}function $(t){return\"number\"==typeof t?function(t){if(o)return new a(BigInt(t));if(s(t)){if(t!==y(t))throw new Error(t+\" is not an integer.\");return new p(t)}return R(t.toString())}(t):\"string\"==typeof t?R(t):\"bigint\"==typeof t?new a(t):t}u.prototype.toArray=function(t){return C(this,t)},p.prototype.toArray=function(t){return C(this,t)},a.prototype.toArray=function(t){return C(this,t)},u.prototype.toString=function(t,e){if(void 0===t&&(t=10),10!==t)return D(this,t,e);for(var r,o=this.value,n=o.length,i=String(o[--n]);--n>=0;)r=String(o[n]),i+=\"0000000\".slice(r.length)+r;return(this.sign?\"-\":\"\")+i},p.prototype.toString=function(t,e){return void 0===t&&(t=10),10!=t?D(this,t,e):String(this.value)},a.prototype.toString=p.prototype.toString,a.prototype.toJSON=u.prototype.toJSON=p.prototype.toJSON=function(){return this.toString()},u.prototype.valueOf=function(){return parseInt(this.toString(),10)},u.prototype.toJSNumber=u.prototype.valueOf,p.prototype.valueOf=function(){return this.value},p.prototype.toJSNumber=p.prototype.valueOf,a.prototype.valueOf=a.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var F=0;F<1e3;F++)i[F]=$(F),F>0&&(i[-F]=$(-F));return i.one=i[1],i.zero=i[0],i.minusOne=i[-1],i.max=U,i.min=T,i.gcd=_,i.lcm=function(t,e){return t=$(t).abs(),e=$(e).abs(),t.divide(_(t,e)).multiply(e)},i.isInstance=function(t){return t instanceof u||t instanceof p||t instanceof a},i.randBetween=function(t,e,r){t=$(t),e=$(e);var o=r||Math.random,n=T(t,e),u=U(t,e).subtract(n).add(1);if(u.isSmall)return n.add(Math.floor(o()*u));for(var p=C(u,1e7).value,a=[],s=!0,l=0;l +a)\n }\n\n static readBigInteger() {\n return bg(this.readString())\n }\n\n static readBigIntegers() {\n return this.readStrings().map(a => bg(a))\n }\n}\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if (inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nrc.construct()\n// bc.construct()\nprocess.stdin.on('data', (i) => {\n rc.input += i\n})\n\nprocess.stdin.on('end', () => {\n rc.input = rc.input.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main()\n})\n\nfunction main() {\n let t = rc.readInts()\n while(t--) {\n let [a, b] = rc.readBigIntegers()\n if(a.compare(b) === 1) {\n [a, b] = [b, a]\n }\n let ans = bg(0)\n while(a.compare(b) === -1) {\n const a8 = a.multiply(8)\n const a4 = a.multiply(4)\n const a2 = a.multiply(2)\n if(a8.compare(b) <= 0) a = a8\n else if(a4.compare(b) <= 0) a = a4\n else if(a2.compare(b) <= 0) a = a2\n else {\n ans = -1\n break\n }\n ans = ans.next()\n }\n wr(ans.toString())\n }\n}\n*/\n\n\n/*Bundled using webpack*/\n\n"}], "negative_code": [], "src_uid": "541039ef3c9b8251b758608811533e06"} {"nl": {"description": "Artem is building a new robot. He has a matrix $$$a$$$ consisting of $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{i,j}$$$ written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side. Artem wants to increment the values in some cells by one to make $$$a$$$ good.More formally, find a good matrix $$$b$$$ that satisfies the following condition — For all valid ($$$i,j$$$), either $$$b_{i,j} = a_{i,j}$$$ or $$$b_{i,j} = a_{i,j}+1$$$. For the constraints of this problem, it can be shown that such a matrix $$$b$$$ always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n, m$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m \\le 100$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines each contain $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$a_{i,j}$$$ ($$$1 \\leq a_{i,j} \\leq 10^9$$$).", "output_spec": "For each case, output $$$n$$$ lines each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$b_{i,j}$$$.", "sample_inputs": ["3\n3 2\n1 2\n4 5\n7 8\n2 2\n1 1\n3 3\n2 2\n1 3\n2 2"], "sample_outputs": ["1 2\n5 6\n7 8\n2 1\n4 3\n2 4\n3 2"], "notes": "NoteIn all the cases, you can verify that no two adjacent cells have the same value and that $$$b$$$ is the same as $$$a$$$ with some values incremented by one. "}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [rowLen, colLen] = readLine().split(\" \").map(Number);\n const arr = [];\n let i = 0;\n while (i++ < rowLen) {\n const row = readLine().split(\" \").map(Number);\n arr.push(row);\n }\n for (let row = 0; row < rowLen; row++) {\n for (let col = 0; col < colLen; col++) {\n if ((row + col) % 2 === 0) {\n if (arr[row][col] % 2 === 1) arr[row][col]++;\n } else {\n if (arr[row][col] % 2 === 0) arr[row][col]++;\n }\n }\n }\n for (let row = 0; row < rowLen; row++) console.log(arr[row].join(\" \"));\n }\n}\n"}, {"source_code": "let input = ''\n\nprocess.stdin.on('data', (x) => input += x)\n\nprocess.stdin.on('end', () => {\n const lines = input.trim().split('\\n')\n const T = parseInt(lines[0])\n let curLine = 1\n for (let t = 0; t < T; t++) {\n const [n] = lines[curLine++].split(' ').map((x) => parseInt(x))\n for (let r = 0; r < n; r++) {\n console.log(lines[curLine++].split(' ').map((x, c) => parseInt(x) + (r + c + parseInt(x)) % 2).join(' '))\n }\n }\n})\n"}], "negative_code": [{"source_code": "let input = ''\n\nprocess.stdin.on('data', (x) => input += x)\n\nprocess.stdin.on('end', () => {\n const lines = input.trim().split('\\n')\n const T = parseInt(lines[0])\n let curLine = 1\n for (let t = 0; t < T; t++) {\n const [n, m] = lines[curLine++].split(' ').map((x) => parseInt(x))\n const mat = new Array(n)\n const cells = []\n for (let r = 0; r < n; r++) {\n mat[r] = lines[curLine++].split(' ').map((x) => parseInt(x))\n for (let c = 0; c < m; c++) {\n cells.push([r, c])\n }\n }\n cells.sort(([ra, ca], [rb, cb]) => mat[ra][ca] - mat[rb][cb])\n cells.forEach(([r, c]) => {\n const delta = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n let change = false\n delta.forEach(([dr, dc]) => {\n const nr = r + dr\n const nc = c + dc\n \n if (nr < 0 || nr >= n || nc < 0 || nc >= m) {\n return\n }\n\n if (mat[nr][nc] === mat[r][c]) {\n change = true\n }\n })\n\n if (change) {\n mat[r][c]++\n }\n })\n\n for (let r = 0; r < n; r++) {\n console.log(mat[r].join(' '))\n } \n } \n})\n"}, {"source_code": "let input = ''\n\nprocess.stdin.on('data', (x) => input += x)\n\nprocess.stdin.on('end', () => {\n const lines = input.trim().split('\\n')\n const T = parseInt(lines[0])\n let curLine = 1\n for (let t = 0; t < T; t++) {\n const [n, m] = lines[curLine++].split(' ').map((x) => parseInt(x))\n const mat = new Array(n)\n const cells = []\n for (let r = 0; r < n; r++) {\n mat[r] = lines[curLine++].split(' ').map((x) => parseInt(x))\n for (let c = 0; c < m; c++) {\n cells.push([r, c])\n }\n }\n cells.sort(([ra, ca], [rb, cb]) => mat[ra][ca] - mat[rb][cb])\n for (let rem = 0; rem < 2; rem++) {\n cells.forEach(([r, c]) => {\n if ((r + c) % 2 !== rem) {\n return\n }\n \n const delta = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n let change = false\n delta.forEach(([dr, dc]) => {\n const nr = r + dr\n const nc = c + dc\n \n if (nr < 0 || nr >= n || nc < 0 || nc >= m) {\n return\n }\n\n if (mat[nr][nc] === mat[r][c]) {\n change = true\n }\n })\n\n if (change) {\n mat[r][c]++\n }\n })\n }\n\n for (let r = 0; r < n; r++) {\n console.log(mat[r].join(' '))\n } \n } \n})\n"}], "src_uid": "fd11967b07870be3294b9191603b17e8"} {"nl": {"description": "Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s.", "input_spec": "The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only.", "output_spec": "If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages.", "sample_inputs": ["next\n2\nnextpermutation\nnextelement", "find\n4\nfind\nfindfirstof\nfindit\nfand", "find\n4\nfondfind\nfondfirstof\nfondit\nfand"], "sample_outputs": ["nextelement", "find", "find"], "notes": null}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar prefix = trim(readline());\n\n\tvar numCandidates = parseInt(readline(), 10),\n\t\tcandidates = new Array(numCandidates);\n\tfor (var candidateIndex = 0; candidateIndex < numCandidates; ++candidateIndex) {\n\t\tcandidates[candidateIndex] = trim(readline());\n\t}\n\n\tcandidates.sort();\n\n\tvar regex = new RegExp(\"^\"+prefix);\n\n\tfor (var candidateIndex = 0; candidateIndex < numCandidates; ++candidateIndex) {\n\t\tif (regex.test(candidates[candidateIndex])) {\n\t\t\tprint(candidates[candidateIndex]);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprint(prefix);\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar prefix = trim(readline());\n\n\tvar numCandidates = parseInt(readline(), 10),\n\t\tcandidates = new Array(numCandidates);\n\tfor (var candidateIndex = 0; candidateIndex < numCandidates; ++candidateIndex) {\n\t\tcandidates[candidateIndex] = trim(readline());\n\t}\n\n\tcandidates.sort();\n\n\tvar regex = new RegExp(\"^\"+prefix);\n\n\tfor (var candidateIndex = 0; candidateIndex < numCandidates; ++candidateIndex) {\n\t\tif (candidates[candidateIndex].match(regex)) {\n\t\t\tprint(candidates[candidateIndex]);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprint(prefix);\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar prefix = trim(readline()),\n\t\tprefixLength = prefix.length;\n\n\tvar numCandidates = parseInt(readline(), 10),\n\t\tcandidates = new Array(numCandidates);\n\tfor (var candidateIndex = 0; candidateIndex < numCandidates; ++candidateIndex) {\n\t\tcandidates[candidateIndex] = trim(readline());\n\t}\n\n\tcandidates.sort();\n\n\tfor (var candidateIndex = 0; candidateIndex < numCandidates; ++candidateIndex) {\n\t\tif (candidates[candidateIndex].substring(0, prefixLength) == prefix) {\n\t\t\tprint(candidates[candidateIndex]);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprint(prefix);\n}\n\nmain();\n"}, {"source_code": "'use strict'\n\nlet inp = readline()\nlet N = +readline()\nlet lll\n\nlet dic = []\nwhile (lll = readline()) {\n dic.push(lll)\n}\n\nprint(dic.filter(w => w.startsWith(inp)).sort()[0] || inp)"}, {"source_code": "var input = readline();\nvar check = new RegExp('^' + input);\nvar iteration = readline();\n\nvar result;\n\nfor (var i = 0; i < iteration; i++) {\n\tvar currentInput = readline();\n\t//currentInput.match(check)&& result?(( currentInput < result)&&result = currentInput):\tresult = currentInput\n\tif (currentInput.match(check)) {\n\nresult? (currentInput < result?\tresult = currentInput:result):(result = currentInput)\n\t}\n\n}\n \n\n\n!!result? print(result):print(input)\n\n"}, {"source_code": "var word = readline();\nvar re = new RegExp('^' + word);\nvar n = parseInt(readline());\nvar res;\nfor (var i = 0; i < n; i++) {\n\tvar input = readline();\n\tif (input.match(re)) {\n\t\tif (res) {\n\t\t\tif (input < res) {\n\t\t\t\tres = input;\n\t\t\t}\n\t\t} else {\n\t\t\tres = input;\n\t\t}\n\t}\n}\n\nif (res) {\n\tprint(res);\n} else {\n\tprint(word);\n}\n"}], "negative_code": [{"source_code": "var input = readline();\nvar iteration = readline();\nvar check = new RegExp('^' + input);\n \nvar result;\n \nfor (var i = 0; i < iteration; i++) {\n\tvar currentInput = readline();\n\tcurrentInput.match(check)&& result? (currentInput < result? result = currentInput : result) : (result = currentInput)\n}\n!!result? print(result):print(input)"}, {"source_code": "var input = readline();\nvar iteration = readline();\nvar check = new RegExp('^' + input);\n\nvar result;\n\nfor (var i = 0; i < iteration; i++) {\n\tvar currentInput = readline();\n\tcurrentInput.match(check)&& result? (currentInput < result? (result = currentInput) : result) : (result = currentInput)\n}\n!!result? print(result):print(input)\n\n"}], "src_uid": "5ad16e23e96de111c4974551b859a5ff"} {"nl": {"description": "Given an array a1, a2, ..., an 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 = y2.", "input_spec": "The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second line contains n integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — 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": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n arr.sort((a, b) => b - a);\n\n for (let i = 0; i < arr.length; i++) {\n if (!Number.isInteger(Math.sqrt(arr[i]))) {\n console.log(arr[i]);\n break;\n }\n }\n\n c++;\n});\n"}, {"source_code": "var x=parseInt(readline());\nvar arr=readline().split(' ').map(a => parseInt(a));\n\narr.sort((a,b) => a-b);\n\nfor(var i=arr.length-1; i>=0; i--){\n var sqrt= Math.floor(Math.sqrt(arr[i]));\n if(sqrt*sqrt !== arr[i]){\n print(arr[i]);\n break;\n }else\n continue;\n}"}, {"source_code": "n=parseInt(readline());\nmas=readline().split(' ');\nfunction compareNumeric(a, b) {\n if (a > b) return 1;\n if (a < b) return -1;\n}\nfor(i=0;i Number.parseInt(x));\n\nfunction isPerfect(x){\n var comp = Math.sqrt(x).toFixed(0)\n\n return x == comp * comp;\n}\nvar max = -Infinity;\nfor(var i = 0; i < nums.length; i++){\n if(!isPerfect(nums[i])){\n max = Math.max(max, nums[i]);\n }\n}\n\nprint(max);"}, {"source_code": "readline()\nprint(readline().split(' ').map(x=>+x).reduce((a,c)=>Math.pow(Math.trunc(Math.sqrt(c)),2)!==c?Math.max(a,c):a,-10000000))\n\n"}, {"source_code": "readline() \nprint(readline().split(' ').map(x=>+x).reduce((a,c)=>Math.pow(Math.trunc(Math.sqrt(c)),2)!==c?Math.max(a,c):a,-10000000))\n"}], "negative_code": [{"source_code": "var x=parseInt(readline());\nvar arr=readline().split(' ').map(a => parseInt(a));\n\narr.sort((a,b) => a-b);\n\nfor(var i=arr.length-1; i>=0; i--){\n var sqrt= Math.sqrt(arr[i]);\n if(sqrt*sqrt !== arr[i]){\n print(arr[i]);\n break;\n }else\n continue;\n}"}, {"source_code": "n=parseInt(readline());\nmas=readline().split('');\nfunction compareNumeric(a, b) {\n if (a > b) return 1;\n if (a < b) return -1;\n}\nfor(i=0;imax){\n\t\tmax2 = max;\n\t\tmax = v;\n\t\tindex = i;\n\t}else if(v>max2){\n\t\tmax2 = v;\n\t}\n});\nprint(index+1, max2);"}, {"source_code": "var\n num = parseInt(readline()),\n arr = readline().split(\" \")\n;\n\nfor(var i in arr) {\n arr[i] = parseInt(arr[i]);\n}\n\nvar sort = arr.slice(0);\nsort.sort(function(a, b){if(a==b) return 0; return a > b ? 1 : -1})\nsort.reverse()\n\nfor(var i in arr){\n if (sort[0] == arr[i]) {\n print((i - 1 + 2) + \" \" + sort[1])\n break;\n }\n}"}, {"source_code": "'use strict';\n\n/*let input = `2\n5 7`.split('\\n');\nfunction print(output) {\n\tconsole.log(output);\n}\nfunction readline() {\n\treturn input.shift();\n}*/\n\n//code\n\nvar n = Number(readline());\nvar prices = readline().split(' ').map(function (el, i) {\n\treturn { index: i, val: Number(el) };\n});\nprices.sort(function (a, b) {\n\treturn a.val - b.val;\n});\nprint(prices.pop().index + 1 + \" \" + prices.pop().val);\n"}, {"source_code": "readline();\nvar a=readline().split(\" \"),b=a.slice().sort(function(a,b){return +a-b}),l=b.length;print(a.indexOf(b[l-1])+1+\" \"+b[l-2]);"}, {"source_code": "var n = Number(readline());\nvar inp = readline().split(' ').map(cur => Number(cur));\nvar max = Math.max(...inp);\nvar index = inp.indexOf(max) \ninp.splice(index, 1);\nvar res = [index + 1, Math.max(...inp)];\nprint(res.join(' '));"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n const sortedArr = arr.slice();\n sortedArr.sort((a, b) => a - b);\n const max = sortedArr[sortedArr.length - 1];\n const secondMax = sortedArr[sortedArr.length - 2];\n let maxIdx;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === max) {\n maxIdx = i + 1;\n break;\n }\n }\n\n console.log(maxIdx, secondMax);\n\n c++;\n});\n"}], "negative_code": [{"source_code": "var \n num = readline(),\n arr = readline().split(\" \"),\n maxx = 0,\n index = 0\n;\n\nvar max = Math.max.apply(Math, arr);\n\nfor(var i in arr){\n if (arr[i] < max && arr[i] > maxx) {\n maxx = arr[i];\n \n }\n if (max == arr[i]) index = parseInt(i) + 1;\n}\n\nprint(index + \" \" + maxx)"}], "src_uid": "1d4aaf15e5c6fcde50515880aae74720"} {"nl": {"description": "Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area? Illustration to the first example. ", "input_spec": "The first and only line of input contains two space-separated integers, n and h (2 ≤ n ≤ 1000, 1 ≤ h ≤ 105).", "output_spec": "The output should contain n - 1 real numbers x1, x2, ..., xn - 1. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0 < x1 < x2 < ... < xn - 1 < h must hold. Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .", "sample_inputs": ["3 2", "2 100000"], "sample_outputs": ["1.154700538379 1.632993161855", "70710.678118654752"], "notes": "NoteDefinition of isosceles triangle: https://en.wikipedia.org/wiki/Isosceles_triangle."}, "positive_code": [{"source_code": " var tmp = readline().split(' ').map(x => parseInt(x));\n var n= tmp[0];\n var h = tmp[1];\n var res = [];\n for(var i = 0; i < n - 1; i += 1) {\n res.push(Math.sqrt((i + 1) / n) * h);\n }\n print(res.join(' '));\n"}], "negative_code": [], "src_uid": "6f8a1a138ea2620f2013f426e29e4d98"} {"nl": {"description": "Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark \"?\". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s=\"ab?b\" as a result, it will appear in t=\"aabrbb\" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol \"?\" should be considered equal to any other symbol.", "input_spec": "The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly. The second line contains n lowercase English letters — string s. The third line contains m lowercase English letters — string t.", "output_spec": "In the first line print single integer k — the minimal number of symbols that need to be replaced. In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.", "sample_inputs": ["3 5\nabc\nxaybz", "4 10\nabcd\nebceabazcd"], "sample_outputs": ["2\n2 3", "1\n2"], "notes": null}, "positive_code": [{"source_code": "var input = readline().split(' ').map(function(x){return Number(x)});\nvar a = input[0];\nvar b = input[1];\nvar s1 = readline();\nvar s2 = readline();\nvar min = 100000;\nvar res = [];\nfor(var i = 0 ; i <= (s2.length - s1.length) ; i++){\n var ss = s2.substring(i, i + s1.length);\n var tmp = [];\n var act = 0;\n for(var j = 0 ; j < s1.length ; j++){\n if( s1[j] !== ss[j] ){\n act++; tmp.push(j + 1);\n }\n }\n if(act < min){\n min = act;\n res = tmp;\n }\n}\n\nprint(min);\nfor(var i = 0 ; i < res.length ; i ++)write(res[i] + \" \");"}, {"source_code": "var st = readline().split(' ').map(Number);\nvar s = readline();\nvar t = readline();\nvar sl = st[0];\nvar tl = st[1];\nvar ans = 1100;\nvar pos = [];\nfor (var i=0; i<=tl-sl; i++){\n\tvar count = 0;\n\tvar poscount = [];\n\tfor (var j=0; j=ans)\n\t{\n\t ans=a[i].y;\n\t}\n\telse\n\t{\n\t ans=a[i].x;\n\t}\n}\nprint(ans);\n\nfunction sortObj(ojA, ojB)\n{\n if(ojA.x==ojB.x)\n\t{\n\t return ojA.y-ojB.y;\n\t}\n\telse\n\t{\n\t return ojA.x - ojB.x;\n\t}\n}"}, {"source_code": "var node = function(x) {\n this.a=x[0];\n this.b=x[1];\n}\n\nvar by_node = function(x,y){\n if(x.a!=y.a) return x.a\"+l.length+\" + \"+r.length);\n return ans;\n}\n\nvar merge_sort = function(arr,cmp) {\n if(!arr) return arr;\n if(arr.length<2) return arr;\n var mid = Math.floor(arr.length/2);\n var right=[];\n for(var i=mid;i=ans) ans=x.b;\n else ans=x.a;\n })\n print(ans);\n}\n\nmain();"}, {"source_code": "var intp = function(x){\n\treturn parseInt(x);\n}\n\nvar node = function(x){\n\tthis.a=parseInt(x[0]);\n\tthis.b=parseInt(x[1]);\n}\n\nvar by_node = function(x,y){\n\treturn x.a!=y.a?x.a>y.a:x.b>y.b;\n}\n\nvar out_type = function(x){\n\tprint(typeof(x.a)+\" \"+typeof(x.b));\n}\n\nvar out_value = function(x){\n\tprint(x.a+\" \"+x.b);\n}\n\nvar qsort = function(arr,cmp)\n{\n\tif(!arr) return [];\n\tif(arr.length<=1) return arr;\n\tvar p=Math.floor(Math.random()*arr.length);\n\tvar pv=arr[p];\n\tarr[p]=arr[arr.length-1];\n\tarr.length--;\n\tvar l=arr.filter(function(value){return cmp(pv,value);});\n\tvar r=arr.filter(function(value){return !cmp(pv,value);});\n\treturn qsort(l,cmp).concat([pv],qsort(r,cmp));\n}\n\nvar line;\nwhile(line=readline()) {\n\tvar n = line.split(' ').map(intp)[0];\n\tvar arr = [];\n\tfor(var i=0;i=ans) ans=x.b;\n\t\telse ans=x.a;\n\t});\n\tprint(ans);\n}\n"}, {"source_code": "var node = function(x){\n this.a=x[0];\n this.b=x[1];\n}\n\nvar by_node = function(x,y){\n if(x.a!=y.a) return x.a-y.a;\n return x.b-y.b;\n}\n\nvar out_value = function(x){\n print(x.a+\" \"+x.b);\n}\n\nwhile(true) {\n line = readline();\n if(!line) break;\n n = parseInt(line);\n var arr = new Array(n+5);\n for(var i=0;i=ans) ans=x.b;\n else ans=x.a;\n });\n print(ans);\n}"}, {"source_code": "var arr = [], elements;\nvar queries = parseInt(readline())\nfor (var l = 0; l < queries;l++){\n\telements = readline().split(' ').map((val)=>{\n\t\treturn parseInt(val);\n\t})\n\tarr.push(elements);\n}\narr.sort((a,b)=>{\n\tif (a[0] == b[0]){\n\t\treturn a[1] - b[1];\n\t}\n\telse{\n\treturn a[0] - b[0];\n\t}\n})\nvar enDay = Math.min(arr[0][0], arr[0][1])\nvar interim;\nfor (var k = 1; k= enDay){\n\t\tenDay = interim;\n\t}\n\telse{\n\t\tenDay = (interim == arr[k][0]) ? arr[k][1] : arr[k][0];\n\t}\n}\nprint(enDay)"}, {"source_code": "var n = parseInt(readline());\nvar a= [];\nfor (var i=0;i{ if ((a[0]-b[0])!==0) {return a[0]-b[0]} else {return a[1]-b[1]}}).map(function (xs) {var mi= Math.min.apply(null,xs); var ma = Math.max.apply(null,xs);if (mi>=this.t) {this.t=mi; return mi} else {this.t=ma; return ma}},{t:0}).pop();\nprint (p);"}, {"source_code": "var n = +readline();\nvar arr=[];\nfor(var i=0;i+v));\narr.sort((a,b)=>{\n if(a[0]===b[0])\n return a[1]-b[1];\n return a[0]-b[0];\n});\n\nvar prev=0;\nfor(var i=0;iy.a;\n else return x.b>y.b;\n})\n\nvar ans=arr[0].b;\n\nfor(var i=0;i=ans) ans=arr[i].b;\n else ans=arr[i].a;\n}\n\nprint(ans);"}, {"source_code": "n = parseInt(readline());\n\nvar arr=[];\n\nfor(var i=0;iy.a;\n else return x.b>y.b;\n})\n\nvar ans=arr[0].b;\n\nfor(var i=0;i=ans) ans=arr[i].b;\n else ans=arr[i].a;\n}\n\nprint(ans);"}, {"source_code": "n = parseInt(readline());\n\nvar arr=[];\n\nfor(var i=0;iy.a;\n else return x.b>y.b;\n})\n\nvar ans=arr[0].b;\n\nfor(var i=0;i=ans) ans=arr[i].b;\n else ans=arr[i].a;\n}\n\n\n\nprint(ans);"}, {"source_code": "n = parseInt(readline());\n\nvar arr=[];\n\nfor(var i=0;iy.a;\n else return x.b>y.b;\n})\n\nvar ans=arr[0].b;\n\narr.forEach(function(x){\n if(x.b>=ans) ans=x.b;\n else ans=x.a;\n})\n\nprint(ans);"}, {"source_code": "n = parseInt(readline());\n\nvar arr=[];\n\nfor(var i=0;iy.a;\n else return x.b>y.b;\n})\n\nvar ans=arr[0].b;\n\nfor(var i=0;i=ans) ans=arr[i].b;\n else ans=arr[i].a;\n}\n\nprint(ans);"}, {"source_code": "var arr = [], elements = []\nvar queries = parseInt(readline())\nfor (var l = 0; l < queries;l++){\n\treadline().split(' ').map((val)=>{\n\t\telements.push(parseInt(val));\n\t})\n\tarr.push(elements);\n}\narr.sort((a,b)=>{\n\treturn a[0] - b[0]\n})\nvar enDay = Math.min(arr[0][0], arr[0][1])\nvar interim;\nfor (var k = 1; k= enDay){\n\t\tenDay = interim;\n\t}\n\telse{\n\t\tenDay = (interim == arr[k][0]) ? arr[k][1] : arr[k][0];\n\t}\n}\nprint(enDay)"}, {"source_code": "var arr = [], elements = []\nvar queries = parseInt(readline())\nfor (var l = 0; l < queries;l++){\n\treadline().split(' ').map((val)=>{\n\t\telements.push(parseInt(val));\n\t})\n\tarr.push(elements);\n\telements.pop();\n\telements.pop()\n}\narr.sort((a,b)=>{\n\treturn a[0] - b[0]\n})\nvar enDay = Math.min(arr[0][0], arr[0][1])\nvar interim;\nfor (var k = 1; k= enDay){\n\t\tenDay = interim;\n\t}\n\telse{\n\t\tenDay = (interim == arr[k][0]) ? arr[k][1] : arr[k][0];\n\t}\n}\nprint(enDay)"}, {"source_code": "var arr = [], elements;\nvar queries = parseInt(readline())\nfor (var l = 0; l < queries;l++){\n\telements = readline().split(' ').map((val)=>{\n\t\treturn parseInt(val);\n\t})\n\tarr.push(elements);\n}\narr.sort((a,b)=>{\n\treturn a[0] - b[0]\n})\nvar enDay = Math.min(arr[0][0], arr[0][1])\nvar interim;\nfor (var k = 1; k= enDay){\n\t\tenDay = interim;\n\t}\n\telse{\n\t\tenDay = (interim == arr[k][0]) ? arr[k][1] : arr[k][0];\n\t}\n}\nprint(enDay)"}, {"source_code": "var n = +readline();\nvar arr=[];\nfor(var i=0;i+v));\nfor(var i=0;i{\n if(a[0]===b[0])\n return a[1]-b[1];\n return a[0]-b[0];\n});\n\nvar ans=0;\nvar prev=0;\nfor(var i=0;i+v));\nprint(arr);\narr.sort((a,b)=>{\n if(a[0]===b[0])\n return a[1]-b[1];\n return a[0]-b[0];\n});\n\nvar ans=0;\nvar prev=0;\nfor(var i=0;i+v));\narr.sort((a,b)=>{\n if(a[0]===b[0])\n return a[1]-b[1];\n return a[0]-b[0];\n});\n\nfor(var i=0;i+v));\narr.sort((a,b)=>{\n if(a[0]===b[0])\n return a[1]-b[1];\n return a[0]-b[0];\n});\n\nvar ans=0;\nvar prev=0;\nfor(var i=0;i {\n if (chainNumberList === 1) return 0\n\n let currentCycleLength = 0\n let maxCycleLength = 0\n\n for (let index = 1; index < chainNumberList; index++) {\n const a = aList[index]\n const b = bList[index]\n\n if (index === 1) {\n currentCycleLength = Math.abs(a - b)\n } else {\n const baseLength = Math.abs(a - b)\n const partLength = cList[index - 1] - 1 - baseLength\n if (baseLength > partLength + currentCycleLength) {\n currentCycleLength = baseLength\n } else {\n currentCycleLength += partLength\n }\n }\n\n if (a === b) {\n currentCycleLength = 0\n }\n\n currentCycleLength += 2\n\n if (maxCycleLength < cList[index] + currentCycleLength) {\n maxCycleLength = cList[index] - 1 + currentCycleLength\n }\n }\n\n currentCycleLength += cList[cList.length - 1] - 1\n\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n }\n\n return maxCycleLength\n}\n\nlet index = -1\nlet maxRound = 0\nlet round = 0\n\nlet cList, aList, bList, chainNumberList\nlet answer = []\n\nreadline.on('line', line => {\n if (index === -1) {\n maxRound = Number(line)\n index = 0\n } else {\n const mode = index % 4\n if (mode === 0) {\n chainNumberList = Number(line)\n } else if (mode === 1) {\n cList = line.split(' ').map(val => Number(val))\n } else if (mode === 2) {\n aList = line.split(' ').map(val => Number(val))\n } else if (mode === 3) {\n bList = line.split(' ').map(val => Number(val))\n answer.push(calculate(chainNumberList, cList, aList, bList))\n round++\n if (round === maxRound) {\n readline.close()\n console.log(answer.join('\\n'))\n return\n }\n }\n index++\n }\n})\n\n// chainNumberList, cList, aList, bList\n// console.log(calculate(4, [3, 4, 3, 3], [-1, 1, 2, 2], [-1, 2, 2, 3]))\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9+5;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst c = rna();\r\n\t\tconst a = rna();\r\n\t\tconst b = rna();\r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 1, cur = -INF; i < n; i++) {\r\n\t\t\tif (a[i] == b[i]) {\r\n\t\t\t\tcur = 0;\r\n\t\t\t} else {\r\n\t\t\t\tcur += c[i-1] - 1 - Math.abs(a[i] - b[i]);\r\n\t\t\t\tcur = Math.max(cur, Math.abs(a[i] - b[i]));\r\n\t\t\t}\r\n\t\t\tcur += 2;\r\n\t\t\tans = Math.max(ans, cur + c[i] - 1);\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst c = rna();\r\n\t\tconst a = rna();\r\n\t\tconst b = rna();\r\n\r\n\t\tlet ans = 0;\r\n\t\tlet cur = Math.abs(a[1] - b[1]);\r\n\t\tfor (let i = 1; i < n; i++) {\r\n\t\t\tcur += 2;\r\n\t\t\tans = Math.max(ans, cur + c[i] - 1);\r\n\t\t\tif (a[i+1] == b[i+1]) {\r\n\t\t\t\tcur = 0;\r\n\t\t\t} else {\r\n\t\t\t\tcur += Math.min(a[i+1], b[i+1]) - 1\r\n\t\t\t\tcur += c[i] - Math.max(a[i+1], b[i+1]);\r\n\t\t\t\tcur = Math.max(cur, Math.abs(a[i+1] - b[i+1]));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, iii) => {\r\n var n = parseInt(readline())\r\n var map = {}\r\n var c = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var b = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n var currentLength = 0\r\n var len = 0\r\n var max = 0\r\n for (let i = 1; i < n; i++) {\r\n currentLength = 1+c[i]+Math.abs(a[i]-b[i])\r\n if (a[i] !== b[i]) {\r\n currentLength = Math.max(currentLength, len + c[i]-Math.abs(a[i]-b[i])+1)\r\n }\r\n max = Math.max(max, currentLength)\r\n len = currentLength\r\n // console.log(currentLength, a[i], b[i], c[i - 1])\r\n }\r\n console.log(max)\r\n })\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n})\n\nconst calculate = (chainNumberList, cList, aList, bList) => {\n if (chainNumberList === 1) return 0\n\n let maxCycleLength = 0\n let currentCycleLength = 0\n for (let index = 1; index < chainNumberList; index++) {\n const a = aList[index]\n const b = bList[index]\n const cOld = cList[index - 1]\n\n if (index === 1) {\n currentCycleLength += Math.abs(b - a)\n } else {\n currentCycleLength += cOld - 1 - Math.abs(b - a)\n }\n\n if (a === b) {\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n currentCycleLength = 0\n }\n } else {\n const newCurrentCycleLength = currentCycleLength + cOld - 1\n if (maxCycleLength < newCurrentCycleLength) {\n maxCycleLength = newCurrentCycleLength\n }\n }\n currentCycleLength += 2\n }\n\n currentCycleLength += cList[cList.length - 1] - 1\n\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n }\n\n return maxCycleLength\n}\n\nlet index = -1\nlet maxRound = 0\nlet round = 0\n\nlet cList, aList, bList, chainNumberList\nlet answer = []\n\nreadline.on('line', line => {\n if (index === -1) {\n maxRound = Number(line)\n index = 0\n } else {\n const mode = index % 4\n if (mode === 0) {\n chainNumberList = Number(line)\n } else if (mode === 1) {\n cList = line.split(' ').map(val => Number(val))\n } else if (mode === 2) {\n aList = line.split(' ').map(val => Number(val))\n } else if (mode === 3) {\n bList = line.split(' ').map(val => Number(val))\n answer.push(calculate(chainNumberList, cList, aList, bList))\n round++\n if (round === maxRound) {\n readline.close()\n console.log(answer.join('\\n'))\n return\n }\n }\n index++\n }\n})\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n})\n\nconst calculate = (chainNumberList, cList, aList, bList) => {\n let maxCycleLength = 0\n let currentCycleLength = 0\n for (let index = 1; index < chainNumberList; index++) {\n const a = aList[index]\n const b = bList[index]\n const cOld = cList[index - 1]\n\n if (index === 1) {\n currentCycleLength += Math.abs(b - a)\n } else {\n currentCycleLength += cOld - 1 - Math.abs(b - a)\n }\n\n if (a === b) {\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n currentCycleLength = 0\n }\n } else {\n const newCurrentCycleLength = currentCycleLength + cOld - 1\n if (maxCycleLength < newCurrentCycleLength) {\n maxCycleLength = newCurrentCycleLength\n }\n }\n currentCycleLength += 2\n }\n\n currentCycleLength += cList[cList.length - 1] - 1\n\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n }\n\n return maxCycleLength\n}\n\nlet index = -1\nlet maxRound = 0\nlet round = 0\n\nlet cList, aList, bList, chainNumberList\nlet answer = []\n\nreadline.on('line', line => {\n if (index === -1) {\n maxRound = Number(line)\n index = 0\n } else {\n const mode = index % 4\n if (mode === 0) {\n chainNumberList = Number(line)\n } else if (mode === 1) {\n cList = line.split(' ').map(val => Number(val))\n } else if (mode === 2) {\n aList = line.split(' ').map(val => Number(val))\n } else if (mode === 3) {\n bList = line.split(' ').map(val => Number(val))\n answer.push(calculate(chainNumberList, cList, aList, bList))\n round++\n if (round === maxRound) {\n readline.close()\n console.log(answer.join('\\n'))\n return\n }\n }\n index++\n }\n})\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n})\n\nconst calculate = (chainNumberList, cList, aList, bList) => {\n let maxCycleLength = 0\n let currentCycleLength = 0\n for (let index = 1; index < chainNumberList; index++) {\n const a = aList[index]\n const b = bList[index]\n const cOld = cList[index - 1]\n\n if (index === 1) {\n currentCycleLength += Math.abs(b - a)\n } else {\n currentCycleLength += cOld - 1 - Math.abs(b - a)\n }\n\n if (a === b) {\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n currentCycleLength = 0\n }\n }\n currentCycleLength += 2\n }\n\n currentCycleLength += cList[cList.length - 1] - 1\n\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n }\n\n return maxCycleLength\n}\n\nlet index = -1\nlet maxRound = 0\nlet round = 0\n\nlet cList, aList, bList, chainNumberList\nlet answer = []\n\nreadline.on('line', line => {\n if (index === -1) {\n maxRound = Number(line)\n index = 0\n } else {\n const mode = index % 4\n if (mode === 0) {\n chainNumberList = Number(line)\n } else if (mode === 1) {\n cList = line.split(' ').map(val => Number(val))\n } else if (mode === 2) {\n aList = line.split(' ').map(val => Number(val))\n } else if (mode === 3) {\n bList = line.split(' ').map(val => Number(val))\n answer.push(calculate(chainNumberList, cList, aList, bList))\n round++\n if (round === maxRound) {\n readline.close()\n console.log(answer.join('\\n'))\n return\n }\n }\n index++\n }\n})\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n})\n\nconst calculate = (chainNumberList, cList, aList, bList) => {\n let maxCycleLength = 0\n let currentCycleLength = 0\n for (let index = 1; index < chainNumberList; index++) {\n const a = aList[index]\n const b = bList[index]\n const cOld = cList[index - 1]\n\n if (index === 1) {\n currentCycleLength += Math.abs(b - a)\n } else {\n currentCycleLength += cOld - 1 - Math.abs(b - a)\n }\n\n if (a === b) {\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n currentCycleLength = 0\n }\n }\n currentCycleLength += 2\n }\n\n currentCycleLength += cList[cList.length - 1] - 1\n\n if (maxCycleLength < currentCycleLength) {\n maxCycleLength = currentCycleLength\n }\n\n return maxCycleLength\n}\n\nlet index = -1\nlet maxRound = 0\nlet round = 0\n\nlet cList, aList, bList, chainNumberList\n\nreadline.on('line', line => {\n if (index === -1) {\n maxRound = Number(line)\n index = 0\n } else {\n const mode = index % 4\n if (mode === 0) {\n chainNumberList = Number(line)\n } else if (mode === 1) {\n cList = line.split(' ').map(val => Number(val))\n } else if (mode === 2) {\n aList = line.split(' ').map(val => Number(val))\n } else if (mode === 3) {\n bList = line.split(' ').map(val => Number(val))\n console.log(calculate(chainNumberList, cList, aList, bList))\n round++\n if (round === maxRound) {\n readline.close()\n return\n }\n }\n index++\n }\n})\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst c = rna();\r\n\t\tconst a = rna();\r\n\t\tconst b = rna();\r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 1, cur = 0; i < n; i++) {\r\n\t\t\tif (a[i] == b[i]) {\r\n\t\t\t\tcur = 0;\r\n\t\t\t} else {\r\n\t\t\t\tcur += c[i-1] - 1 - Math.abs(a[i] - b[i]);\r\n\t\t\t\tcur = Math.max(cur, Math.abs(a[i] - b[i]));\r\n\t\t\t}\r\n\t\t\tcur += 2;\r\n\t\t\tans = Math.max(ans, cur + c[i] - 1);\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst c = rna();\r\n\t\tconst a = rna();\r\n\t\tconst b = rna();\r\n\r\n\t\tlet ans = 0;\r\n\t\tlet cur = Math.abs(a[1] - b[1]);\r\n\t\tfor (let i = 1; i < n; i++) {\r\n\t\t\tcur += 2;\r\n\t\t\tans = Math.max(ans, cur + c[i] - 1);\r\n\t\t\tif (a[i+1] == b[i+1]) {\r\n\t\t\t\tcur = 0;\r\n\t\t\t} else {\r\n\t\t\t\tcur += Math.min(a[i+1], b[i+1]) - 1\r\n\t\t\t\tcur += c[i] - Math.max(a[i+1], b[i+1]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "3d898a45ab89b93e006270a77db49017"} {"nl": {"description": "You are given a multiset $$$S$$$ initially consisting of $$$n$$$ distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.You will perform the following operation $$$k$$$ times: Add the element $$$\\lceil\\frac{a+b}{2}\\rceil$$$ (rounded up) into $$$S$$$, where $$$a = \\operatorname{mex}(S)$$$ and $$$b = \\max(S)$$$. If this number is already in the set, it is added again. Here $$$\\operatorname{max}$$$ of a multiset denotes the maximum integer in the multiset, and $$$\\operatorname{mex}$$$ of a multiset denotes the smallest non-negative integer that is not present in the multiset. For example: $$$\\operatorname{mex}(\\{1,4,0,2\\})=3$$$; $$$\\operatorname{mex}(\\{2,5,1\\})=0$$$. Your task is to calculate the number of distinct elements in $$$S$$$ after $$$k$$$ operations will be done.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1\\le n\\le 10^5$$$, $$$0\\le k\\le 10^9$$$) — the initial size of the multiset $$$S$$$ and how many operations you need to perform. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\\dots,a_n$$$ ($$$0\\le a_i\\le 10^9$$$) — the numbers in the initial multiset. 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 number of distinct elements in $$$S$$$ after $$$k$$$ operations will be done.", "sample_inputs": ["5\n4 1\n0 1 3 4\n3 1\n0 1 4\n3 0\n0 1 4\n3 2\n0 1 2\n3 2\n1 2 3"], "sample_outputs": ["4\n4\n3\n5\n3"], "notes": "NoteIn the first test case, $$$S=\\{0,1,3,4\\}$$$, $$$a=\\operatorname{mex}(S)=2$$$, $$$b=\\max(S)=4$$$, $$$\\lceil\\frac{a+b}{2}\\rceil=3$$$. So $$$3$$$ is added into $$$S$$$, and $$$S$$$ becomes $$$\\{0,1,3,3,4\\}$$$. The answer is $$$4$$$.In the second test case, $$$S=\\{0,1,4\\}$$$, $$$a=\\operatorname{mex}(S)=2$$$, $$$b=\\max(S)=4$$$, $$$\\lceil\\frac{a+b}{2}\\rceil=3$$$. So $$$3$$$ is added into $$$S$$$, and $$$S$$$ becomes $$$\\{0,1,3,4\\}$$$. The answer is $$$4$$$."}, "positive_code": [{"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n, k, a) => {\r\n if (k == 0) return pr(n);\r\n a.sort((x, y) => x - y);\r\n let max = a[n - 1];\r\n let mex = n;\r\n for (let i = 0; i < n; i++) {\r\n if (i != a[i]) {\r\n mex = i;\r\n break;\r\n }\r\n }\r\n if (mex > max) return pr(n + k);\r\n let add = mex + max + 1 >> 1;\r\n for (let i = 0; i < n; i++) {\r\n if (add == a[i]) {\r\n return pr(n);\r\n }\r\n }\r\n pr(n + 1);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i][0], input[i][1], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n arr.sort((a, b) => a - b);\r\n let mex = Infinity;\r\n if (arr[0] !== 0) mex = 0;\r\n for (let i = 1; i < n; i++) {\r\n if (arr[i - 1] + 1 !== arr[i]) {\r\n mex = Math.min(mex, arr[i - 1] + 1);\r\n break;\r\n }\r\n }\r\n if (mex === Infinity) {\r\n console.log(k + n);\r\n continue;\r\n }\r\n let obj = {};\r\n for (let i = 0; i < n; i++) obj[arr[i]] = 1;\r\n let i = 0,\r\n max = arr[n - 1];\r\n while (i < k) {\r\n let j = Math.ceil((mex + max) / 2);\r\n if (obj[j]) break;\r\n else {\r\n arr.push(j);\r\n obj[j] = 1;\r\n if (mex === j) {\r\n while (obj[j]) j++;\r\n mex = j;\r\n }\r\n max = Math.max(j, max);\r\n }\r\n i++;\r\n }\r\n console.log(Object.keys(obj).length);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\nfunction solve([n, k], set) {\r\n set.sort((a, b) => a - b)\r\n let min = Number.MAX_SAFE_INTEGER, prv = -1\r\n for (let i of set) {\r\n if (i - 1 != prv) {\r\n min = prv + 1\r\n break\r\n }\r\n prv = i\r\n }\r\n let max = set[n - 1];\r\n let a = Math.ceil((min + max) / 2)\r\n let flag = true\r\n for (let i of set) {\r\n if (i == a) flag = false\r\n }\r\n if (k == 0) flag = false\r\n if (min + 1 <= max) return n + Number(flag)\r\n else return n + k\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) console.log(solve(inputArr[i], inputArr[i + 1]))\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n var [n, k] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var exist = false\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] >= n) exist = true\r\n }\r\n if (!exist) return console.log(n + k)\r\n if (k === 0) return console.log(n)\r\n\r\n var mex = 0\r\n var max = 0\r\n for (let i = 0; i <= n; i++) {\r\n if (a[i] > max) max = a[i]\r\n }\r\n for (let i = 0; i <= n; i++) {\r\n if (!a.includes(i)) {\r\n mex = i\r\n break\r\n }\r\n }\r\n if (!a.includes(Math.ceil((mex + max) / 2))) return console.log(n + 1)\r\n console.log(n)\r\n // console.log(exist ? n : n + k)\r\n })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n"}, {"source_code": "function getInt(num){\r\n return parseInt(num, 10)\r\n }\r\n \r\nvar t = parseInt(readline(), 10);\r\nvar lines= [];\r\nfor(var i = 0; i= 1){\r\n var newItem = Math.ceil((max+mex)/2);\r\n addition = sorted.some( function(item){\r\n return item === newItem;\r\n }) ? 0 : 1;\r\n \r\n }\r\n print(n + addition);\r\n}\r\n\r\nfunction getMex(arr,max){\r\n var res = 0;\r\n \r\n arr.forEach(function(item){\r\n if(res === item){\r\n res = item +1;\r\n }\r\n } )\r\n return res\r\n}\r\n"}], "negative_code": [{"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n, k, a) => {\r\n if (k == 0) return pr(n);\r\n let max = Math.max.apply(Math, a);\r\n let mex = n;\r\n for (let i = 0; i < n; i++) {\r\n if (i != a[i]) {\r\n mex = i;\r\n break;\r\n }\r\n }\r\n if (mex > max) return pr(n + k);\r\n let add = mex + max + 1 >> 1;\r\n for (let i = 0; i < n; i++) {\r\n if (add == a[i]) {\r\n return pr(n);\r\n }\r\n }\r\n pr(n + 1);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i][0], input[i][1], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n arr.sort((a, b) => a - b);\r\n let mex = Infinity;\r\n if (arr[0] === 0) mex = 0;\r\n for (let i = 1; i < n; i++) {\r\n if (arr[i - 1] + 1 !== arr[i]) {\r\n mex = Math.min(mex, arr[i - 1] + 1);\r\n break;\r\n }\r\n }\r\n if (mex === Infinity) mex = arr[n - 1] + 1;\r\n let obj = {};\r\n for (let i = 0; i < n; i++) obj[arr[i]] = 1;\r\n let i = 0,\r\n max = arr[n - 1];\r\n while (i < k) {\r\n let j = Math.ceil((mex + max) / 2);\r\n if (obj[j]) break;\r\n else {\r\n arr.push(j);\r\n obj[j] = 1;\r\n if (mex === j) {\r\n while (obj[j]) j++;\r\n mex = j;\r\n }\r\n max = Math.max(j, max);\r\n }\r\n i++;\r\n }\r\n let l = {},\r\n cnt = 0;\r\n for (let i = 0; i < arr.length; i++) {\r\n if (!l[arr[i]]) cnt++;\r\n else l[arr[i]] = 1;\r\n }\r\n console.log(cnt);\r\n }\r\n};\r\nsolve();\r\n"}], "src_uid": "c0d23fe28ebddbfc960674e3b10122ad"} {"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 ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get.", "input_spec": "The first line contains a non-empty sequence of n (1 ≤ n ≤ 1000) 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 ≤ m ≤ 1000) 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 — he doesn't have a sheet of color z."}, "positive_code": [{"source_code": "print(function(a, b) {\n\tvar c = new Int32Array(256);\n\tvar has = new Int8Array(256);\n\n\tfor (var i = 0; i < a.length; i++)\n\t\tc[a.charCodeAt(i)]++;\n\n\tfor (var i = 0; i < 256; i++)\n\t\tif (c[i] > 0) has[i] = 1;\n\n\tvar ans = 0;\n\tfor (var i = 0; i < b.length; i++) {\n\t\tvar clr = b.charCodeAt(i);\n\t\tif (has[clr] === 0) return -1;\n\t\tif (c[clr] > 0) {\n\t\t\tc[clr]--;\n\t\t\tans++;\n\t\t}\n\t}\n\treturn ans;\n}(readline(), readline()));"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tfunction string2hash(s) {\n\t\tvar h = { nonzero: [] },\n\t\t\talpha = 'abcdefghijklmnopqrstuvwxyz';\n\t\tfor (var i = 0; i < 26; ++i) {\n\t\t\th[alpha.charAt(i)] = 0;\n\t\t}\n\t\tfor (var i = 0; i < s.length; ++i) {\n\t\t\tvar ch = s.charAt(i);\n\t\t\tif (h[ch] == 0) {\n\t\t\t\th.nonzero.push(ch);\n\t\t\t}\n\t\t\th[ch] += 1;\n\t\t}\n\t\treturn h;\n\t}\n\tvar source = string2hash(readline()),\n\t\ttarget = string2hash(readline()),\n\t\tcount = 0;\n\tfor (var i = 0; i < target.nonzero.length; ++i) {\n\t\tvar ch = target.nonzero[i];\n\t\tif (source[ch] == 0) {\n\t\t\tprint(-1);\n\t\t\treturn;\n\t\t}\n\t\tcount += Math.min(source[ch], target[ch]);\n\t}\n\tprint(count);\n}\n\nmain();\n"}], "negative_code": [{"source_code": "print(function(a, b) {\n\tvar c = new Int32Array(1000);\n\tfor (var i = 0; i < a.length; i++)\n\t\tc[a.charCodeAt(i)]++;\n\n\tvar ans = 0;\n\tfor (var i = 0; i < b.length; i++)\n\t\tif (c[b.charCodeAt(i)] > 0) {\n\t\t\tc[b.charCodeAt(i)]--;\n\t\t\tans++;\n\t\t}\n\n\treturn ans == 0 ? -1 : ans;\n}(readline(), readline()));"}, {"source_code": "print(function(a, b) {\n\tvar c = new Int8Array(255);\n\tfor (var i = 0; i < a.length; i++)\n\t\tc[a.charCodeAt(i)]++;\n\n\tvar ans = 0;\n\tfor (var i = 0; i < b.length; i++)\n\t\tif (c[b.charCodeAt(i)] > 0) {\n\t\t\tc[b.charCodeAt(i)]--;\n\t\t\tans++;\n\t\t}\n\n\treturn ans == 0 ? -1 : ans;\n}(readline(), readline()));"}, {"source_code": "print(function(a, b) {\n\tvar c = new Int32Array(255);\n\tfor (var i = 0; i < a.length; i++)\n\t\tc[a.charCodeAt(i)]++;\n\n\tvar ans = 0;\n\tfor (var i = 0; i < b.length; i++)\n\t\tif (c[b.charCodeAt(i)] > 0) {\n\t\t\tc[b.charCodeAt(i)]--;\n\t\t\tans++;\n\t\t}\n\n\treturn ans == 0 ? -1 : ans;\n}(readline(), readline()));"}], "src_uid": "b1e09df7c47dbd04992e64826337c28a"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$, which is sorted in non-descending order. You decided to perform the following steps to create array $$$b_1, b_2, \\dots, b_n$$$: Create an array $$$d$$$ consisting of $$$n$$$ arbitrary non-negative integers. Set $$$b_i = a_i + d_i$$$ for each $$$b_i$$$. Sort the array $$$b$$$ in non-descending order. You are given the resulting array $$$b$$$. For each index $$$i$$$, calculate what is the minimum and maximum possible value of $$$d_i$$$ you can choose in order to get the given array $$$b$$$.Note that the minimum (maximum) $$$d_i$$$-s are independent of each other, i. e. they can be obtained from different possible arrays $$$d$$$.", "input_spec": "The first line contains the single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the length of arrays $$$a$$$, $$$b$$$ and $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$; $$$a_i \\le a_{i+1}$$$) — the array $$$a$$$ in non-descending order. The third line contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 10^9$$$; $$$b_i \\le b_{i+1}$$$) — the array $$$b$$$ in non-descending order. Additional constraints on the input: there is at least one way to obtain the array $$$b$$$ from the $$$a$$$ by choosing an array $$$d$$$ consisting of non-negative integers; the sum of $$$n$$$ doesn't exceed $$$2 \\cdot 10^5$$$. ", "output_spec": "For each test case, print two lines. In the first line, print $$$n$$$ integers $$$d_1^{min}, d_2^{min}, \\dots, d_n^{min}$$$, where $$$d_i^{min}$$$ is the minimum possible value you can add to $$$a_i$$$. Secondly, print $$$n$$$ integers $$$d_1^{max}, d_2^{max}, \\dots, d_n^{max}$$$, where $$$d_i^{max}$$$ is the maximum possible value you can add to $$$a_i$$$. All $$$d_i^{min}$$$ and $$$d_i^{max}$$$ values are independent of each other. In other words, for each $$$i$$$, $$$d_i^{min}$$$ is just the minimum value among all possible values of $$$d_i$$$.", "sample_inputs": ["4\n\n3\n\n2 3 5\n\n7 11 13\n\n1\n\n1000\n\n5000\n\n4\n\n1 2 3 4\n\n1 2 3 4\n\n4\n\n10 20 30 40\n\n22 33 33 55"], "sample_outputs": ["5 4 2\n11 10 8\n4000\n4000\n0 0 0 0\n0 0 0 0\n12 2 3 15\n23 13 3 15"], "notes": "NoteIn the first test case, in order to get $$$d_1^{min} = 5$$$, we can choose, for example, $$$d = [5, 10, 6]$$$. Then $$$b$$$ $$$=$$$ $$$[2+5,3+10,5+6]$$$ $$$=$$$ $$$[7,13,11]$$$ $$$=$$$ $$$[7,11,13]$$$.For $$$d_2^{min} = 4$$$, we can choose $$$d$$$ $$$=$$$ $$$[9, 4, 8]$$$. Then $$$b$$$ $$$=$$$ $$$[2+9,3+4,5+8]$$$ $$$=$$$ $$$[11,7,13]$$$ $$$=$$$ $$$[7,11,13]$$$."}, "positive_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\n// Finds index where x should be\r\nfunction lowerBound(x, a) {\r\n let iMin = 0;\r\n let iMax = a.length - 1;\r\n // 1 2 3 4 (1) => 0\r\n // 1 2 3 4 (2) => 1\r\n // 1 2 3 4 (3) => 2\r\n // 1 2 3 4 (4) => 3\r\n // 1 2 3 4 (5) => 3\r\n while (iMax - iMin > 0) {\r\n const iMiddle = Math.floor((iMax + iMin) / 2);\r\n\r\n if (a[iMiddle] >= x) {\r\n iMax = iMiddle;\r\n } else {\r\n // a[iMiddle] < x\r\n iMin = iMiddle + 1;\r\n }\r\n }\r\n \r\n if (x > a[iMin]) {\r\n return Math.min(iMin + 1, a.length - 1);\r\n }\r\n\r\n return iMin;\r\n}\r\n\r\n// console.log('lb test', lowerBound(1, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(2, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(3, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(4, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(5, [1, 2, 3, 4], 0, 3));\r\n\r\nfunction pickMinIndex(x, b) {\r\n for (let j = 0; j < b.length; j++) {\r\n return lowerBound(x, b);\r\n }\r\n}\r\n\r\nfunction pickMaxIndex(i, a, b) {\r\n for (let j = i; j < b.length - 1; j++) {\r\n if (a[j + 1] > b[j]) {\r\n return j;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\n// indecies of elements which cannot be moved by -1\r\nfunction createArrayOfBoulders(a, b) {\r\n const boulders = [];\r\n\r\n for (let i = 1; i < a.length; i++) {\r\n if (a[i] > b[i - 1]) {\r\n boulders.push(i);\r\n }\r\n }\r\n\r\n return boulders;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n }\r\n\r\n const boulders = createArrayOfBoulders(a, b);\r\n // console.log(boulders);\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n if (boulders.length > 0) {\r\n let bi = lowerBound(i, boulders);\r\n let j = boulders[bi];\r\n\r\n if (j < i) {\r\n j = b.length - 1;\r\n } else if (j === i) {\r\n if (bi === boulders.length - 1) {\r\n j = b.length - 1;\r\n } else {\r\n j = boulders[bi + 1] - 1;\r\n }\r\n } else if (j > i) {\r\n j = j - 1;\r\n }\r\n\r\n max.push(b[j] - a[i]);\r\n // const j = pickMaxIndex(i, a, b);\r\n // max.push(b[j] - a[i]);\r\n } else {\r\n max.push(b[b.length - 1] - a[i]);\r\n }\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const sa = lines[l++].trim().split(' ').map(Number)\n const sb = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, sa, sb)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, sa, sb) {\n const min = sa.map((x, i) => {\n const j = binarySearch(0, n - 1, p => sb[p] < x) + 1\n return sb[j] - x\n })\n const bar = [0]\n for (let i = 1; i < n; i++) {\n if (sb[i - 1] < sa[i]) {\n bar.push(i)\n }\n }\n bar.push(n)\n // console.log('bar', bar)\n const max = sa.map((x, i) => {\n const j = binarySearch(0, bar.length - 1, p => bar[p] <= i) + 1\n return sb[bar[j] - 1] - x\n })\n return min.join(' ') + '\\n' + max.join(' ')\n}\nfunction binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}\n"}], "negative_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\n// Finds index where x should be\r\nfunction lowerBound(x, a) {\r\n let iMin = 0;\r\n let iMax = a.length - 1;\r\n // 1 2 3 4 (1) => 0\r\n // 1 2 3 4 (2) => 1\r\n // 1 2 3 4 (3) => 2\r\n // 1 2 3 4 (4) => 3\r\n // 1 2 3 4 (5) => 3\r\n while (iMax - iMin > 0) {\r\n const iMiddle = Math.floor((iMax + iMin) / 2);\r\n\r\n if (a[iMiddle] >= x) {\r\n iMax = iMiddle;\r\n } else {\r\n // a[iMiddle] < x\r\n iMin = iMiddle + 1;\r\n }\r\n }\r\n \r\n if (x > a[iMin]) {\r\n return Math.min(iMin + 1, a.length - 1);\r\n }\r\n\r\n return iMin;\r\n}\r\n\r\n// console.log('lb test', lowerBound(1, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(2, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(3, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(4, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(5, [1, 2, 3, 4], 0, 3));\r\n\r\nfunction pickMinIndex(x, b) {\r\n for (let j = 0; j < b.length; j++) {\r\n return lowerBound(x, b);\r\n }\r\n}\r\n\r\nfunction pickMaxIndex(i, a, b) {\r\n for (let j = i; j < b.length - 1; j++) {\r\n if (a[j + 1] > b[j]) {\r\n return j;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\n// indecies of elements which cannot be moved by -1\r\nfunction createArrayOfBoulders(a, b) {\r\n const boulders = [];\r\n\r\n for (let i = 1; i < a.length; i++) {\r\n if (a[i] > b[i - 1]) {\r\n boulders.push(i);\r\n }\r\n }\r\n\r\n return boulders;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n }\r\n\r\n const boulders = createArrayOfBoulders(a, b);\r\n // console.log(boulders);\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n if (boulders.length > 0) {\r\n let bi = lowerBound(i, boulders);\r\n let j = boulders[bi];\r\n\r\n if (j === i) {\r\n if (bi === boulders.length - 1) {\r\n j = b.length - 1;\r\n } else {\r\n j = boulders[bi + 1];\r\n }\r\n }\r\n\r\n if (j > i) {\r\n j--;\r\n }\r\n\r\n max.push(b[j] - a[i]);\r\n // const j = pickMaxIndex(i, a, b);\r\n // max.push(b[j] - a[i]);\r\n } else {\r\n max.push(b[b.length - 1] - a[i]);\r\n }\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\n// Finds index where x should be\r\nfunction lowerBound(x, a) {\r\n let iMin = 0;\r\n let iMax = a.length - 1;\r\n // 1 2 3 4 (1) => 0\r\n // 1 2 3 4 (2) => 1\r\n // 1 2 3 4 (3) => 2\r\n // 1 2 3 4 (4) => 3\r\n // 1 2 3 4 (5) => 3\r\n while (iMax - iMin > 0) {\r\n const iMiddle = Math.floor((iMax + iMin) / 2);\r\n\r\n if (a[iMiddle] >= x) {\r\n iMax = iMiddle;\r\n } else {\r\n // a[iMiddle] < x\r\n iMin = iMiddle + 1;\r\n }\r\n }\r\n \r\n if (x > a[iMin]) {\r\n return Math.min(iMin + 1, a.length - 1);\r\n }\r\n\r\n return iMin;\r\n}\r\n\r\n// console.log('lb test', lowerBound(1, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(2, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(3, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(4, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(5, [1, 2, 3, 4], 0, 3));\r\n\r\nfunction pickMinIndex(x, b) {\r\n for (let j = 0; j < b.length; j++) {\r\n return lowerBound(x, b);\r\n }\r\n}\r\n\r\nfunction pickMaxIndex(i, a, b) {\r\n for (let j = i; j < b.length - 1; j++) {\r\n if (a[j + 1] > b[j]) {\r\n return j;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\n// indecies of elements which cannot be moved by -1\r\nfunction createArrayOfBoulders(a, b) {\r\n const boulders = [];\r\n\r\n for (let i = 1; i < a.length; i++) {\r\n if (a[i] > b[i - 1]) {\r\n boulders.push(i);\r\n }\r\n }\r\n\r\n return boulders;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n }\r\n\r\n const boulders = createArrayOfBoulders(a, b);\r\n // console.log(boulders);\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n if (boulders.length > 0) {\r\n let bi = lowerBound(i, boulders);\r\n let j = boulders[bi];\r\n if (j > i) {\r\n j--;\r\n } else if (j === i) {\r\n // last boulder\r\n if (bi === boulders.length - 1) {\r\n j = b.length - 1;\r\n } else {\r\n j = boulders[bi + 1] - 1;\r\n }\r\n }\r\n max.push(b[j] - a[i]);\r\n } else {\r\n max.push(b[b.length - 1] - a[i]);\r\n }\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\n// Finds index where x should be\r\nfunction lowerBound(x, a) {\r\n let iMin = 0;\r\n let iMax = a.length - 1;\r\n // 1 2 3 4 (1) => 0\r\n // 1 2 3 4 (2) => 1\r\n // 1 2 3 4 (3) => 2\r\n // 1 2 3 4 (4) => 3\r\n // 1 2 3 4 (5) => 3\r\n while (iMax - iMin > 0) {\r\n const iMiddle = Math.floor((iMax + iMin) / 2);\r\n\r\n if (a[iMiddle] >= x) {\r\n iMax = iMiddle;\r\n } else {\r\n // a[iMiddle] < x\r\n iMin = iMiddle + 1;\r\n }\r\n }\r\n \r\n if (x > a[iMin]) {\r\n return Math.min(iMin + 1, a.length - 1);\r\n }\r\n\r\n return iMin;\r\n}\r\n\r\n// console.log('lb test', lowerBound(1, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(2, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(3, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(4, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(5, [1, 2, 3, 4], 0, 3));\r\n\r\nfunction pickMinIndex(x, b) {\r\n for (let j = 0; j < b.length; j++) {\r\n return lowerBound(x, b);\r\n }\r\n}\r\n\r\nfunction pickMaxIndex(i, a, b) {\r\n for (let j = i; j < b.length - 1; j++) {\r\n if (a[j + 1] > b[j]) {\r\n return j;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\n// indecies of elements which cannot be moved by -1\r\nfunction createArrayOfBoulders(a, b) {\r\n const boulders = [];\r\n\r\n for (let i = 1; i < a.length; i++) {\r\n if (a[i] > b[i - 1]) {\r\n boulders.push(i);\r\n }\r\n }\r\n\r\n return boulders;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n }\r\n\r\n const boulders = createArrayOfBoulders(a, b);\r\n // console.log(boulders);\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n if (boulders.length > 0) {\r\n let bi = boulders[lowerBound(i, boulders)];\r\n if (bi > i) {\r\n bi--;\r\n } else if (bi === i) {\r\n bi = b.length - 1;\r\n }\r\n max.push(b[bi] - a[i]);\r\n } else {\r\n max.push(b[b.length - 1] - a[i]);\r\n }\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\n// Finds index where x should be\r\nfunction lowerBound(x, a) {\r\n let iMin = 0;\r\n let iMax = a.length - 1;\r\n // 1 2 3 4 (1) => 0\r\n // 1 2 3 4 (2) => 1\r\n // 1 2 3 4 (3) => 2\r\n // 1 2 3 4 (4) => 3\r\n // 1 2 3 4 (5) => 3\r\n while (iMax - iMin > 0) {\r\n const iMiddle = Math.floor((iMax + iMin) / 2);\r\n\r\n if (a[iMiddle] >= x) {\r\n iMax = iMiddle;\r\n } else {\r\n // a[iMiddle] < x\r\n iMin = iMiddle + 1;\r\n }\r\n }\r\n \r\n if (x > a[iMin]) {\r\n return Math.min(iMin + 1, a.length - 1);\r\n }\r\n\r\n return iMin;\r\n}\r\n\r\n// console.log('lb test', lowerBound(1, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(2, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(3, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(4, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(5, [1, 2, 3, 4], 0, 3));\r\n\r\nfunction pickMinIndex(x, b) {\r\n for (let j = 0; j < b.length; j++) {\r\n return lowerBound(x, b);\r\n }\r\n}\r\n\r\nfunction pickMaxIndex(i, a, b) {\r\n for (let j = i; j < b.length - 1; j++) {\r\n if (a[j + 1] > b[j]) {\r\n return j;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\n// indecies of elements which cannot be moved by -1\r\nfunction createArrayOfBoulders(a, b) {\r\n const boulders = [];\r\n\r\n for (let i = 1; i < a.length; i++) {\r\n if (a[i] > b[i - 1]) {\r\n boulders.push(i);\r\n }\r\n }\r\n\r\n return boulders;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n }\r\n\r\n const boulders = createArrayOfBoulders(a, b);\r\n // console.log(boulders);\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n if (boulders.length > 0) {\r\n let bi = boulders[lowerBound(i, boulders)];\r\n if (bi > i) {\r\n bi--;\r\n }\r\n max.push(b[bi] - a[i]);\r\n } else {\r\n max.push(b[b.length - 1] - a[i]);\r\n }\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\n// Finds index where x should be\r\nfunction lowerBound(x, a, iMin = 0, iMax = a.length - 1) {\r\n // let iMin = 0;\r\n // let iMax = a.length - 1;\r\n // 1 2 3 4 (1) => 0\r\n // 1 2 3 4 (2) => 1\r\n // 1 2 3 4 (3) => 2\r\n // 1 2 3 4 (4) => 3\r\n // 1 2 3 4 (5) => 3\r\n while (iMax - iMin > 0) {\r\n const iMiddle = Math.floor((iMax + iMin) / 2);\r\n\r\n if (a[iMiddle] >= x) {\r\n iMax = iMiddle;\r\n } else {\r\n // a[iMiddle] < x\r\n iMin = iMiddle + 1;\r\n }\r\n }\r\n \r\n if (x > a[iMin]) {\r\n return Math.min(iMin + 1, a.length - 1);\r\n }\r\n\r\n return iMin;\r\n}\r\n\r\n// console.log('lb test', lowerBound(1, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(2, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(3, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(4, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(5, [1, 2, 3, 4], 0, 3));\r\n\r\nfunction pickMinIndex(x, b) {\r\n for (let j = 0; j < b.length; j++) {\r\n return lowerBound(x, b, 0, j);\r\n }\r\n}\r\n\r\nfunction pickMaxIndex(i, a, b) {\r\n for (let j = i; j < b.length - 1; j++) {\r\n if (a[j + 1] > b[j]) {\r\n return j;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\n// indecies of elements which cannot be moved by -1\r\nfunction createArrayOfBoulders(a, b) {\r\n const boulders = [];\r\n\r\n for (let i = 1; i < a.length; i++) {\r\n if (a[i] > b[i - 1]) {\r\n boulders.push(i);\r\n }\r\n }\r\n\r\n return boulders;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n }\r\n\r\n const boulders = createArrayOfBoulders(a, b);\r\n // console.log(boulders);\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n if (boulders.length > 0) {\r\n let bi = boulders[lowerBound(i, boulders)];\r\n if (bi > i) {\r\n bi--;\r\n }\r\n max.push(b[bi] - a[i]);\r\n } else {\r\n max.push(b[b.length - 1] - a[i]);\r\n }\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\n// Finds index where x should be\r\nfunction lowerBound(x, a) {\r\n let iMin = 0;\r\n let iMax = a.length - 1;\r\n // 1 2 3 4 (1) => 0\r\n // 1 2 3 4 (2) => 1\r\n // 1 2 3 4 (3) => 2\r\n // 1 2 3 4 (4) => 3\r\n // 1 2 3 4 (5) => 3\r\n while (iMax - iMin > 0) {\r\n const iMiddle = Math.floor((iMax + iMin) / 2);\r\n\r\n if (a[iMiddle] >= x) {\r\n iMax = iMiddle;\r\n } else {\r\n // a[iMiddle] < x\r\n iMin = iMiddle + 1;\r\n }\r\n }\r\n \r\n if (x > a[iMin]) {\r\n return Math.min(iMin + 1, a.length - 1);\r\n }\r\n\r\n return iMin;\r\n}\r\n\r\n// console.log('lb test', lowerBound(1, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(2, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(3, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(4, [1, 2, 3, 4], 0, 3));\r\n// console.log('lb test', lowerBound(5, [1, 2, 3, 4], 0, 3));\r\n\r\nfunction pickMinIndex(x, b) {\r\n for (let j = 0; j < b.length; j++) {\r\n return lowerBound(x, b, 0, j);\r\n }\r\n}\r\n\r\nfunction pickMaxIndex(i, a, b) {\r\n for (let j = i; j < b.length - 1; j++) {\r\n if (a[j + 1] > b[j]) {\r\n return j;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\n// indecies of elements which cannot be moved by -1\r\nfunction createArrayOfBoulders(a, b) {\r\n const boulders = [];\r\n\r\n for (let i = 1; i < a.length; i++) {\r\n if (a[i] > b[i - 1]) {\r\n boulders.push(i);\r\n }\r\n }\r\n\r\n return boulders;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n }\r\n\r\n const boulders = createArrayOfBoulders(a, b);\r\n // console.log(boulders);\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n if (boulders.length > 0) {\r\n let bi = boulders[lowerBound(i, boulders)];\r\n if (bi !== i) {\r\n bi--;\r\n }\r\n max.push(b[bi] - a[i]);\r\n } else {\r\n max.push(b[b.length - 1] - a[i]);\r\n }\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\nfunction pickMinIndex(x, b /* a is sorted */, minMap) {\r\n for (let j = 0; j < b.length; j++) {\r\n const num = b[j];\r\n if (\r\n num >= x\r\n ) {\r\n if (b[j + 1] === num && minMap[j + 1] === undefined) {\r\n continue;\r\n }\r\n\r\n return j;\r\n }\r\n }\r\n\r\n throw new Error('Cant find min');\r\n}\r\n\r\nfunction pickMaxIndex(x, xi, b /* a is sorted */, minMap, xMap) {\r\n for (let j = xMap[xi] + 1; j < b.length; j++) {\r\n if (minMap[j] !== undefined) {\r\n return j - 1;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const minMap = {};\r\n const xMap = {};\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b, minMap);\r\n min.push(b[j] - x);\r\n minMap[j] = true;\r\n xMap[i] = j;\r\n }\r\n\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMaxIndex(x, i, b, minMap, xMap);\r\n max.push(b[j] - x);\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\nfunction pickMinIndex(x, a /* a is sorted */) {\r\n for (let i = 0; i < a.length; i++) {\r\n const num = a[i];\r\n if (num >= x && a[i + 1] !== num) {\r\n return i;\r\n }\r\n }\r\n\r\n throw new Error('Cant find min');\r\n}\r\n\r\nfunction pickMaxIndex(x, xi, b /* a is sorted */, minMap, xMap) {\r\n for (let j = xMap[xi] + 1; j < b.length; j++) {\r\n if (minMap[j] !== undefined) {\r\n return j - 1;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const minMap = {};\r\n const xMap = {};\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n minMap[j] = true;\r\n xMap[i] = j;\r\n }\r\n\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMaxIndex(x, i, b, minMap, xMap);\r\n max.push(b[j] - x);\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\nfunction pickMinIndex(x, a /* a is sorted */) {\r\n for (let i = 0; i < a.length; i++) {\r\n const num = a[i];\r\n if (num >= x) {\r\n return i;\r\n }\r\n }\r\n\r\n throw new Error('Cant find min');\r\n}\r\n\r\nfunction pickMaxIndex(x, xi, b /* a is sorted */, minMap, xMap) {\r\n for (let j = xMap[xi] + 1; j < b.length; j++) {\r\n if (minMap[j] !== undefined) {\r\n return j - 1;\r\n }\r\n }\r\n\r\n return b.length - 1;\r\n}\r\n\r\nfunction solve(a, b) {\r\n const minMap = {};\r\n const xMap = {};\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n minMap[j] = true;\r\n xMap[i] = j;\r\n }\r\n\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMaxIndex(x, i, b, minMap, xMap);\r\n max.push(b[j] - x);\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\nfunction pickMinIndex(x, a /* a is sorted */) {\r\n for (let i = 0; i < a.length; i++) {\r\n const num = a[i];\r\n if (num >= x) {\r\n return i;\r\n }\r\n }\r\n\r\n throw new Error('Cant find min');\r\n}\r\n\r\nfunction pickMaxIndex(x, xi, a /* a is sorted */, minMap) {\r\n for (let i = a.length - 1; i >= 0; i--) {\r\n const num = a[i];\r\n if (num < x) {\r\n throw new Error(`Cant find max ${x}`);\r\n }\r\n\r\n if (\r\n minMap[i] === undefined ||\r\n minMap[i] === xi\r\n ) {\r\n return i;\r\n }\r\n }\r\n\r\n throw new Error(`Cant find max ${x}`);\r\n}\r\n\r\nfunction solve(a, b) {\r\n const minMap = {};\r\n const min = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMinIndex(x, b);\r\n min.push(b[j] - x);\r\n minMap[j] = i;\r\n }\r\n\r\n const max = [];\r\n for (let i = 0; i < a.length; i++) {\r\n const x = a[i];\r\n const j = pickMaxIndex(x, i, b, minMap);\r\n max.push(b[j] - x);\r\n }\r\n\r\n console.log(min.join(' '));\r\n console.log(max.join(' '));\r\n}\r\n\r\nprocess.stdin.on('end', function() {\r\n const data = input.trim().split('\\n');\r\n\r\n for (let i = 1; i < data.length; i += 3) {\r\n const a = data[i + 1].split(' ').map(Number);\r\n const b = data[i + 2].split(' ').map(Number);\r\n\r\n solve(a, b);\r\n }\r\n});\r\n"}], "src_uid": "ffc96dc83a6fde2e83e07671a8d8ed41"} {"nl": {"description": "The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out — one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.", "input_spec": "The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100, 2 ≤  n · m) — the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).", "output_spec": "On the first line output integer k — the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2). Then print nm + 1 lines containing 2 numbers each — the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.", "sample_inputs": ["2 2", "3 3"], "sample_outputs": ["0\n1 1\n1 2\n2 2\n2 1\n1 1", "1\n3 3 1 1\n1 1\n1 2\n1 3\n2 3\n2 2\n2 1\n3 1\n3 2\n3 3\n1 1"], "notes": null}, "positive_code": [{"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar moves = [];\nvar needTeleport = false;\nrl.on('line', (input) => {\n let line = input.split(' ').map(item => { return parseInt(item) });\n let n = line[0];\n let m = line[1];\n for (var i = 1; i <= n; i++)\n moves.push([i, 1]);\n\n if (m % 2 == 0 && n > 1) {\n var up = true;\n for (let j = 2; j <= m; j++) {\n if (up) {\n for (let i = n; i > 1; i--)\n moves.push([i, j]);\n up = false;\n } else {\n for (let i = 2; i <= n; i++)\n moves.push([i, j]);\n up = true;\n }\n\n }\n for (let j = m; j >= 1; j--)\n moves.push([1, j]);\n\n }\n else if (n % 2 == 0 && m > 1) {\n var right = true;\n for (let i = n; i > 1; i--) {\n\n if (right) {\n for (let j = 2; j <= m; j++)\n moves.push([i, j]);\n right = false;\n\n } else {\n for (let j = m; j > 1; j--)\n moves.push([i, j]);\n right = true;\n }\n }\n for (let j = m; j >= 1; j--)\n moves.push([1, j]);\n }\n else {\n if (!(n == 1 && m == 2) && !(n == 2 && m == 1))\n needTeleport = true;\n var up = true;\n for (let j = 2; j <= m; j++) {\n\n if (up) {\n for (let i = n; i >= 1; i--)\n moves.push([i, j]);\n up = false;\n } else {\n for (let i = 1; i <= n; i++)\n moves.push([i, j]);\n up = true;\n }\n\n }\n\n\n moves.push([1, 1]);\n }\n if (needTeleport) {\n console.log(1);\n //console.log(n + \" \" + m + \" \" + 1 + \" \" + 1);\n console.log(\"%d %d %d %d\", n, m, 1, 1);\n } else\n console.log(0);\n\n moves.forEach(function (Element) {\n //console.log(element[0] + \" \" + element[1])\n console.log(\"%d %d\", Element[0], Element[1]);\n });\n rl.close();\n\n});"}], "negative_code": [], "src_uid": "a98622d5b6d6d139df90b6fee3baa544"} {"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 ≤ n ≤ 200) — 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 — 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": "var n = parseInt(readline());\nvar s, m=0, a = new Array(), b = new Array(), l = new Array();\nfor(i=0; i=0; j--) {\nl[j] = 2;\nkk = b[j];\nwhile (kk != b[0]) {\nfor (i=0; i m) m = l[j];\n}\nprint(m);"}, {"source_code": "function Stack()\n{\n this.a = [];\n}\n\nStack.prototype.empty = function()\n{\n return this.a.length == 0;\n}\n\nStack.prototype.push = function(v)\n{\n this.a.push(v);\n}\n\nStack.prototype.pop = function()\n{\n if (!this.empty())\n return this.a.pop();\n return undefined;\n}\n\nStack.prototype.top = function()\n{\n if (!this.empty())\n return this.a[this.a.length - 1];\n return undefined; \n}\n\nStack.prototype.clear = function()\n{\n this.a = [];\n}\n\nStack.prototype.size = function()\n{\n return this.a.length;\n}\n\nfunction Queue()\n{\n this.l = new Stack();\n this.r = new Stack();\n}\n\nQueue.prototype.push = function(v)\n{\n this.l.push(v);\n}\n\nQueue.prototype.empty = function()\n{\n return this.r.empty() && this.l.empty();\n}\n\nQueue.prototype.pop = function()\n{\n if (this.r.empty())\n {\n while(!this.l.empty())\n this.r.push(this.l.pop()); \n }\n if (!this.r.empty())\n return this.r.pop();\n return undefined;\n}\n\nQueue.prototype.front = function()\n{\n if (this.r.empty())\n {\n while(!this.l.empty())\n this.r.push(this.l.pop()); \n }\n if (!this.r.empty())\n return this.r.top();\n return undefined; \n}\n\nQueue.prototype.size = function()\n{\n return l.size() + r.size();\n}\n\nQueue.prototype.clear = function()\n{\n l.clear();\n r.clear();\n}\n\nfunction Reader()\n{\n this.b = [];\n this.c = 0;\n}\n\nReader.prototype.next = function()\n{\n if (this.c == this.b.length)\n {\n this.c = 0;\n this.b = readline().split(' ');\n } \n return this.b[this.c++];\n}\n\nfunction Writer()\n{\n this.l = [\"\"];\n this.c = 0;\n}\n\nWriter.prototype.print = function(s)\n{\n this.l[this.c] += s;\n}\n\nWriter.prototype.println = function(s)\n{\n if (s == undefined)\n s = \"\";\n this.l[this.c] += s;\n this.l.push(\"\");\n ++this.c;\n}\n\nWriter.prototype.flush = function()\n{\n print(this.l.join('\\n'));\n this.l = [];\n}\n\nMath.cmp = function(a, b)\n{\n return (+a > +b)-(+a < +b);\n}\n\nfunction Treap(cmp)\n{\n if (typeof cmp == \"undefined\")\n this.cmp = function(a,b){return ((a>b)-(a t.p)\n {\n var tmp = this._split(t, n.k);\n n.l = tmp.l;\n n.r = tmp.r;\n this._update(n);\n return n;\n }\n if (this.cmp(n.k, t.k) <= 0)\n t.l = this._insert(t.l, n);\n else\n t.r = this._insert(t.r, n);\n this._update(t);\n return t;\n}\n\nTreap.prototype.nth = function(n)\n{\n var cur = this._root;\n var lSize = 0;\n while(cur)\n {\n lSize = this._sizeOf(cur.l);\n if (lSize == n)\n return {k: cur.k, v: cur.v};\n cur = lSize > n ? cur.l : cur.r;\n if (lSize < n)\n n -= lSize + 1; \n } \n return null;\n}\n\nTreap.prototype._forEach = function(t, cb)\n{\n if (t.l)\n this._forEach(t.l, cb);\n cb(t.k, t.v);\n if (t.r)\n this._forEach(t.r, cb);\n}\n\nTreap.prototype.forEach = function(cb)\n{\n if (this._root)\n this._forEach(this._root, cb);\n}\n\nTreap.prototype.insert = function(k, v)\n{\n this._root = this._insert(this._root, new Treap.Node(k, v, Math.random()+Math.random(), null, null)); \n}\n\nTreap.prototype._merge = function(l, r)\n{\n if (!l)\n {\n this._update(r);\n return r;\n }\n if (!r)\n {\n this._update(l);\n return l;\n }\n if (l.p > r.p)\n {\n l.r = this._merge(l.r, r)\n this._update(l);\n return l;\n }\n r.l = this._merge(l, r.l);\n this._update(r);\n return r;\n}\n\nTreap.prototype._erase = function(t, k)\n{\n if (t.k == k)\n {\n var tmp = this._merge(t.l, t.r);\n this._update(tmp);\n return tmp;\n }\n if (this.cmp(k, t.k) <= 0)\n if (t.l)\n t.l = this._erase(t.l, k);\n else\n if (t.r)\n t.r = this._erase(t.r, k);\n this._update(t);\n return t;\n}\n\nTreap.prototype.erase = function(k)\n{\n if (this._root)\n this._root = this._erase(this._root, k);\n}\n\nTreap.prototype._get = function(t, k)\n{\n if (!t)\n return undefined;\n if (this.cmp(k, t.k) == 0)\n return t.v;\n if (this.cmp(k, t.k) < 0)\n return this._get(t.l, k);\n return this._get(t.r, k);\n}\n\nTreap.prototype.get = function(k)\n{\n if (this._root)\n return this._get(this._root, k);\n return undefined;\n}\n\nTreap.prototype.clear = function()\n{\n this._root = null;\n}\n\nTreap.prototype.size = function()\n{\n return (this._root?this._root.size:0);\n}\n\nfunction cmp(a, b)\n{\n if (a < b)\n return -1;\n if (a > b)\n return 1;\n return 0;\n}\n\nfunction main(cin, cout)\n{\n var n = +cin.next();\n var treap = new Treap(cmp);\n treap.insert(\"polycarp\", 1);\n for(var i = 0; i < n; ++i)\n { \n var s = cin.next().toLowerCase();\n cin.next();\n var t = cin.next().toLowerCase();\n treap.insert(s, treap.get(t) + 1);\n }\n var ans = 0;\n treap.forEach(function(k, v){ans=Math.max(ans,v);});\n cout.print(ans);\n}\n\nvar cin = new Reader();\nvar cout = new Writer(); \n\nmain(cin, cout);\n\ncout.flush();"}, {"source_code": "var n = parseInt(readline());\nvar mapa = new Array();\nmapa['Polycarp'.toUpperCase()] = 1;\nvar rs = 0;\nfor (var i = 0; i < n; ++i) {\n var s = readline().split(' ');\n mapa[s[0].toUpperCase()] = mapa[s[2].toUpperCase()] + 1;\n if (mapa[s[0].toUpperCase()] > rs) {\n rs = mapa[s[0].toUpperCase()];\n }\n}\nprint(rs);"}, {"source_code": "\"use strict\";\nvar i = 0,\n\tdepth = {\n\t\t'polycarp': 1\n\t},\n\tmax = 0,\n\tpair,\n\tcur,\n\tn = +readline();\n\nfor (; i max && (max = cur);\n}\nprint(max);"}, {"source_code": "var n = parseInt(readline());\nvar s, m=0, a = new Array(), b = new Array(), l = new Array();\nfor(i=0; i=0; j--) {\nl[j] = 2;\nkk = b[j];\nwhile (kk != b[0]) {\nfor (i=0; i m) m = l[j];\n}\nprint(m);"}, {"source_code": "var count = readline();\nvar chain = {polycarp: []};\n\nfor(var i = 0; i < count; i++) {\n var names = readline()\n .split(' reposted ')\n .map(function(v) { return v.toLowerCase() });\n\n if(!chain[names[0]]) chain[names[0]] = chain[names[1]].concat();\n chain[names[0]].push(names[1]);\n}\n\nvar max = 0;\nfor(var key in chain) {\n var cur = chain[key].length + 1;\n if(max < cur) max = cur;\n}\n\nprint(max);\n"}, {"source_code": "'use strict';\n\n// const rlLib = require('readline');\n\n// const rl = rlLib.createInterface({\n// input: process.stdin,\n// output: process.stdout\n// });\n\n// let inputs = [];\n// let allCount = 1;\n// let currentLine = 0;\n\n// rl.on('line', (input) => {\n// inputs.push(input);\n// if (inputs.length === 1) {\n// allCount = +inputs[0] + 1;\n// }\n// if (inputs.length >= allCount) {\n// main();\n\n// rl.close(); \n// }\n// });\n\n// function readline() {\n// return inputs[currentLine++];\n// }\n// function print() {\n// console.log.apply(this, arguments);\n// }\n\n// /**\n// * @param {number} s\n// * @param {number[]} nums\n// * @return {number}\n// */\n// function main() {\n var count = +readline();\n // parent => children\n var tree = {'polycarp': []};\n\n for (var i = 0; i < count; i++) {\n var str = readline().split(' ').map(x => x.toLowerCase());\n\n tree[str[2]].push(str[0]);\n \n if (!tree[str[0]]) {\n tree[str[0]] = [];\n }\n }\n\n\n // пройдем поиском в ширину и посчитаем\n\n var st = [];\n var set = new Set();\n var res = 1;\n\n st.push(['polycarp', 1]);\n set.add('polycarp');\n\n while (st.length) {\n var data = st.pop();\n var name = data[0];\n var count = data[1];\n\n if (res < count) {\n res = count;\n }\n\n tree[name].forEach(function(name) {\n if (!set.has(name)) {\n st.push([name, count + 1]);\n set.add(name);\n }\n });\n }\n\n\n print(res);\n// };\n\n\n"}, {"source_code": "var i = 0,\n repostsCount = 0,\n maxDeep = 1,\n users = {\n 'polycarp': {\n reposts: [],\n repostedFrom: false,\n deep: maxDeep,\n },\n };\n\nvar repostsCount = parseInt(readline());\n\nfunction lower(string) {\n return string.toLowerCase();\n}\n\nwhile(i < repostsCount) {\n var _ = readline().split(' reposted ').map(lower),\n destination = _[0], source = _[1];\n users[source].reposts.push(destination);\n destinationDeep = users[source].deep + 1;\n if(maxDeep < destinationDeep) {\n maxDeep = destinationDeep;\n }\n users[destination] = {\n reposts: [],\n repostedFrom: source,\n deep: users[source].deep + 1,\n }\n i++;\n}\n\n print(maxDeep);"}, {"source_code": "var lengths = [];\n\nfunction callback(arr, name2, i, d) {\n\tvar indOf = true;\n\n\tfor (; i < arr.length; i++) {\n\t\tif (arr[i][1] === name2) {\n\t\t\tcallback(arr, arr[i][0], i + 1, d + 1);\n\t\t\tindOf = false;\n\t\t}\n\t}\n\n\tif (indOf) {\n\t\tlengths.push(d);\n\t}\n}\n\n\nfunction maxLengthOfChain() {\n\tvar n = readline();\n var arr = [];\n\n for (var i = 0; i < n; i++) {\n arr.push(readline().toLowerCase().split(' reposted '));\n }\n\n\n\tcallback(arr, 'polycarp', 0, 1);\n\n\n\treturn Math.max(...lengths);\n}\n\nprint(maxLengthOfChain());\n"}, {"source_code": "\n\nTree.prototype.traverseDF = function(callback) {\n\n\t// это рекурсивная и мгновенно вызываемая функция \n\t(function recurse(currentNode) {\n\t\t// шаг 2\n\t\tfor (var i = 0, length = currentNode.children.length; i < length; i++) {\n\t\t\t// шаг 3\n\t\t\trecurse(currentNode.children[i]);\n\t\t}\n\n\t\t// шаг 4\n\t\tcallback(currentNode);\n\n\t\t// шаг 1\n\t})(this._root);\n};\n\nTree.prototype.add = function(data, toData, traversal) {\n\tvar child = new Node(data),\n\tparent = null,\n\tcallback = function(node) {\n\t\tif (node.data === toData) {\n\t\t\tparent = node;\n\t\t}\n\t};\n\n\tthis.contains(callback, traversal);\n\n\tif (parent) {\n\t\tparent.children.push(child);\n\t\tchild.parent = parent;\n\t} else {\n\t\tthrow new Error('Cannot add node to a non-existent parent.');\n\t}\n};\n\nTree.prototype.contains = function(callback, traversal) {\n\ttraversal.call(this, callback);\n};\n\nfunction length(node, startLength) {\n\tif (node.parent === null) {\n\t\treturn startLength;\n\t}\n\treturn length(node.parent, startLength + 1);\n}\n\nfunction maxLengthOfChain() {\n \n var n = readline();\n var arr = [];\n var line;\n \n while (line = readline()) {\n arr.push(line);\n }\n\n// \tvar s = str.substring(2).toLowerCase();\n// \tvar arr = s.split('\\n');\n\tvar tree = new Tree('polycarp');\n\n\tarr.forEach(function(elem) {\n\t\tvar names = elem.toLowerCase().split(' reposted ');\n\t\t\t\n\t\ttree.add(names[0], names[1], tree.traverseDF);\n\t});\n\n\tvar maxLength = 0;\n\ttree.contains(function(node) {\n\t\tvar l = length(node, 1);\n\t\tif (maxLength < l) {\n\t\t\tmaxLength = l;\n\t\t}\n\t}, tree.traverseDF);\n\n\tprint(maxLength);\n}\n\nmaxLengthOfChain();\n\nfunction Node(data) {\n\tthis.data = data;\n\tthis.parent = null;\n\tthis.children = [];\n}\n\nfunction Tree(data) {\n\tvar node = new Node(data);\n\tthis._root = node;\n}\n\n"}, {"source_code": "var lengths = [];\n\nfunction callback(arr, name2, i, d) {\n\tvar indOf = true;\n\n\tfor (; i < arr.length; i++) {\n\t\tif (arr[i][1] === name2) {\n\t\t\tcallback(arr, arr[i][0], i + 1, d + 1);\n\t\t\tindOf = false;\n\t\t}\n\t}\n\n\tif (indOf) {\n\t\tlengths.push(d);\n\t}\n}\n\n\nfunction maxLengthOfChain() {\n\tvar n = readline();\n var arr = [];\n var line;\n \n while (line = readline()) {\n arr.push(line.toLowerCase().split(' reposted '));\n }\n\n\n\tcallback(arr, 'polycarp', 0, 1);\n\n\n\treturn Math.max(...lengths);\n}\n\nprint(maxLengthOfChain());\n"}, {"source_code": "var n = readline();\nvar reposts = {\n\tpolycarp: 1\n};\nvar max = 1;\nfor (var i=0; i < n; i++) {\n\tvar str = readline().toLowerCase().split(' ');\n\tvar newValue = reposts[str[2]] + 1;\n\treposts[str[0]] = newValue;\n\tif (newValue > max) {\n\t\tmax = newValue;\n\t}\n}\nprint(max);"}, {"source_code": "\nfunction parseRepost(repostString) {\n var splitNames = repostString.split(\" reposted \");\n var parent = splitNames[1];\n var child = splitNames[0];\n\n return [parent.toLowerCase(), child.toLowerCase()];\n}\n\nfunction getPopularity() {\n var repostMap = {};\n var max = 0;\n var numPosts = parseInt(readline());\n for(var i = 0; i < numPosts; i++) {\n var users = parseRepost(readline());\n if(!repostMap.hasOwnProperty(users[0])) {\n repostMap[users[0]] = 1;\n }\n\n repostMap[users[1]] = repostMap[users[0]] + 1;\n if(repostMap[users[1]]> max) {\n max = repostMap[users[1]];\n }\n }\n return max;\n}\n\n\n\nprint(getPopularity());\n"}, {"source_code": "var l = +readline();\nvar chainLengths = {}\n\nchainLengths[\"polycarp\"] = 1\nvar maxLen = 0\n\nfor (var i = 0; i < l; i++) {\n var rec = readline().split(' reposted ');\n var a = rec[0].toLowerCase()\n var b = rec[1].toLowerCase()\n chainLengths[a] = chainLengths[b] + 1\n if (chainLengths[a] > maxLen) {\n maxLen = chainLengths[a]\n }\n}\n\nprint(maxLen);"}, {"source_code": "// #################################################################### //\n/**\n * @class UserNode will constitute the nodes of our repost tree,\n * with each node in the tree maintaining a count of the longest\n * chain perturbing from this node, and a reference to its parent\n * node.\n *\n * NOTE: the popularity attribute of the node or the popularity of\n * of this node's subtree refers to the length of the longest chain\n * perturbing from this node, with it as root.\n */\nvar UserNode = function(name){\n // Method to append a child node to children list.\n this.appendChild = function(childName){\n var newChild = new UserNode(childName.toLowerCase());\n newChild.parent = self;\n self.children.push(newChild);\n }\n // Method to get reference to the last child of this node.\n this.getLastChild = function(){\n return self.children[self.children.length-1];\n }\n // Method to determine popularity of this nodes's subtree.\n this.computePopularity = function(){\n var maxPopularity = 0;\n for(var i = 0;i 0; i--) {\n var line = readline().split(\" \");\n var len = posts[line[2].toLowerCase()] + 1;\n posts[line[0].toLowerCase()] = len;\n if (max < len) max = len;\n}\nprint(max);\n"}], "negative_code": [{"source_code": "\"use strict\";\nvar i = 0,\n\tdepth = {\n\t\t'polycarp': 0\n\t},\n\tmax = 0,\n\tpair,\n\tcur,\n\tn = +readline();\n\nfor (; i max && (max = cur);\n}\nprint(max);"}, {"source_code": "//var n = parseInt(readline());\nvar s, m=0, a = new Array(), b = new Array(), l = new Array();\n/*for(i=0; i=0; j--) {\nl[j] = 2;\nkk = b[j];\nwhile (kk != b[0]) {\nfor (i=0; i m) m = l[j];\n}\nprint(m);"}, {"source_code": "var count = readline();\nvar chain = {};\n\nfor(var i = 0; i < count; i++) {\n var names = readline()\n .split(' reposted ')\n .map(function(v) { return v.toLowerCase() });\n\n if(!chain[names[0]]) chain[names[0]] = chain[names[1]] || [];\n chain[names[0]].push(names[1]);\n}\n\nvar max = 0;\nfor(var key in chain) {\n var cur = chain[key].length + 1;\n if(max < cur) max = cur;\n}\n\nprint(max);\n"}, {"source_code": "var n = readline();\nvar reposts = {\n\tpolycarp: 1\n};\nvar max = 1;\nfor (var i=0; i < n; i++) {\n\tvar str = readline().toLowerCase().split(' ');\n\tvar newValue = reposts[str[2]] + 1;\n\treposts[str[0]] = newValue;\n\tif (newValue > max) {\n\t\tmax = newValue;\n\t}\n}"}, {"source_code": "\nfunction parseRepost(repostString) {\n var splitNames = repostString.split(\" reposted \");\n var parent = splitNames[1];\n var child = splitNames[0];\n\n return [parent.toLowerCase(), child.toLowerCase()];\n}\n\nfunction getPopularity() {\n var repostMap = {};\n var max = 0;\n var numPosts = parseInt(readline());\n for(var i = 0; i < numPosts; i++) {\n var users = parseRepost(readline());\n if(!repostMap.hasOwnProperty(users[0])) {\n repostMap[users[0]] = 0;\n }\n\n repostMap[users[1]] = repostMap[users[0]] + 1;\n if(repostMap[users[1]]> max) {\n max = repostMap[users[1]];\n }\n }\n return max;\n}\n\n\n\nprint(getPopularity());\n"}], "src_uid": "16d4035b138137bbad247ccd5e560051"} {"nl": {"description": "This is an interactive problem.There is a positive integer $$$1 \\le x \\le 10^9$$$ that you have to guess.In one query you can choose two positive integers $$$a \\neq b$$$. As an answer to this query you will get $$$\\gcd(x + a, x + b)$$$, where $$$\\gcd(n, m)$$$ is the greatest common divisor of the numbers $$$n$$$ and $$$m$$$.To guess one hidden number $$$x$$$ you are allowed to make no more than $$$30$$$ queries.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) denoting the number of test cases. The integer $$$x$$$ that you have to guess satisfies the constraints: ($$$1 \\le x \\le 10^9$$$).", "output_spec": null, "sample_inputs": ["2\n\n1\n\n8\n\n\n1"], "sample_outputs": ["? 1 2\n\n? 12 4\n\n! 4\n? 2000000000 1999999999\n\n! 1000000000"], "notes": "NoteThe first hidden number is $$$4$$$, that's why the answers for the queries are:\"? 1 2\" — $$$\\gcd(4 + 1, 4 + 2) = \\gcd(5, 6) = 1$$$.\"? 12 4\" — $$$\\gcd(4 + 12, 4 + 4) = \\gcd(16, 8) = 8$$$.The second hidden number is $$$10^9$$$, that's why the answer for the query is:\"? 2000000000 1999999999\" — $$$\\gcd(3 \\cdot 10^9, 3 \\cdot 10^9 - 1) = 1$$$.These queries are made only for understanding the interaction and are not enough for finding the true $$$x$$$."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n console.log(`! ${res}`);\r\n return res;\r\n}\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\nfunction crt(p, a) {\r\n const n = p.reduce((a, b) => a * b, 1);\r\n let res = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n return (res % n + n) % n;\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nlet inputs = new Array(primes.length).fill(0);\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\nfunction question(message) {\r\n return new Promise(function (resolve, reject) {\r\n rl.question(message, answer => {\r\n resolve(Number(answer));\r\n });\r\n });\r\n}\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\nvoid async function () {\r\n let t = await read();\r\n while (t--) {\r\n inputs = [];\r\n for (let i = 1; i <= 23; i++) {\r\n const message = `? ${i} ${i + lcm}\\n`;\r\n const res = await question(message);\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = (-i % primes[j] + primes[j]) % primes[j];\r\n }\r\n }\r\n }\r\n main(inputs, primes);\r\n }\r\n}();\r\n"}], "negative_code": [{"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers)\r\n console.log(`! ${res}`)\r\n return res\r\n}\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\nfunction crt(p, a) {\r\n const n = p.reduce((a, b) => a * b, 1)\r\n let res = 0\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i])\r\n m2 = ((m2 % p[i]) + p[i]) % p[i]\r\n res += a[i] * m1 * m2\r\n }\r\n return ((res % n) + n) % n\r\n}\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nlet inputs = new Array(primes.length).fill(0)\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n let pre = new Date().valueOf(),\r\n readtime = 0,\r\n primetime = 0,\r\n maintime = 0\r\n while (t--) {\r\n inputs = []\r\n for (let i = 1; i <= 23; i++) {\r\n let now = new Date().valueOf()\r\n console.log(`? ${i} ${i + lcm}`)\r\n\r\n const res = await read()\r\n\r\n readtime += new Date().valueOf() - now\r\n now = new Date().valueOf()\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = ((-i % primes[j]) + primes[j]) % primes[j]\r\n }\r\n }\r\n\r\n primetime += new Date().valueOf() - now\r\n }\r\n let now = new Date().valueOf()\r\n main(inputs, primes)\r\n maintime += new Date().valueOf() - now\r\n if (new Date().valueOf() - pre > 2000) {\r\n console.log(`? ${readtime},${readtime},${maintime}`)\r\n }\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers)\r\n console.log(`! ${res}`)\r\n return res\r\n}\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\nfunction crt(p, a) {\r\n const n = p.reduce((a, b) => a * b, 1)\r\n let res = 0\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i])\r\n m2 = ((m2 % p[i]) + p[i]) % p[i]\r\n res += a[i] * m1 * m2\r\n }\r\n return ((res % n) + n) % n\r\n}\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nlet inputs = new Array(primes.length).fill(0)\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n let pre = new Date().valueOf(),\r\n readtime = 0,\r\n primetime = 0,\r\n maintime = 0\r\n while (t--) {\r\n inputs = []\r\n for (let i = 1; i <= 23; i++) {\r\n let now = new Date().valueOf()\r\n console.log(`? ${i} ${i + lcm}`)\r\n\r\n const res = await read()\r\n\r\n readtime += new Date().valueOf() - now\r\n now = new Date().valueOf()\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = ((-i % primes[j]) + primes[j]) % primes[j]\r\n }\r\n }\r\n\r\n primetime += new Date().valueOf() - now\r\n }\r\n let now = new Date().valueOf()\r\n main(inputs, primes)\r\n maintime += new Date().valueOf() - now\r\n if (new Date().valueOf() - pre > 2000) {\r\n console.log(`readtime: ${readtime},primetime: ${readtime},maintime: ${maintime}`)\r\n }\r\n }\r\n})()\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n //if(res===76636274)console.log(answers.join(',')+'|'+primes.join(','))\r\n console.log(`! ${res}`); // console.log(answers, primes)\r\n\r\n return res;\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1); // console.log('n', n)\r\n\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n // if (!a[i]) continue\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 0; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = (-i % primes[j] + primes[j]) % primes[j];\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(num => num !== undefined), primes.filter((_, i) => inputs[i] !== undefined));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n //if(res===76636274)console.log(answers.join(',')+'|'+primes.join(','))\r\n console.log(`! ${res}`); // console.log(answers, primes)\r\n\r\n return res;\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1); // console.log('n', n)\r\n\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n // if (!a[i]) continue\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 0; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = (-i % primes[j] + primes[j]) % primes[j];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(num => num !== undefined), primes.filter((_, i) => inputs[i] !== undefined));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n if(res===76636274)console.log(answers.join(',')+'|'+primes.join(','))\r\n console.log(`! ${res}`); // console.log(answers, primes)\r\n\r\n return res;\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1); // console.log('n', n)\r\n\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n // if (!a[i]) continue\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = (-i % primes[j] + primes[j]) % primes[j];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(num => num !== undefined), primes.filter((_, i) => inputs[i] !== undefined));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n console.log(`! ${res}`); // console.log(answers, primes)\r\n\r\n return res;\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1); // console.log('n', n)\r\n\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n // if (!a[i]) continue\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = (-i % primes[j] + primes[j]) % primes[j];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(num => num !== undefined), primes.filter((_, i) => inputs[i] !== undefined));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n console.log(`! ${res}`); // console.log(answers, primes)\r\n\r\n return res;\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1); // console.log('n', n)\r\n\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n // if (!a[i]) continue\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(num => num !== undefined), primes.filter((_, i) => inputs[i] !== undefined));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n console.log(`! ${res}`); // console.log(answers, primes)\r\n\r\n return res;\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1);\r\n console.log('n', n);\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [ 23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(Boolean), primes.filter((_, i) => Boolean(inputs[i])));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n let res = crt(primes, answers);\r\n console.log(`! ${res}`); // console.log(answers, primes)\r\n\r\n return res;\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1);\r\n console.log('n', n);\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [29, 23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(Boolean), primes.filter((_, i) => Boolean(inputs[i])));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n console.log(`! ${crt(primes, answers)}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1);\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [29, 23, 19, 17, 13, 11, 7, 5];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(Boolean), primes.filter((_, i) => Boolean(inputs[i])));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n console.log(`! ${crt(primes, answers)}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1);\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [29, 23, 19, 17, 13, 11, 7, 5, 3];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(Boolean), primes.filter((_, i) => Boolean(inputs[i])));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes) {\r\n console.log(`! ${crt(primes, answers)}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1);\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [29, 23, 19, 17, 13, 11, 7, 5, 3, 2];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs.filter(Boolean), primes.filter((_, i) => Boolean(inputs[i])));\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes, lcm) {\r\n console.log(`! ${crt(primes, answers)}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n // console.log(p, a)\r\n const n = p.reduce((a, b) => a * b, 1);\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes);\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\n// import { solve } from './solve'\r\nfunction main(answers, primes, lcm) {\r\n console.log(`! ${crt(primes, answers)}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(p, a) {\r\n console.log(p, a);\r\n const n = p.reduce((a, b) => a * b, 1);\r\n let res = 0;\r\n\r\n for (let i = 0; i < p.length; i++) {\r\n if (!a[i]) continue;\r\n let m1 = n / p[i],\r\n [, m2] = exgcd(m1, p[i]);\r\n m2 = (m2 % p[i] + p[i]) % p[i];\r\n res += a[i] * m1 * m2;\r\n }\r\n\r\n return (res % n + n) % n;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 29; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes);\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined);\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0;\r\n\r\n for (let num of r) n *= num;\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i]);\r\n const [d, x, y] = exgcd(m, r[i]);\r\n res = (res + a[i] * m * x % n) % n;\r\n }\r\n\r\n return res;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nlet inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n inputs = [];\r\n\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes, lcm);\r\n }\r\n}();\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined)\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\nlet a = 0\r\nvoid (async function () {\r\n let t = await read()\r\n\r\n\r\n while (t--) {\r\n a++\r\n let str = []\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read()\r\n //str.push(res)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n if(i===2)str.push(`${i}-${j}-${res}-${primes[j]}`)\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n if (a === 4) console.log(inputs.join(',')+'|'+str.join(','))\r\n main(inputs, primes, lcm)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined)\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\nlet a = 0\r\nvoid (async function () {\r\n let t = await read()\r\n\r\n\r\n while (t--) {\r\n a++\r\n let str = []\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read()\r\n //str.push(res)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n if(i===2)str.push(`${i}-${j}-${res}-${primes[j]}`)\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n if (a === 4) console.log(inputs.join(',')+'|',primes.join(','))\r\n main(inputs, primes, lcm)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined)\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n let a = 0\r\n\r\n while (t--) {\r\n a++\r\n let str = []\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read()\r\n //str.push(res)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n if(i===2)str.push(`${i}-${j}-${res}-${primes[j]}`)\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n if (a === 4) console.log(str.join(','))\r\n main(inputs, primes, lcm)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined)\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n let a = 0\r\n\r\n while (t--) {\r\n a++\r\n let str = []\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read()\r\n str.push(res)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n if(i===2)str.push(`${i}-${j}-${res}-${primes[j]}`)\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n if (a === 4) console.log(str.join(','))\r\n main(inputs, primes, lcm)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined)\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n let a = 0\r\n\r\n while (t--) {\r\n a++\r\n let str = []\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read()\r\n str.push(res)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n str.push(`${i}-${j}-${res}-${primes[j]}`)\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n if (a === 4) console.log(str.join(','))\r\n main(inputs, primes, lcm)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes, lcm, a) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined)\r\n\r\n if (a === 4) console.log(nums1.join(',') + '|' + nums2.join(','))\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n let a = 0\r\n\r\n while (t--) {\r\n a++\r\n let str = ''\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read()\r\n str += res\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n main(inputs, primes, lcm, a)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined)\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n let a = 0\r\n\r\n while (t--) {\r\n a++\r\n let str = ''\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read()\r\n str += res\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n if (a === 4) console.log(str)\r\n main(inputs, primes, lcm)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined);\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0;\r\n\r\n for (let num of r) n *= num;\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i]);\r\n const [d, x, y] = exgcd(m, r[i]);\r\n res = (res + a[i] * m * x % n) % n;\r\n }\r\n\r\n return res;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n let a = 0;\r\n\r\n while (t--) {\r\n a++;\r\n\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n if (a === 4) console.log(res);\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes, lcm);\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined);\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0;\r\n\r\n for (let num of r) n *= num;\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i]);\r\n const [d, x, y] = exgcd(m, r[i]);\r\n res = (res + a[i] * m * x % n) % n;\r\n }\r\n\r\n return res;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n let a = 0;\r\n\r\n while (t--) {\r\n a++;\r\n\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (a === 3) console.log(inputs, primes, lcm);\r\n main(inputs, primes, lcm);\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes, lcm) {\r\n const nums1 = answers.filter(num => num !== undefined),\r\n nums2 = primes.filter((_, i) => answers[i] !== undefined);\r\n console.log(`! ${(crt(nums1.length, nums1, nums2) + lcm) % lcm}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0;\r\n\r\n for (let num of r) n *= num;\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i]);\r\n const [d, x, y] = exgcd(m, r[i]);\r\n res = (res + a[i] * m * x % n) % n;\r\n }\r\n\r\n return res;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read();\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes, lcm);\r\n }\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes, lcm) {\r\n console.log(`! ${(crt(answers.length, answers, primes) + lcm) % lcm}`); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0;\r\n\r\n for (let num of r) n *= num;\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i]);\r\n const [d, x, y] = exgcd(m, r[i]);\r\n res = (res + a[i] * m * x % n) % n;\r\n }\r\n\r\n return res;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\n// import fs from 'fs'\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n\r\n while (t--) {\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`);\r\n const res = await read(); // let res = gcd(i + 50, i + lcm + 50)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes, lcm);\r\n }\r\n}();\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes) {\r\n console.log(`! ${crt(answers.length, answers, primes)}`) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\n// import fs from 'fs'\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction question(message) {\r\n return new Promise(function (resolve, reject) {\r\n rl.question(message, answer => {\r\n resolve(Number(answer))\r\n })\r\n })\r\n}\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n\r\n while (t--) {\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read() // let res = gcd(i + 23, i + lcm + 23)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes)\r\n }\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes) {\r\n console.log(crt(answers.length, answers, primes)) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\n// import fs from 'fs'\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction question(message) {\r\n return new Promise(function (resolve, reject) {\r\n rl.question(message, answer => {\r\n resolve(Number(answer))\r\n })\r\n })\r\n}\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n\r\n while (t--) {\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read() // let res = gcd(i + 23, i + lcm + 23)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes)\r\n})()\r\n"}, {"source_code": "'use strict'\r\n\r\nvar readline = require('readline')\r\n\r\nfunction _interopDefaultLegacy(e) {\r\n return e && typeof e === 'object' && 'default' in e ? e : { default: e }\r\n}\r\n\r\nvar readline__default = /*#__PURE__*/ _interopDefaultLegacy(readline)\r\n\r\nfunction main(answers, primes) {\r\n console.log(crt(answers.length, answers, primes)) // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0]\r\n const [d, y, x] = exgcd(b, a % b)\r\n return [d, x, y - Math.floor(a / b) * x]\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0\r\n\r\n for (let num of r) n *= num\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i])\r\n const [d, x, y] = exgcd(m, r[i])\r\n res = (res + ((a[i] * m * x) % n)) % n\r\n }\r\n\r\n return res\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\n// import fs from 'fs'\r\nconst rl = readline__default['default'].createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\nconst inputs = []\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4]\r\nconst lcm = primes.reduce((a, b) => a * b, 1)\r\n\r\nfunction question(message) {\r\n return new Promise(function (resolve, reject) {\r\n rl.question(message, answer => {\r\n resolve(Number(answer))\r\n })\r\n })\r\n}\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)))\r\n })\r\n}\r\n\r\nvoid (async function () {\r\n let t = await read()\r\n\r\n while (t--) {\r\n for (let i = 1; i <= 23; i++) {\r\n console.log(`? ${i} ${i + lcm}`)\r\n const res = await read() // let res = gcd(i + 23, i + lcm + 23)\r\n console.log(res)\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i\r\n break\r\n }\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes)\r\n})()\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes) {\r\n console.log(crt(answers.length, answers, primes)); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0;\r\n\r\n for (let num of r) n *= num;\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i]);\r\n const [d, x, y] = exgcd(m, r[i]);\r\n res = (res + a[i] * m * x % n) % n;\r\n }\r\n\r\n return res;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\n// import fs from 'fs'\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction question(message) {\r\n return new Promise(function (resolve, reject) {\r\n rl.question(message, answer => {\r\n resolve(Number(answer));\r\n });\r\n });\r\n}\r\n\r\nfunction read() {\r\n return new Promise(function (resolve, reject) {\r\n rl.on('line', line => resolve(Number(line)));\r\n });\r\n}\r\n\r\nvoid async function () {\r\n let t = await read();\r\n console.log(t)\r\n while (t--) {\r\n for (let i = 1; i <= 23; i++) {\r\n const res = await question(`? ${i} ${i + lcm}`); // let res = gcd(i + 23, i + lcm + 23)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction main(answers, primes) {\r\n console.log(crt(answers.length, answers, primes)); // console.log(answers, primes)\r\n}\r\n\r\nfunction exgcd(a, b) {\r\n if (b === 0) return [a, 1, 0];\r\n const [d, y, x] = exgcd(b, a % b);\r\n return [d, x, y - Math.floor(a / b) * x];\r\n}\r\n\r\nfunction crt(k, a, r) {\r\n let n = 1,\r\n res = 0;\r\n\r\n for (let num of r) n *= num;\r\n\r\n for (let i = 0; i < k; i++) {\r\n const m = Math.floor(n / r[i]);\r\n const [d, x, y] = exgcd(m, r[i]);\r\n res = (res + a[i] * m * x % n) % n;\r\n }\r\n\r\n return res;\r\n} // console.log(crt(3, [2, 3, 2], [3, 5, 7]))\r\n\r\n// import fs from 'fs'\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst inputs = [];\r\nconst primes = [23, 19, 17, 13, 11, 9, 7, 5, 4];\r\nconst lcm = primes.reduce((a, b) => a * b, 1);\r\n\r\nfunction question(message) {\r\n return new Promise(function (resolve, reject) {\r\n rl.question(message, answer => {\r\n resolve(Number(answer));\r\n });\r\n });\r\n}\r\n\r\nvoid async function () {\r\n for (let i = 1; i <= 23; i++) {\r\n const res = await question(`? ${i} ${i + lcm}`); // let res = gcd(i + 23, i + lcm + 23)\r\n\r\n for (let j = 0; j < primes.length; j++) {\r\n if (res % primes[j] === 0) {\r\n inputs[j] = -i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n main(inputs, primes);\r\n}();\r\n"}], "src_uid": "442015fe13f7f75876d7163f438960d8"} {"nl": {"description": "A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.", "input_spec": "A single line contains a single integer n (1 ≤ n ≤ 100) — the permutation size.", "output_spec": "If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn — permutation p, that is perfect. Separate printed numbers by whitespaces.", "sample_inputs": ["1", "2", "4"], "sample_outputs": ["-1", "2 1", "2 1 4 3"], "notes": null}, "positive_code": [{"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction isPrime(x) {\n\tlet s = Math.sqrt(x);\n\tlet i = 2;\n\twhile (i <= s) {\n\t\tif (x % i === 0) {\n\t\t\treturn false;\n\t\t}\n\t\ti++;\n\t}\n\treturn true;\n}\n\nfunction main() {\n\tlet n = readLine() >> 0;\n\tif ((n & 1) === 1) {\n\t\tconsole.log(-1);\n\t\treturn;\n\t}\n\n\tlet arr = [];\n\tfor (let i = 1; i <= n; i += 2) {\n\t\tarr[i - 1] = i + 1;\n\t\tarr[i] = i;\n\t}\n\n\tconsole.log(arr.join(' '));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on('end', function () {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((str) => {\n return str.trim();\n });\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let input = parseInt(readLine());\n if (input % 2 !== 0) {\n console.log(-1);\n return;\n }\n let finalArray = [];\n\n for (let i = 1; i <= input; i++) {\n if (i % 2 === 0) {\n finalArray.push(i - 1);\n } else {\n finalArray.push(i + 1);\n }\n }\n let final = finalArray.join(' ');\n\n console.log(final);\n}\n"}, {"source_code": "\nvar n=+readline();\n\nif(n%2){\n\tprint(-1);\n}else{\n\tvar p=[];\n\tfor(var i=2; i<=n; i+=2){\n\t\tp.push(i);\n\t\tp.push(i-1);\n\t}\n\tprint(p.join(' '));\n}"}, {"source_code": ";(function () {\n\n\tvar n = +readline();\n\n\tif (n%2 !== 0) {\n\t\tprint(-1);\n\t\treturn;\n\t}\n\n\tvar t = [];\n\tfor (var i = 0; i < n; i += 2) t.push(i + 2, i + 1)\n\tprint( t.join(' ') );\n\n}).call(this);"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline());\n\tif (n%2 == 1) {\n\t\tprint(-1);\n\t} else {\n\t\tvar result = [];\n\t\tfor (var i = 1; 2*i <= n; ++i) {\n\t\t\tresult.push(2*i);\n\t\t\tresult.push(2*i-1);\n\t\t}\n\t\tprint(result.join(' '));\n\t}\n}\n\nmain();\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let len = +readLine();\n if (len % 2 !== 0) {\n console.log(-1);\n return;\n }\n let result = [];\n let [even, odd] = [2, 1];\n\n for (let i = 1; i <= len; i++) {\n if (i % 2 === 0) {\n result.push(odd);\n odd += 2;\n } else {\n result.push(even);\n even += 2;\n }\n }\n console.log(result.join(\" \"));\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n if(N % 2 == 1){\n myout(-1);\n return;\n }\n var output = [];\n for(var i = 1; i <= N; i += 2){\n output.push(i + 1);\n output.push(i);\n } \n myout(myconv(output, 8));\n}\n"}, {"source_code": "//Perfect Permutation\n\nconst {EOL} = require('os');\n\nlet inp = '';\n\nprocess.stdin.on('data', c => inp += c);\n\nprocess.stdin.on('end', () => {\n let n = +inp.split(EOL)[0];\n \n if(n % 2 == 1) {\n \tprocess.stdout.write(\"-1\");\n \treturn;\n }\n\n for(let i = 1; i <= n; i += 2) {\n \tprocess.stdout.write((i + 1) + \" \" + i + \" \");\n }\n\n return;\n});"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const n = +d;\n\n if (n % 2 === 1) {\n console.log(-1);\n return;\n }\n\n let ans = [];\n for (let i = 1; i <= n; i++) {\n if (i % 2 === 1) {\n ans.push(i + 1);\n }\n else {\n ans.push(i - 1);\n }\n }\n\n console.log(ans.join(' '));\n});\n"}], "negative_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const n = +d;\n\n if (n === 1) {\n console.log(-1);\n return;\n }\n\n let ans = [];\n for (let i = 1; i <= n; i++) {\n if (i % 2 === 1) {\n ans.push(i + 1);\n }\n else {\n ans.push(i - 1);\n }\n }\n\n console.log(ans.join(' '));\n});\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n if(N == 1){\n myout(-1);\n return;\n }\n var output = [];\n for(var i = 2; i <= N; i++){\n output.push(i);\n }\n output.push(1);\n myout(myconv(output, 8));\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const n = +d;\n\n if (n === 1) {\n console.log(-1);\n return;\n }\n\n const ans = [n];\n for (let i = 1; i < n; i++) {\n ans.push(i);\n }\n\n console.log(ans.join(' '));\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const n = +d;\n\n if (n === 1) {\n console.log(-1);\n return;\n }\n\n const ans = [];\n for (let i = n; i > 0; i--) {\n ans.push(i);\n }\n\n console.log(ans.join(' '));\n});\n"}], "src_uid": "204ba74195a384c59fb1357bdd71e16c"} {"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 ≤ n ≤ 200 000). The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), 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  + 8 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": "function sa(n ,moves){\n var minPos = -1* Number.MAX_VALUE;\n var maxPos = Number.MAX_VALUE;\n var prevDiv = Number(moves[0][1]);\n var step = Number(moves[0][0]);\n if(n==1){\n if(prevDiv==2){\n return 1899 + step\n }\n return \"Infinity\";\n }\n \n if(prevDiv == 2){\n maxPos = 1899;\n }\n if(prevDiv == 1){\n minPos = 1900;\n }\n \n for(var i=1;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos + step < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(minPos + step >= 1900){\n return \"Impossible\";\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos + step < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == 0){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Impossible\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == 0){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos + step < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(minPos + step >= 1900){\n return \"Impossible\";\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n print(minPos, maxPos)\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == 0){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == 0){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos + step < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(minPos + step >= 1900){\n return \"Impossible\";\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos + step < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(minPos + step >= 1900){\n return \"Impossible\";\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == 0){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == 0){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos + step < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(minPos + step >= 1900){\n return \"Impossible\";\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(maxPos + step < 1900){\n return \"Impossible\";\n }\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos == -1* Number.MAX_VALUE){\n minPos = 1900;\n }\n if(minPos + step >= 1900){\n return \"Impossible\";\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n print(minPos, maxPos)\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i 0){\n if(curDiv == 2){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(minPos >= 1900){\n return \"Impossible\";\n }\n if(maxPos >=1900){\n maxPos = 1899;\n }\n } else {\n \n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1){\n minPos = minPos + step;\n maxPos = maxPos + step;\n if(maxPos < 1900){\n return \"Impossible\";\n }\n if(minPos <1900){\n minPos = 1900;\n }\n } else {\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n } else {\n if(step > 0){\n if(curDiv == 2) {\n return \"Impossible\";\n\n } else {\n if(maxPos == Number.MAX_VALUE){\n maxPos = 1899;\n }\n if(minPos < 1900 - step){\n minPos = 1900 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n } else {\n if(curDiv == 1) {\n return \"Impossible\";\n\n } else {\n if(minPos == 0){\n minPos = 1900;\n }\n if(maxPos > 1899 - step){\n maxPos = 1899 - step;\n }\n minPos = minPos + step;\n maxPos = maxPos + step;\n }\n }\n }\n step = Number(moves[i][0]);\n prevDiv = curDiv;\n }\n if(maxPos == Number.MAX_VALUE){\n return \"Infinity\";\n }\n return maxPos + Number(moves[n-1][0]);\n}\n\n\nvar n = Number(readline());\nvar moves = [];\nfor(var i=0;i inp += chunk);\nprocess.stdin.on('end', () => {\n inp = inp.split('\\n');\n let ic = 0;\n let ntest = +inp[ic++];\n while (ntest--) {\n let [n, r] = inp[ic++].split(' ').map(BigInt);\n\n let t = min(n - 1n, r);\n let ans = t * (t + 1n) / 2n;\n if (r >= n) {\n ++ans;\n }\n console.log(ans.toString());\n\n }\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = ''\nlet currentLine = 0\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin\n})\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n')\n\n main()\n})\n\nfunction readLine() {\n return inputString[currentLine++]\n}\n\nconst s2i = s => parseInt(s, 10)\n\nconst readLineOfInts = () => {\n const split = readLine().split(' ')\n const result = []\n for (let i = 0, l = split.length; i < l; i++) {\n result.push(s2i(split[i]));\n }\n return result\n}\n\nfunction main() {\n let T = s2i(readLine())\n let out = ''\n\n while (T--) {\n const [n, r] = readLineOfInts()\n\n const min = BigInt(Math.min(n-1, r))\n\n const result = (n <= r ? 1n : 0n) + (min * (min + 1n) / 2n)\n\n out += result.toString() + '\\n'\n }\n console.log(out)\n}\n"}, {"source_code": "function solve() {\n var nr = read().split(' ').map(BigInt);\n var n = nr[0];\n var r = nr[1];\n if (r < n) {\n write('' + (r * (r + 1n) / 2n));\n } else {\n write('' + (n * (n - 1n) / 2n + 1n))\n }\n\n}\n\nfunction init() {\n var T;\n T = 1;\n T = Number(read());\n for (var t = 0; t < T; t++) {\n solve();\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n \n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n \n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n init();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', init);\n }\n} else {\n init();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}, {"source_code": " // Lang: Node.js\n 'use strict';\n let x = '', y = 0;\n let print = x => console.log(x);\n \n process.stdin.on('data', inputStdin => x += inputStdin);\n process.stdin.on('end', () => { x = x.split('\\n'); main(); });\n let readline = () => x[y++];\n \n \n // ************************ Code Start ***************************\n \n function main() {\n var Tc = parseInt(readline());\n while (Tc-- > 0) {\n var Arr = readline().split(\" \").map(BigInt);\n var n = Arr[0];\n var r = Arr[1];\n if (r < n) {\n print(\"\" + (r * (r + 1n)) / 2n);\n } else {\n print(\"\" + ((n * (n - 1n)) / 2n + 1n));\n }\n }\n }"}, {"source_code": "// Lang: Node.js\n'use strict';\nlet x = '', y = 0;\nlet print = x => console.log(x);\n \nprocess.stdin.on('data', inputStdin => x += inputStdin);\nprocess.stdin.on('end', () => { x = x.split('\\n'); main(); });\nlet readline = () => x[y++];\n \n \n// ************************ Code Start ***************************\n \nfunction main() {\n var Tc = parseInt(readline());\n while (Tc-- > 0) {\n var Arr = readline().split(\" \").map(BigInt);\n var n = Arr[0];\n var r = Arr[1];\n if (r < n) {\n print(\"\" + (r * (r + 1n)) / 2n);\n } else {\n print(\"\" + ((n * (n - 1n)) / 2n + 1n));\n }\n }\n\n}"}], "negative_code": [], "src_uid": "eb3d8259ca598c3c455ddfdbe433cb78"} {"nl": {"description": "Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).You are given an $$$n \\times m$$$ grid of \"R\", \"W\", and \".\" characters. \"R\" is red, \"W\" is white and \".\" is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count).Your job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells.", "input_spec": "The first line contains $$$t$$$ ($$$1 \\le t \\le 100$$$), the number of test cases. In each test case, the first line will contain $$$n$$$ ($$$1 \\le n \\le 50$$$) and $$$m$$$ ($$$1 \\le m \\le 50$$$), the height and width of the grid respectively. The next $$$n$$$ lines will contain the grid. Each character of the grid is either 'R', 'W', or '.'.", "output_spec": "For each test case, output \"YES\" if there is a valid grid or \"NO\" if there is not. If there is, output the grid on the next $$$n$$$ lines. If there are multiple answers, print any. In the output, the \"YES\"s and \"NO\"s are case-insensitive, meaning that outputs such as \"yEs\" and \"nO\" are valid. However, the grid is case-sensitive.", "sample_inputs": ["3\n4 6\n.R....\n......\n......\n.W....\n4 4\n.R.W\n....\n....\n....\n5 1\nR\nW\nR\nW\nR"], "sample_outputs": ["YES\nWRWRWR\nRWRWRW\nWRWRWR\nRWRWRW\nNO\nYES\nR\nW\nR\nW\nR"], "notes": "NoteThe answer for the first example case is given in the example output, and it can be proven that no grid exists that satisfies the requirements of the second example case. In the third example all cells are initially coloured, and the colouring is valid."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// End of Codeforces interface\r\n\r\nfunction fillLine(c1, c2, index, length) {\r\n let line = '';\r\n for (let i = 0; i < length; i++) {\r\n const first = index % 2 == i % 2;\r\n line += (first ? c1 : c2);\r\n }\r\n return line;\r\n}\r\n\r\nfunction fillGrid(x, y, c1, c2) {\r\n const grid = [];\r\n for (let i = 0; i < x; i++) {\r\n grid.push(fillLine(c1, c2, i, y));\r\n }\r\n return grid;\r\n}\r\n\r\nfunction isOkGrid(initialGrid, finalGrid) {\r\n try {\r\n initialGrid.forEach((x, i) => {\r\n for (let y = 0; y < x.length; y++) {\r\n if (x.charAt(y) != '.') {\r\n if (x.charAt(y) != finalGrid[i].charAt(y)) throw new Error();\r\n }\r\n }\r\n });\r\n return true;\r\n } catch (e) {\r\n return false;\r\n }\r\n}\r\n\r\nfunction main() {\r\n let testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n let [x, y] = readline().split(\" \").map(n => parseInt(n));\r\n let initialGrid = [];\r\n let finalGrid;\r\n let isOkTestCase;\r\n\r\n for (let j = 0; j < x; j++) {\r\n initialGrid.push(readline());\r\n }\r\n \r\n finalGrid = fillGrid(x, y, 'R', 'W');\r\n isOkTestCase = isOkGrid(initialGrid, finalGrid);\r\n\r\n if (!isOkTestCase) {\r\n finalGrid = fillGrid(x, y, 'W', 'R');\r\n isOkTestCase = isOkGrid(initialGrid, finalGrid);\r\n }\r\n\r\n if (isOkTestCase) {\r\n console.log('YES');\r\n for (let line of finalGrid) {\r\n console.log(line);\r\n }\r\n } else {\r\n console.log('NO');\r\n }\r\n }\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar dy = [-1,0,1,0];\r\n\tvar dx = [0,-1,0,1];\r\n\twhile(hasNext()){\r\n\t\tvar H = nextInt();\r\n\t\tvar W = nextInt();\r\n\t\tvar s = new Array(H);\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\ts[i] = nextCharArray();\r\n\t\t}\r\n\t\tvar queue = [];\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\tfor(var j = 0; j < W; j++){\r\n\t\t\t\tif(s[i][j] != \".\"){\r\n\t\t\t\t\tqueue.push([i,j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(queue.length == 0){\r\n\t\t\tqueue.push([0,0]);\r\n\t\t\ts[0][0] = \"R\";\r\n\t\t}\r\n\t\twhile(queue.length > 0){\r\n\t\t\tvar tmp = queue.shift();\r\n\t\t\tvar y = tmp[0];\r\n\t\t\tvar x = tmp[1];\r\n\t\t\tfor(var j = 0; j < dy.length; j++){\r\n\t\t\t\tvar nextY = y + dy[j];\r\n\t\t\t\tvar nextX = x + dx[j];\r\n\t\t\t\tif(nextY >= 0 && nextY < H && nextX >= 0 && nextX < W){\r\n\t\t\t\t\tif(s[nextY][nextX] == \".\"){\r\n\t\t\t\t\t\tif(s[y][x] == \"R\"){\r\n\t\t\t\t\t\t\ts[nextY][nextX] = \"W\";\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\ts[nextY][nextX] = \"R\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tqueue.push([nextY, nextX]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar isOK = true;\r\n\t\tfor(var i = 0; i < H - 1; i++){\r\n\t\t\tfor(var j = 0; j < W; j++){\r\n\t\t\t\tif(s[i][j] == s[i + 1][j]){\r\n\t\t\t\t\tisOK = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\tfor(var j = 0; j < W - 1; j++){\r\n\t\t\t\tif(s[i][j] == s[i][j + 1]){\r\n\t\t\t\t\tisOK = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout((isOK) ? \"Yes\" : \"No\");\r\n\t\tif(isOK){\r\n\t\t\tfor(var i = 0; i < H; i++){\r\n\t\t\t\tmyout(myconv(s[i], 0));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}"}, {"source_code": "let i = \"\";\nprocess.stdin.on(\"data\", c => (i += c));\nprocess.stdin.on(\"end\", () => {\n\tconst { EOL } = require(\"os\");\n\tconst lines = i.split(EOL);\n\tsolve(lines);\n});\n\nfunction solve(lines) {\n\tconst t = lines[0];\n\tlet index = 1;\n\tfor (let i = 0; i < t; i++) {\n\t\tconst ij = lines[index++];\n\t\tconst [n, m] = ij.split(\" \").map(c => +c);\n\t\tlet map = { R: [], W: [], \".\": [] };\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tconst line = lines[index++];\n\t\t\tline.split(\"\").forEach((c, k) => {\n\t\t\t\tmap[c].push([(k + j) % 2, j, k]);\n\t\t\t});\n\t\t}\n\t\tlet rVal = -1;\n\t\tmap[\"R\"].forEach(element => {\n\t\t\tif (rVal === -1) {\n\t\t\t\trVal = element[0];\n\t\t\t} else if (element[0] !== rVal) {\n\t\t\t\trVal = -2;\n\t\t\t}\n\t\t});\n\t\tlet wVal = -1;\n\t\tmap[\"W\"].forEach(element => {\n\t\t\tif (wVal === -1) {\n\t\t\t\twVal = element[0];\n\t\t\t} else if (element[0] !== wVal) {\n\t\t\t\twVal = -2;\n\t\t\t}\n\t\t});\n\t\tif (rVal === -2 || wVal === -2 || (rVal === wVal && rVal !== -1) ) {\n\t\t\tconsole.log(\"NO\");\n\t\t} else {\n\t\t\tconsole.log(\"YES\");\n\t\t\tif (rVal === -1) {\n if(wVal === 1)\n\t\t\t\t rVal = 0;\n else \n rVal = 1;\n\t\t\t}\n\t\t\tfor (let l = 0; l < n; l++) {\n\t\t\t\tlet res = \"\";\n\t\t\t\tfor (let c = 0; c < m; c++) {\n\t\t\t\t\tif (rVal === (c + l) % 2) {\n\t\t\t\t\t\tres += \"R\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres += \"W\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconsole.log(res);\n\t\t\t}\n\t\t}\n\t}\n}\n"}, {"source_code": "/**\r\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\r\n *\r\n * To modify the template, go to Preferences -> Editor -> File and Code Templates -> Other\r\n */\r\n\r\n// Write your solution here\r\nconst {EOL} = require(\"os\");\r\n\r\nfunction alternate_color(current_color) {\r\n return current_color === 'R' ? 'W' : 'R';\r\n}\r\n\r\nfunction is_valid(flag, start_color) {\r\n for (const row of flag) {\r\n let expected_color = start_color;\r\n for (const actual_color of row) {\r\n if (actual_color !== '.' && actual_color !== expected_color) {\r\n return false;\r\n }\r\n expected_color = alternate_color(expected_color);\r\n }\r\n start_color = alternate_color(start_color);\r\n }\r\n return true;\r\n}\r\n\r\nfunction print_solution(start_color, height, width) {\r\n for (let row_no = 0; row_no < height; row_no += 1) {\r\n let row_str = '';\r\n let color = start_color;\r\n for (let col_no = 0; col_no < width; col_no += 1) {\r\n row_str += color;\r\n color = alternate_color(color);\r\n }\r\n console.log(row_str);\r\n start_color = alternate_color(start_color);\r\n }\r\n\r\n}\r\n\r\nfunction solution({height, width, flag}) {\r\n for (const start_color of ['R', 'W']) {\r\n if (is_valid(flag, start_color)) {\r\n console.log('YES');\r\n print_solution(start_color, height, width);\r\n return;\r\n }\r\n }\r\n console.log('NO');\r\n}\r\n\r\nfunction parse(input) {\r\n const [height, width] = input.shift().split(' ').map(Number);\r\n return {\r\n height, width,\r\n flag: input.splice(0, height).map(row => row.trim())\r\n };\r\n}\r\n\r\n\r\nlet lines = '';\r\n\r\nprocess.stdin.on('data', data => lines += data);\r\n\r\nprocess.stdin.on('end', () => {\r\n const input = lines.split(EOL);\r\n const number_of_test_cases = Number(input.shift());\r\n for (let _ = 0; _ < number_of_test_cases; _ += 1) {\r\n solution(parse(input));\r\n }\r\n process.exit();\r\n});"}, {"source_code": "const {EOL} = require(\"os\");\r\n\r\nfunction alternate_color(current_color) {\r\n return current_color === 'R' ? 'W' : 'R';\r\n}\r\n\r\nfunction is_valid(flag, start_color) {\r\n for (const row of flag) {\r\n let expected_color = start_color;\r\n for (const actual_color of row) {\r\n if (actual_color !== '.' && actual_color !== expected_color) {\r\n return false;\r\n }\r\n expected_color = alternate_color(expected_color);\r\n }\r\n start_color = alternate_color(start_color);\r\n }\r\n return true;\r\n}\r\n\r\nfunction print_solution(start_color, height, width) {\r\n for (let row_no = 0; row_no < height; row_no += 1) {\r\n let row_str = '';\r\n let color = start_color;\r\n for (let col_no = 0; col_no < width; col_no += 1) {\r\n row_str += color;\r\n color = alternate_color(color);\r\n }\r\n console.log(row_str);\r\n start_color = alternate_color(start_color);\r\n }\r\n\r\n}\r\n\r\nfunction solution({height, width, flag}) {\r\n for (const start_color of ['R', 'W']) {\r\n if (is_valid(flag, start_color)) {\r\n console.log('YES');\r\n print_solution(start_color, height, width);\r\n return;\r\n }\r\n }\r\n console.log('NO');\r\n}\r\n\r\nfunction parse(input) {\r\n const [height, width] = input.shift().split(' ').map(Number);\r\n return {\r\n height, width,\r\n flag: input.splice(0, height).map(row => row.trim())\r\n };\r\n}\r\n\r\n\r\nlet lines = '';\r\n\r\nprocess.stdin.on('data', data => lines += data);\r\n\r\nprocess.stdin.on('end', () => {\r\n const input = lines.split(EOL);\r\n const number_of_test_cases = Number(input.shift());\r\n for (let _ = 0; _ < number_of_test_cases; _ += 1) {\r\n solution(parse(input));\r\n }\r\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\n \r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\n \r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\n \r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(str => str.trim());\r\n\r\n \r\n\r\n main();\r\n});\r\n\r\n \r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\nvar gcd = function(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n \r\n return gcd(b, a % b);\r\n}\r\n\r\nfunction main()\r\n{\r\n //const name=readLine();\r\n //console.log(name);\r\n\r\n let test=readLine();\r\n while(test--)\r\n {\r\n nn=readLine();\r\n nn=nn.split(\" \");\r\n n=parseInt(nn[0]);\r\n m=parseInt(nn[1]);\r\n grid=[];\r\n pos_x=-1,pos_y=-1;\r\n for(i=0;i=0;j--)\r\n {\r\n if(ch=='R')\r\n {\r\n cur='W';\r\n temp=grid[pos_x][j];\r\n if(temp===ch)\r\n {\r\n chk=false;\r\n break;\r\n }\r\n else\r\n {\r\n grid[pos_x][j]=cur;\r\n ch=cur;\r\n }\r\n }\r\n else\r\n {\r\n cur='R';\r\n temp=grid[pos_x][j];\r\n if(temp===ch)\r\n {\r\n chk=false;\r\n break;\r\n }\r\n else\r\n {\r\n grid[pos_x][j]=cur;\r\n ch=cur;\r\n }\r\n }\r\n }\r\n\r\n ///line right\r\n ch=grid[pos_x][pos_y];\r\n for(j=pos_y+1;j=0;i--)\r\n {\r\n now=grid[i+1][0];\r\n for(j=0;j args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\nconst solve = (n, m, g) => {\r\n // pr(n, m, g);\r\n let res1 = generate(n, m, 'W');\r\n let res2 = generate(n, m, 'R');\r\n if (ok(g, res1)) {\r\n pr('YES');\r\n // pr(\"res1\", res1);\r\n res1 = res1.map(x => x.join(\"\"));\r\n for (const s of res1) pr(s);\r\n } else if (ok(g, res2)) {\r\n pr('YES');\r\n res2 = res2.map(x => x.join(\"\"));\r\n for (const s of res2) pr(s);\r\n } else {\r\n pr('NO');\r\n }\r\n};\r\n\r\nconst ok = (g, t) => {\r\n let n = g.length;\r\n let m = g[0].length;\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (g[i][j] == '.') continue;\r\n if (g[i][j] != t[i][j]) return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\nconst generate = (n, m, start) => {\r\n let res = [];\r\n let c = start;\r\n for (let i = 0; i < n; i++) {\r\n let tmp = [];\r\n for (let j = 0; j < m; j++) {\r\n tmp.push(c = transfer(c));\r\n }\r\n start = transfer(start);\r\n c = start;\r\n res.push(tmp);\r\n }\r\n return res;\r\n};\r\n\r\nconst transfer = (c) => {\r\n return c == 'W' ? 'R' : 'W';\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line);\r\n });\r\n rl.on('close', () => {\r\n let t = Number(input[0]);\r\n let i = 1;\r\n while (t--) {\r\n let s = input[i];\r\n let a = s.split(\" \").map(Number);\r\n let [n, m] = [a[0], a[1]];\r\n let tmp = input.slice(i + 1, i + n + 1);\r\n tmp = tmp.map(s => s.split(\"\"));\r\n solve(n, m, tmp);\r\n i += n + 1;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n const nsc = parseInt(await getLine());\r\n for (let sc = 0; sc < nsc; sc++) {\r\n let n, m;\r\n [n, m] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const table = new Array(n);\r\n for (let i = 0; i < n; i++)\r\n table[i] = (await getLine()).split(\"\");\r\n let fail = false;\r\n let dfs = function (row, col) {\r\n let delta = [-1, 0, 1];\r\n for (let i = 0; i < 3; i++)\r\n for (let j = 0; j < 3; j++) {\r\n if (Math.abs(delta[i]) + Math.abs(delta[j]) === 1) {\r\n let nrow = row + delta[i];\r\n let ncol = col + delta[j];\r\n if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m) {\r\n if (table[nrow][ncol] === table[row][col])\r\n return -1;\r\n else if (table[nrow][ncol] === '.') {\r\n if (table[row][col] == 'R')\r\n table[nrow][ncol] = 'W';\r\n else\r\n table[nrow][ncol] = 'R';\r\n if (dfs(nrow, ncol) < 0)\r\n return -1;\r\n }\r\n }\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n for (let row = 0; row < n && !fail; row++)\r\n for (let col = 0; col < m && !fail; col++)\r\n if (table[row][col] !== '.') {\r\n if (dfs(row, col) < 0) {\r\n fail = true;\r\n }\r\n }\r\n if (table[0][0] === '.') {\r\n table[0][0] = 'R';\r\n if (dfs(0,0) < 0)\r\n faile = true;\r\n }\r\n if (fail)\r\n console.log('NO');\r\n else {\r\n console.log('YES');\r\n for (let row = 0; row < n; row++)\r\n console.log(table[row].join(''));\r\n }\r\n }\r\n}\r\n\r\nsolve();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n let isOkTestCase = true;\r\n let first = '.';\r\n let second = '.';\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n const r = line.indexOf('R');\r\n const w = line.indexOf('W');\r\n if (first == '.' && second == '.') {\r\n if (r !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'R';\r\n second = 'W';\r\n } else {\r\n first = 'W';\r\n second = 'R';\r\n }\r\n }\r\n if (w !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'W';\r\n second = 'R';\r\n } else {\r\n first = 'R';\r\n second = 'W';\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (first == '.' || second == '.') {\r\n first = 'R';\r\n second = 'W';\r\n }\r\n \r\n let color = '.';\r\n forloop:\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (x % 2 == 0 && y % 2 == 0 || x % 2 != 0 && y % 2 != 0) {\r\n color = first;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n } else {\r\n color = second;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (isOkTestCase) {\r\n console.log('YES');\r\n printGrid(grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n let isOkTestCase = true;\r\n let first = '.';\r\n let second = '.';\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n const r = line.indexOf('R');\r\n const w = line.indexOf('W');\r\n if (first == '.' && second == '.') {\r\n if (r !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'R';\r\n second = 'W';\r\n } else {\r\n first = 'W';\r\n second = 'R';\r\n }\r\n }\r\n if (w !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'W';\r\n second = 'R';\r\n } else {\r\n first = 'R';\r\n second = 'W';\r\n }\r\n }\r\n }\r\n }\r\n \r\n let color = '.';\r\n forloop:\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (x % 2 == 0 && y % 2 == 0 || x % 2 != 0 && y % 2 != 0) {\r\n color = first;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n } else {\r\n color = second;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (isOkTestCase) {\r\n console.log('YES');\r\n printGrid(grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x, y] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n let isOkTestCase = true;\r\n let first = '.';\r\n let second = '.';\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n const r = line.indexOf('R');\r\n const w = line.indexOf('W');\r\n if (first == '.' && second == '.') {\r\n if (r !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'R';\r\n second = 'W';\r\n } else {\r\n first = 'W';\r\n second = 'R';\r\n }\r\n }\r\n if (w !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'W';\r\n second = 'R';\r\n } else {\r\n first = 'R';\r\n second = 'W';\r\n }\r\n }\r\n }\r\n }\r\n \r\n let color = '.';\r\n forloop:\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (x % 2 == 0 && y % 2 == 0 || x % 2 != 0 && y % 2 != 0) {\r\n color = first;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n } else {\r\n color = second;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (isOkTestCase) {\r\n console.log('YES');\r\n printGrid(grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction isDifferentNeighborTwo(c1, c2) {\r\n if (!c1 || !c2 || c1 == '.' || c2 == '.') return false;\r\n if (c1 != c2) return true; else return false;\r\n}\r\n\r\nfunction isEqualNeighbor(c1, c2) {\r\n if (!c1 || !c2 || c1 == '.' || c2 == '.') return false;\r\n if (c1 == c2) return true; else return false;\r\n}\r\n\r\nfunction isOkGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n for (let i = -2; i <= 2; i = i + 4) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length)\r\n if (isDifferentNeighborTwo(grid[x][y], grid[x2][y]))\r\n return false;\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid.length)\r\n if (isDifferentNeighborTwo(grid[x][y], grid[x][y2]))\r\n return false;\r\n }\r\n for (let i = -1; i <= 1; i = i + 2) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length)\r\n if (isEqualNeighbor(grid[x][y], grid[x2][y]))\r\n return false;\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid.length)\r\n if (isEqualNeighbor(grid[x][y], grid[x][y2]))\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction isGridComplete(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (grid[x][y] == '.') return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x, y] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n let isOkTestCase = true;\r\n let first = '.';\r\n let second = '.';\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n const r = line.indexOf('R');\r\n const w = line.indexOf('W');\r\n if (first == '.' && second == '.') {\r\n if (r !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'R';\r\n second = 'W';\r\n } else {\r\n first = 'W';\r\n second = 'R';\r\n }\r\n }\r\n if (w !== -1) {\r\n if (j % 2 == 0 && r % 2 == 0 || j % 2 != 0 && r % 2 != 0) {\r\n first = 'W';\r\n second = 'R';\r\n } else {\r\n first = 'R';\r\n second = 'W';\r\n }\r\n }\r\n }\r\n }\r\n \r\n let color = '.';\r\n forloop:\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (x % 2 == 0 && y % 2 == 0 || x % 2 != 0 && y % 2 != 0) {\r\n color = first;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n } else {\r\n color = second;\r\n if (grid[x][y] == '.') {\r\n grid[x][y] = color;\r\n } else if (grid[x][y] != color) {\r\n isOkTestCase = false;\r\n break forloop;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (isOkTestCase) {\r\n console.log('YES');\r\n printGrid(grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction isDifferentNeighborTwo(x1, y1, x2, y2, grid) {\r\n if (x2 < 0 || y2 < 0) return false;\r\n if (x2 >= grid.length || y2 >= grid[x2].length) return false;\r\n if (grid[x1][y1] == '.' || grid[x2][y2] == '.') return false;\r\n if (grid[x1][y1] != grid[x2][y2]) return true; else return false;\r\n}\r\n\r\nfunction isEqualNeighbor(x1, y1, x2, y2, grid) {\r\n if (x2 < 0 || y2 < 0) return false;\r\n if (x2 >= grid.length || y2 >= grid[x2].length) return false;\r\n if (grid[x1][y1] == '.' || grid[x2][y2] == '.') return false;\r\n if (grid[x1][y1] == grid[x2][y2]) return true; else return false;\r\n}\r\n\r\nfunction isOkCell(x, y, grid) {\r\n if (\r\n isEqualNeighbor(x, y, x-1, y, grid) ||\r\n isEqualNeighbor(x, y, x+1, y, grid) ||\r\n isEqualNeighbor(x, y, x, y-1, grid) ||\r\n isEqualNeighbor(x, y, x, y+1, grid) ||\r\n\r\n isDifferentNeighborTwo(x, y, x-2, y, grid) ||\r\n isDifferentNeighborTwo(x, y, x+2, y, grid) ||\r\n isDifferentNeighborTwo(x, y, x, y-2, grid) ||\r\n isDifferentNeighborTwo(x, y, x, y+2, grid)\r\n ) return false; else return true;\r\n}\r\n\r\nfunction isOkGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (!isOkCell(x, y, grid)) return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction fillCell(x, y, grid, color) {\r\n if (x < 0 || y < 0) return;\r\n if (x >= grid.length || y >= grid[x].length) return;\r\n if (grid[x][y] != '.') return;\r\n grid[x][y] = color;\r\n}\r\n\r\nfunction fillNeighborCells(x, y, grid) {\r\n if (grid[x][y] == 'R') {\r\n fillCell(x-1, y, grid, 'W');\r\n fillCell(x+1, y, grid, 'W');\r\n fillCell(x, y-1, grid, 'W');\r\n fillCell(x, y+1, grid, 'W');\r\n } else {\r\n fillCell(x-1, y, grid, 'R');\r\n fillCell(x+1, y, grid, 'R');\r\n fillCell(x, y-1, grid, 'R');\r\n fillCell(x, y+1, grid, 'R');\r\n }\r\n}\r\n\r\nfunction isGridComplete(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (grid[x][y] == '.') return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction fillGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n fillNeighborCells(x, y, grid);\r\n }\r\n }\r\n}\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n const testCases = [];\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x, y] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n }\r\n \r\n testCases.push({ x, y, grid });\r\n }\r\n \r\n testCases.forEach((testCase) => {\r\n if (isOkGrid(testCase.grid)) {\r\n testCase.isOk = true;\r\n } else {\r\n testCase.isOk = false;\r\n }\r\n });\r\n\r\n testCases.forEach((testCase) => {\r\n if (testCase.isOk) {\r\n fillGrid(testCase.grid);\r\n }\r\n });\r\n \r\n testCases.forEach((testCase) => {\r\n if (isOkGrid(testCase.grid)) {\r\n testCase.isOk = true;\r\n } else {\r\n testCase.isOk = false;\r\n }\r\n });\r\n\r\n testCases.forEach((testCase) => {\r\n if (testCase.isOk) {\r\n console.log('YES');\r\n printGrid(testCase.grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n });\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction isDifferentNeighborTwo(x1, y1, x2, y2, grid) {\r\n if (x2 < 0 || y2 < 0) return false;\r\n if (x2 >= grid.length || y2 >= grid[x2].length) return false;\r\n if (grid[x1][y1] == '.' || grid[x2][y2] == '.') return false;\r\n if (grid[x1][y1] != grid[x2][y2]) return true; else return false;\r\n}\r\n\r\nfunction isEqualNeighbor(x1, y1, x2, y2, grid) {\r\n if (x2 < 0 || y2 < 0) return false;\r\n if (x2 >= grid.length || y2 >= grid[x2].length) return false;\r\n if (grid[x1][y1] == '.' || grid[x2][y2] == '.') return false;\r\n if (grid[x1][y1] == grid[x2][y2]) return true; else return false;\r\n}\r\n\r\nfunction isOkCell(x, y, grid) {\r\n if (\r\n isEqualNeighbor(x, y, x-1, y, grid) ||\r\n isEqualNeighbor(x, y, x+1, y, grid) ||\r\n isEqualNeighbor(x, y, x, y-1, grid) ||\r\n isEqualNeighbor(x, y, x, y+1, grid) ||\r\n\r\n isDifferentNeighborTwo(x, y, x-2, y, grid) ||\r\n isDifferentNeighborTwo(x, y, x+2, y, grid) ||\r\n isDifferentNeighborTwo(x, y, x, y-2, grid) ||\r\n isDifferentNeighborTwo(x, y, x, y+2, grid)\r\n ) return false; else return true;\r\n}\r\n\r\nfunction isOkGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (!isOkCell(x, y, grid)) return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction fillCell(x, y, grid, color) {\r\n if (x < 0 || y < 0) return;\r\n if (x >= grid.length || y >= grid[x].length) return;\r\n if (grid[x][y] != '.') return;\r\n grid[x][y] = color;\r\n}\r\n\r\nfunction fillNeighborCells(x, y, grid) {\r\n if (grid[x][y] == 'R') {\r\n fillCell(x-1, y, grid, 'W');\r\n fillCell(x+1, y, grid, 'W');\r\n fillCell(x, y-1, grid, 'W');\r\n fillCell(x, y+1, grid, 'W');\r\n } else {\r\n fillCell(x-1, y, grid, 'R');\r\n fillCell(x+1, y, grid, 'R');\r\n fillCell(x, y-1, grid, 'R');\r\n fillCell(x, y+1, grid, 'R');\r\n }\r\n}\r\n\r\nfunction isGridComplete(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (grid[x][y] == '.') return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction fillGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n fillNeighborCells(x, y, grid);\r\n }\r\n }\r\n}\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n const testCases = [];\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x, y] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n }\r\n \r\n testCases.push({ x, y, grid });\r\n }\r\n \r\n testCases.forEach((testCase) => {\r\n if (isOkGrid(testCase.grid)) {\r\n testCase.isOk = true;\r\n } else {\r\n testCase.isOk = false;\r\n }\r\n });\r\n\r\n testCases.forEach((testCase) => {\r\n if (testCase.isOk) {\r\n fillGrid(testCase.grid);\r\n }\r\n });\r\n\r\n testCases.forEach((testCase) => {\r\n if (testCase.isOk) {\r\n console.log('YES');\r\n printGrid(testCase.grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n });\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction isDifferentNeighborTwo(c1, c2) {\r\n if (!c1 || !c2 || c1 == '.' || c2 == '.') return false;\r\n if (c1 != c2) return true; else return false;\r\n}\r\n\r\nfunction isEqualNeighbor(c1, c2) {\r\n if (!c1 || !c2 || c1 == '.' || c2 == '.') return false;\r\n if (c1 == c2) return true; else return false;\r\n}\r\n\r\nfunction isOkGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n for (let i = -2; i <= 2; i = i + 4) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length)\r\n if (isDifferentNeighborTwo(grid[x][y], grid[x2][y]))\r\n return false;\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid.length)\r\n if (isDifferentNeighborTwo(grid[x][y], grid[x][y2]))\r\n return false;\r\n }\r\n for (let i = -1; i <= 1; i = i + 2) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length)\r\n if (isEqualNeighbor(grid[x][y], grid[x2][y]))\r\n return false;\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid.length)\r\n if (isEqualNeighbor(grid[x][y], grid[x][y2]))\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction isGridComplete(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (grid[x][y] == '.') return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x, y] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n }\r\n\r\n if (isOkGrid(grid)) {\r\n let color = '.';\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (grid[x][y] == 'R') {\r\n color = 'W';\r\n } else {\r\n color = 'R';\r\n }\r\n for (let i = -1; i <= 1; i = i + 2) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length) {\r\n if (grid[x2][y] == '.')\r\n grid[x2][y] = color;\r\n }\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid[x].length) {\r\n if (grid[x][y2] == '.')\r\n grid[x][y2] = color;\r\n }\r\n }\r\n }\r\n }\r\n console.log('YES');\r\n printGrid(grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n\r\nfunction isDifferentNeighborTwo(c1, c2) {\r\n if (!c1 || !c2 || c1 == '.' || c2 == '.') return false;\r\n if (c1 != c2) return true; else return false;\r\n}\r\n\r\nfunction isEqualNeighbor(c1, c2) {\r\n if (!c1 || !c2 || c1 == '.' || c2 == '.') return false;\r\n if (c1 == c2) return true; else return false;\r\n}\r\n\r\nfunction isOkGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n for (let i = -2; i <= 2; i = i + 4) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length)\r\n if (isDifferentNeighborTwo(grid[x][y], grid[x2][y]))\r\n return false;\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid.length)\r\n if (isDifferentNeighborTwo(grid[x][y], grid[x][y2]))\r\n return false;\r\n }\r\n for (let i = -1; i <= 1; i = i + 2) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length)\r\n if (isEqualNeighbor(grid[x][y], grid[x2][y]))\r\n return false;\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid.length)\r\n if (isEqualNeighbor(grid[x][y], grid[x][y2]))\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction isGridComplete(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (grid[x][y] == '.') return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nfunction printGrid(grid) {\r\n for (let x = 0; x < grid.length; x++) {\r\n console.log(grid[x].join(''));\r\n }\r\n}\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n const [x, y] = readline().split(\" \").map(n => parseInt(n));\r\n const grid = [];\r\n\r\n for (let j = 0; j < x; j++) {\r\n const line = readline().split(\"\");\r\n grid.push(line);\r\n }\r\n\r\n if (isOkGrid(grid)) {\r\n let color = '.';\r\n for (let x = 0; x < grid.length; x++) {\r\n for (let y = 0; y < grid[x].length; y++) {\r\n if (grid[x][y] == 'R') {\r\n color = 'W';\r\n } else {\r\n color = 'R';\r\n }\r\n for (let i = -1; i <= 1; i = i + 2) {\r\n const x2 = x + i;\r\n if (x2 >= 0 && x2 < grid.length) {\r\n grid[x2][y] = color;\r\n }\r\n const y2 = y + i;\r\n if (y2 >= 0 && y2 < grid[x].length) {\r\n grid[x][y2] = color;\r\n }\r\n }\r\n }\r\n }\r\n console.log('YES');\r\n printGrid(grid);\r\n } else {\r\n console.log('NO');\r\n }\r\n }\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar dy = [-1,0,1,0];\r\n\tvar dx = [0,-1,0,1];\r\n\twhile(hasNext()){\r\n\t\tvar H = nextInt();\r\n\t\tvar W = nextInt();\r\n\t\tvar s = new Array(H);\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\ts[i] = nextCharArray();\r\n\t\t}\r\n\t\tvar queue = [];\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\tfor(var j = 0; j < W; j++){\r\n\t\t\t\tif(s[i][j] != \".\"){\r\n\t\t\t\t\tqueue.push([i,j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(queue.length == 0){\r\n\t\t\tqueue.push([0,0]);\r\n\t\t}\r\n\t\twhile(queue.length > 0){\r\n\t\t\tvar tmp = queue.shift();\r\n\t\t\tvar y = tmp[0];\r\n\t\t\tvar x = tmp[1];\r\n\t\t\tfor(var j = 0; j < dy.length; j++){\r\n\t\t\t\tvar nextY = y + dy[j];\r\n\t\t\t\tvar nextX = x + dx[j];\r\n\t\t\t\tif(nextY >= 0 && nextY < H && nextX >= 0 && nextX < W){\r\n\t\t\t\t\tif(s[nextY][nextX] == \".\"){\r\n\t\t\t\t\t\tif(s[y][x] == \"R\"){\r\n\t\t\t\t\t\t\ts[nextY][nextX] = \"W\";\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\ts[nextY][nextX] = \"R\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tqueue.push([nextY, nextX]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar isOK = true;\r\n\t\tfor(var i = 0; i < H - 1; i++){\r\n\t\t\tfor(var j = 0; j < W; j++){\r\n\t\t\t\tif(s[i][j] == s[i + 1][j]){\r\n\t\t\t\t\tisOK = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\tfor(var j = 0; j < W - 1; j++){\r\n\t\t\t\tif(s[i][j] == s[i][j + 1]){\r\n\t\t\t\t\tisOK = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout((isOK) ? \"Yes\" : \"No\");\r\n\t\tif(isOK){\r\n\t\t\tfor(var i = 0; i < H; i++){\r\n\t\t\t\tmyout(myconv(s[i], 0));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar dy = [-1,0,1,0];\r\n\tvar dx = [0,-1,0,1];\r\n\twhile(hasNext()){\r\n\t\tvar H = nextInt();\r\n\t\tvar W = nextInt();\r\n\t\tvar s = new Array(H);\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\ts[i] = nextCharArray();\r\n\t\t}\r\n\t\tvar queue = [];\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\tfor(var j = 0; j < W; j++){\r\n\t\t\t\tif(s[i][j] != \".\"){\r\n\t\t\t\t\tqueue.push([i,j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\twhile(queue.length > 0){\r\n\t\t\tvar tmp = queue.shift();\r\n\t\t\tvar y = tmp[0];\r\n\t\t\tvar x = tmp[1];\r\n\t\t\tfor(var j = 0; j < dy.length; j++){\r\n\t\t\t\tvar nextY = y + dy[j];\r\n\t\t\t\tvar nextX = x + dx[j];\r\n\t\t\t\tif(nextY >= 0 && nextY < H && nextX >= 0 && nextX < W){\r\n\t\t\t\t\tif(s[nextY][nextX] == \".\"){\r\n\t\t\t\t\t\tif(s[y][x] == \"R\"){\r\n\t\t\t\t\t\t\ts[nextY][nextX] = \"W\";\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\ts[nextY][nextX] = \"R\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tqueue.push([nextY, nextX]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar isOK = true;\r\n\t\tfor(var i = 0; i < H - 1; i++){\r\n\t\t\tfor(var j = 0; j < W; j++){\r\n\t\t\t\tif(s[i][j] == s[i + 1][j]){\r\n\t\t\t\t\tisOK = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor(var i = 0; i < H; i++){\r\n\t\t\tfor(var j = 0; j < W - 1; j++){\r\n\t\t\t\tif(s[i][j] == s[i][j + 1]){\r\n\t\t\t\t\tisOK = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout((isOK) ? \"Yes\" : \"No\");\r\n\t\tif(isOK){\r\n\t\t\tfor(var i = 0; i < H; i++){\r\n\t\t\t\tmyout(myconv(s[i], 0));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}"}, {"source_code": "let i = \"\";\nprocess.stdin.on(\"data\", c => (i += c));\nprocess.stdin.on(\"end\", () => {\n\tconst { EOL } = require(\"os\");\n\tconst lines = i.split(EOL);\n\tsolve(lines);\n});\n\nfunction solve(lines) {\n\tconst t = lines[0];\n\tlet index = 1;\n\tfor (let i = 0; i < t; i++) {\n\t\tconst ij = lines[index++];\n\t\tconst [n, m] = ij.split(\" \").map(c => +c);\n\t\tlet map = { R: [], W: [], \".\": [] };\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tconst line = lines[index++];\n\t\t\tline.split(\"\").forEach((c, k) => {\n\t\t\t\tmap[c].push([(k + j) % 2, j, k]);\n\t\t\t});\n\t\t}\n\t\tlet rVal = -1;\n\t\tmap[\"R\"].forEach(element => {\n\t\t\tif (rVal === -1) {\n\t\t\t\trVal = element[0];\n\t\t\t} else if (element[0] !== rVal) {\n\t\t\t\trVal = -2;\n\t\t\t}\n\t\t});\n\t\tlet wVal = -1;\n\t\tmap[\"W\"].forEach(element => {\n\t\t\tif (wVal === -1) {\n\t\t\t\twVal = element[0];\n\t\t\t} else if (element[0] !== wVal) {\n\t\t\t\twVal = -2;\n\t\t\t}\n\t\t});\n\t\tif (rVal === -2 || wVal === -2 || rVal === wVal) {\n\t\t\tconsole.log(\"NO\");\n\t\t} else {\n\t\t\tconsole.log(\"YES\");\n\t\t\tif (rVal === -1) {\n if(wVal === 1)\n\t\t\t\t rVal = 0;\n else \n rVal = 1;\n\t\t\t}\n\t\t\tfor (let l = 0; l < n; l++) {\n\t\t\t\tlet res = \"\";\n\t\t\t\tfor (let c = 0; c < m; c++) {\n\t\t\t\t\tif (rVal === (c + l) % 2) {\n\t\t\t\t\t\tres += \"R\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres += \"W\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconsole.log(res);\n\t\t\t}\n\t\t}\n\t}\n}\n"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n solve(lines); \n});\n\nfunction solve(lines){ \n const t = lines[0];\n let index = 1;\n for(let i =0; i < t; i++) {\n const ij = lines[index++];\n const [ n, m ] = ij.split(\" \").map(c=>+c);\n let map = { \"R\": [], \"W\": [], \".\": [] };\n for(let j = 0; j < n; j++) {\n const line = lines[index++];\n line.split(\"\").forEach((c, k) => {\n map[c].push([(k+j)%2 ,j, k]);\n \n });\n\n }\n let rVal = -1;\n map[\"R\"].forEach((element) => {\n if(rVal === -1) {\n rVal = element[0];\n } else if(element[0] !== rVal){\n rVal = -2;\n }\n });\n let wVal = -1;\n map[\"W\"].forEach((element) => {\n if(wVal === -1) {\n wVal = element[0];\n } else if(element[0] !== wVal){\n wVal = -2;\n }\n });\n if(rVal === -2 || wVal === -2 || rVal === wVal) {\n console.log(\"NO\")\n } else {\n console.log(\"YES\");\n for(let l = 0; l < n ; l++){\n let res = \"\";\n for(let c = 0; c < m ; c++) {\n if(rVal === (c+l)%2) {\n res+=\"R\";\n } else {\n res+=\"W\";\n }\n }\n console.log(res);\n }\n }\n }\n}"}], "src_uid": "12f35743f482b68e3156a45d6ac5bb14"} {"nl": {"description": "This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine.The main element of this machine are $$$n$$$ rods arranged along one straight line and numbered from $$$1$$$ to $$$n$$$ inclusive. Each of these rods must carry an electric charge quantitatively equal to either $$$1$$$ or $$$-1$$$ (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.More formally, the rods can be represented as an array of $$$n$$$ numbers characterizing the charge: either $$$1$$$ or $$$-1$$$. Then the condition must hold: $$$a_1 - a_2 + a_3 - a_4 + \\ldots = 0$$$, or $$$\\sum\\limits_{i=1}^n (-1)^{i-1} \\cdot a_i = 0$$$.Sparky charged all $$$n$$$ rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has $$$q$$$ questions. In the $$$i$$$th question Sparky asks: if the machine consisted only of rods with numbers $$$l_i$$$ to $$$r_i$$$ inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.Help your friends and answer all of Sparky's questions!", "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 two positive integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\le 3 \\cdot 10^5$$$) — the number of rods and the number of questions. The second line of each test case contains a non-empty string $$$s$$$ of length $$$n$$$, where the charge of the $$$i$$$-th rod is $$$1$$$ if $$$s_i$$$ is the \"+\" symbol, or $$$-1$$$ if $$$s_i$$$ is the \"-\" symbol. Each next line from the next $$$q$$$ lines contains two positive integers $$$l_i$$$ ans $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$) — numbers, describing Sparky's questions. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer — the minimal number of rods that can be removed.", "sample_inputs": ["3\n14 1\n+--++---++-++-\n1 14\n14 3\n+--++---+++---\n1 14\n6 12\n3 10\n4 10\n+-+-\n1 1\n1 2\n1 3\n1 4\n2 2\n2 3\n2 4\n3 3\n3 4\n4 4"], "sample_outputs": ["2\n2\n1\n0\n1\n2\n1\n2\n1\n2\n1\n1\n2\n1"], "notes": "NoteIn the first test case for the first query you can remove the rods numbered $$$5$$$ and $$$8$$$, then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero.In the second test case: For the first query, we can remove the rods numbered $$$1$$$ and $$$11$$$, then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero. For the second query we can remove the rod numbered $$$9$$$, then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero. For the third query we can not remove the rods at all. "}, "positive_code": [{"source_code": "'use strict'\r\nvar os = require('os')\r\nfunction createInput(t) {\r\n const n = t.stdin || process.stdin,\r\n e = /-?\\d+/g,\r\n r = /-?\\d+(?:\\.\\d+)?/g\r\n let u = [],\r\n o = 0\r\n return {\r\n init: async function () {\r\n const t = []\r\n ;(u = await new Promise(e => {\r\n n.on('data', n => t.push(n)),\r\n n.on('end', function () {\r\n const n = t.join('').split(os.EOL)\r\n e(n)\r\n })\r\n })),\r\n (o = 0)\r\n },\r\n dried: function () {\r\n return o >= u.length\r\n },\r\n readLine: i,\r\n readLineAsNumber: function () {\r\n return Number(i())\r\n },\r\n readIntegersOfLine: function () {\r\n const t = i().match(e)\r\n return null == t ? [] : t.map(t => Number(t))\r\n },\r\n readNumsOfLine: function () {\r\n const t = i().match(r)\r\n return null == t ? [] : t.map(t => Number(t))\r\n },\r\n }\r\n function i() {\r\n return u[o++]\r\n }\r\n}\r\nfunction createOutput(t) {\r\n const n = t.stdout || process.stdout,\r\n e = t.encoding || 'ascii',\r\n r = t.outputBufferThreshold || 1 << 24,\r\n u = Buffer.alloc(r)\r\n let o = 0\r\n return {\r\n flush: i,\r\n print: function (t) {\r\n s('string' == typeof t ? t : t.toString())\r\n },\r\n println: function (t) {\r\n s(('string' == typeof t ? t : t.toString()).concat('\\n'))\r\n },\r\n }\r\n function i() {\r\n n.write(u.toString(e, 0, o)), (o = 0)\r\n }\r\n function s(t) {\r\n const s = Buffer.byteLength(t, e)\r\n r - o < s && (i(), s >= r) ? n.write(t) : (u.write(t, o, e), (o += s))\r\n }\r\n}\r\nfunction createInputAndOutput(t) {\r\n return {\r\n ...createInput({ stdin: t.stdin, encoding: t.encoding }),\r\n ...createOutput({\r\n stdout: t.stdout,\r\n encoding: t.encoding,\r\n outputBufferThreshold: t.outputBufferThreshold,\r\n }),\r\n }\r\n}\r\nasync function __main__(t, n, e = {}) {\r\n const r = createInputAndOutput(e)\r\n await Promise.all([r.init(), Promise.resolve(n && n())]),\r\n await t(r),\r\n r.flush()\r\n}\r\nconst MAX_N = 300010,\r\n sum = new Array(MAX_N)\r\n__main__(\r\n function (t) {\r\n const n = t.readLineAsNumber()\r\n sum[0] = 0\r\n for (let e = 1; e <= n; ++e) {\r\n const [n, e] = t.readIntegersOfLine(),\r\n r = t.readLine()\r\n for (let t = 0; t < n; ++t) {\r\n const n = r[t],\r\n e = (t + 1) & 1 ? ('+' === n ? 1 : -1) : '+' === n ? -1 : 1\r\n sum[t + 1] = sum[t] + e\r\n }\r\n for (let n = 1; n <= e; ++n) {\r\n const [n, e] = t.readIntegersOfLine(),\r\n r = (e - n + 1) & 1 ? 1 : sum[e] === sum[n - 1] ? 0 : 2\r\n t.println(r)\r\n }\r\n }\r\n },\r\n void 0,\r\n { outputBufferThreshold: 1 << 20 },\r\n)\r\n"}, {"source_code": "'use strict'\r\nvar os = require('os')\r\nfunction createInput(t) {\r\n const n = t.stdin || process.stdin,\r\n e = /-?\\d+/g,\r\n r = /-?\\d+(?:\\.\\d+)?/g\r\n let u = [],\r\n o = 0\r\n return {\r\n init: async function () {\r\n const t = []\r\n ;(u = await new Promise(e => {\r\n n.on('data', n => t.push(n)),\r\n n.on('end', function () {\r\n const n = t.join('').split(os.EOL)\r\n e(n)\r\n })\r\n })),\r\n (o = 0)\r\n },\r\n dried: function () {\r\n return o >= u.length\r\n },\r\n readLine: i,\r\n readLineAsNumber: function () {\r\n return Number(i())\r\n },\r\n readIntegersOfLine: function () {\r\n const t = i().match(e)\r\n return null == t ? [] : t.map(t => Number(t))\r\n },\r\n readNumsOfLine: function () {\r\n const t = i().match(r)\r\n return null == t ? [] : t.map(t => Number(t))\r\n },\r\n }\r\n function i() {\r\n return u[o++]\r\n }\r\n}\r\nfunction createOutput(t) {\r\n const n = t.stdout || process.stdout,\r\n e = t.encoding || 'ascii',\r\n r = t.outputBufferThreshold || 1 << 24,\r\n u = Buffer.alloc(r)\r\n let o = 0\r\n return {\r\n flush: i,\r\n print: function (t) {\r\n s('string' == typeof t ? t : t.toString())\r\n },\r\n println: function (t) {\r\n s(('string' == typeof t ? t : t.toString()).concat('\\n'))\r\n },\r\n }\r\n function i() {\r\n n.write(u.toString(e, 0, o)), (o = 0)\r\n }\r\n function s(t) {\r\n const s = Buffer.byteLength(t, e)\r\n r - o < s && (i(), s >= r) ? n.write(t) : (u.write(t, o, e), (o += s))\r\n }\r\n}\r\nfunction createInputAndOutput(t) {\r\n return {\r\n ...createInput({ stdin: t.stdin, encoding: t.encoding }),\r\n ...createOutput({\r\n stdout: t.stdout,\r\n encoding: t.encoding,\r\n outputBufferThreshold: t.outputBufferThreshold,\r\n }),\r\n }\r\n}\r\nasync function __main__(t, n, e = {}) {\r\n const r = createInputAndOutput(e)\r\n await Promise.all([r.init(), Promise.resolve(n && n())]),\r\n await t(r),\r\n r.flush()\r\n}\r\nconst MAX_N = 300010,\r\n sum = new Array(MAX_N)\r\n__main__(\r\n function (t) {\r\n const n = t.readLineAsNumber()\r\n sum[0] = 0\r\n for (let e = 1; e <= n; ++e) {\r\n const [n, e] = t.readIntegersOfLine(),\r\n r = t.readLine()\r\n for (let t = 0; t < n; ++t) {\r\n const n = r[t],\r\n e = (t + 1) & 1 ? ('+' === n ? 1 : -1) : '+' === n ? -1 : 1\r\n sum[t + 1] = sum[t] + e\r\n }\r\n for (let n = 1; n <= e; ++n) {\r\n const [n, e] = t.readIntegersOfLine(),\r\n r = (e - n + 1) & 1 ? 1 : sum[e] === sum[n - 1] ? 0 : 2\r\n t.println(r)\r\n }\r\n }\r\n },\r\n void 0,\r\n { outputBufferThreshold: 1 << 26 },\r\n)\r\n"}, {"source_code": "'use strict'\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n encoding\r\n outputBuffer\r\n outputBufferThreshold\r\n outputBufferSize\r\n lineIndex = 0\r\n lines = []\r\n constructor(t) {\r\n ;(this.outputBufferThreshold = t.outputBufferThreshold || 1 << 24),\r\n (this.outputBuffer = Buffer.alloc(this.outputBufferThreshold)),\r\n (this.encoding = t.encoding || 'ascii'),\r\n (this.outputBufferSize = 0)\r\n }\r\n flush() {\r\n const { encoding: t, outputBuffer: e, outputBufferSize: n } = this\r\n stdout.write(e.toString(t, 0, n)), (this.outputBufferSize = 0)\r\n }\r\n print(t) {\r\n const e = Buffer.byteLength(t, this.encoding)\r\n this.outputBufferThreshold - this.outputBufferSize < e &&\r\n (this.flush(), e >= this.outputBufferThreshold)\r\n ? stdout.write(t)\r\n : (this.outputBuffer.write(t, this.outputBufferSize, this.encoding),\r\n (this.outputBufferSize += e))\r\n }\r\n printNumber(t) {\r\n this.print(String(t))\r\n }\r\n println(t) {\r\n this.print(String(t).concat('\\n'))\r\n }\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const t = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), t\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const t = this.readLine().match(integerRegex)\r\n return null == t ? [] : t.map(t => Number(t))\r\n }\r\n readNumsOfLine() {\r\n const t = this.readLine().match(decimalRegex)\r\n return null == t ? [] : t.map(t => Number(t))\r\n }\r\n async init() {\r\n const t = await this.readLines()\r\n this.lines = t\r\n }\r\n readLines() {\r\n const t = []\r\n return new Promise(e => {\r\n stdin.on('data', e => t.push(e)),\r\n stdin.on('end', function () {\r\n const n = t.join('').split(os.EOL)\r\n e(n)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(t, e = {}) {\r\n const n = new InputAndOutput(e)\r\n await n.init(), await t(n), n.flush()\r\n}\r\nconst MAX_N = 300010,\r\n sum = new Array(MAX_N)\r\n__main__(function (t) {\r\n const e = t.readLineAsNumber()\r\n sum[0] = 0\r\n for (let n = 1; n <= e; ++n) {\r\n const [e, n] = t.readIntegersOfLine(),\r\n i = t.readLine()\r\n for (let t = 0; t < e; ++t) {\r\n const e = i[t],\r\n n = (t + 1) & 1 ? ('+' === e ? 1 : -1) : '+' === e ? -1 : 1\r\n sum[t + 1] = sum[t] + n\r\n }\r\n for (let e = 1; e <= n; ++e) {\r\n const [e, n] = t.readIntegersOfLine(),\r\n i = (n - e + 1) & 1 ? 1 : sum[n] === sum[e - 1] ? 0 : 2\r\n t.println(i)\r\n }\r\n }\r\n})\r\n"}, {"source_code": "'use strict'\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n encoding\r\n outputBuffer\r\n outputBufferThreshold\r\n outputBufferSize\r\n lineIndex = 0\r\n lines = []\r\n constructor(t) {\r\n ;(this.outputBufferThreshold = t.outputBufferThreshold || 1 << 24),\r\n (this.outputBuffer = Buffer.alloc(this.outputBufferThreshold)),\r\n (this.encoding = t.encoding || 'ascii'),\r\n (this.outputBufferSize = 0)\r\n }\r\n flush() {\r\n const { encoding: t, outputBuffer: e, outputBufferSize: n } = this\r\n stdout.write(e.toString(t, 0, n)), (this.outputBufferSize = 0)\r\n }\r\n print(t) {\r\n const e = Buffer.byteLength(t, this.encoding)\r\n this.outputBufferThreshold - this.outputBufferSize < e &&\r\n (this.flush(), e >= this.outputBufferThreshold)\r\n ? stdout.write(t)\r\n : (this.outputBuffer.write(t, this.outputBufferSize, this.encoding),\r\n (this.outputBufferSize += e))\r\n }\r\n printNumber(t) {\r\n this.print(String(t))\r\n }\r\n println(t) {\r\n stdout.write(String(t).concat('\\n'))\r\n }\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const t = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), t\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const t = this.readLine().match(integerRegex)\r\n return null == t ? [] : t.map(t => Number(t))\r\n }\r\n readNumsOfLine() {\r\n const t = this.readLine().match(decimalRegex)\r\n return null == t ? [] : t.map(t => Number(t))\r\n }\r\n async init() {\r\n const t = await this.readLines()\r\n this.lines = t\r\n }\r\n readLines() {\r\n const t = []\r\n return new Promise(e => {\r\n stdin.on('data', e => t.push(e)),\r\n stdin.on('end', function () {\r\n const n = t.join('').split(os.EOL)\r\n e(n)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(t, e = {}) {\r\n const n = new InputAndOutput(e)\r\n await n.init(), await t(n), n.flush()\r\n}\r\nconst MAX_N = 300010,\r\n sum = new Array(MAX_N)\r\n__main__(function (t) {\r\n const e = t.readLineAsNumber()\r\n sum[0] = 0\r\n for (let n = 1; n <= e; ++n) {\r\n const [e, n] = t.readIntegersOfLine(),\r\n i = t.readLine()\r\n for (let t = 0; t < e; ++t) {\r\n const e = i[t],\r\n n = (t + 1) & 1 ? ('+' === e ? 1 : -1) : '+' === e ? -1 : 1\r\n sum[t + 1] = sum[t] + n\r\n }\r\n const s = []\r\n for (let e = 1; e <= n; ++e) {\r\n const [e, n] = t.readIntegersOfLine(),\r\n i = (n - e + 1) & 1 ? 1 : sum[n] === sum[e - 1] ? 0 : 2\r\n s.push(i)\r\n }\r\n t.println(s.join('\\n'))\r\n }\r\n})\r\n"}, {"source_code": "'use strict'\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const n = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), n\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const n = this.readLine().match(integerRegex)\r\n return null == n ? [] : n.map(n => Number(n))\r\n }\r\n readNumsOfLine() {\r\n const n = this.readLine().match(decimalRegex)\r\n return null == n ? [] : n.map(n => Number(n))\r\n }\r\n print(n) {\r\n stdout.write(String(n))\r\n }\r\n println(n) {\r\n stdout.write(String(n)), stdout.write('\\n')\r\n }\r\n async init() {\r\n const n = await this.readLines()\r\n this.lines = n\r\n }\r\n readLines() {\r\n const n = []\r\n return new Promise(e => {\r\n stdin.on('data', e => n.push(e)),\r\n stdin.on('end', function () {\r\n const t = n.join('').split(os.EOL)\r\n e(t)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(n) {\r\n const e = new InputAndOutput()\r\n await e.init(), n(e)\r\n}\r\nconst MAX_N = 300010,\r\n sum = new Array(MAX_N)\r\n__main__(function (n) {\r\n const e = n.readLineAsNumber()\r\n sum[0] = 0\r\n for (let t = 1; t <= e; ++t) {\r\n const [e, t] = n.readIntegersOfLine(),\r\n s = n.readLine()\r\n for (let n = 0; n < e; ++n) {\r\n const e = s[n],\r\n t = (n + 1) & 1 ? ('+' === e ? 1 : -1) : '+' === e ? -1 : 1\r\n sum[n + 1] = sum[n] + t\r\n }\r\n const i = []\r\n for (let e = 1; e <= t; ++e) {\r\n const [e, t] = n.readIntegersOfLine(),\r\n s = (t - e + 1) & 1 ? 1 : sum[t] === sum[e - 1] ? 0 : 2\r\n i.push(s)\r\n }\r\n n.println(i.join('\\n'))\r\n }\r\n})\r\n"}], "negative_code": [], "src_uid": "3f7f29e57cc03be8ff1251ab42738739"} {"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$$$ — 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$$$) — 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$$$) — 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 — 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": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n solve();\r\n }\r\n}\r\nfunction solve() {\r\n let [l, r, a] = readLine().split(\" \").map(i => BigInt(i));\r\n let ans = r / a + r % a;\r\n let m = r / a * a - 1n;\r\n if (m >= l) ans = Math.max(Number(ans), Number(m / a + m % a));\r\n console.log(Number(ans));\r\n}\r\n"}, {"source_code": "var m = function(a){\n return Math.floor(a); \n};\nlet stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n var l = k[0], r = k[1], a = k[2];\n var x = Math.floor((r + 1) / a) * a - 1;\n console.log(l <= x ? m(x / a) + m(x % a) : m(r / a) + m(r % a));\n }\n});"}, {"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nmodule.exports = E;\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\n\nconst EPS = 1e-6;\n\nlet f = (a, x)=>{\n return Math.floor(x/a) + (x%a);\n};\nconst calc = (l, r, a)=>{\n let ans = f(a, l);\n ans = Math.max(ans, f(a, r));\n let R = r-r%a;\n if (R>=l && R<=r)\n ans = Math.max(ans, f(a, R));\n R--;\n if (R>=l && R<=r)\n ans = Math.max(ans, f(a, R));\n R-=2;\n if (R>=l && R<=r)\n ans = Math.max(ans, f(a, R));\n return ans;\n};\n\nfunction main() {\n let T = +readline()\n while (T--){\n let [l, r, a] = ra();\n print(calc(l, r, a));\n }\n}\n\nE.calc = calc;"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n solve();\r\n }\r\n}\r\nfunction solve() {\r\n let [l, r, a] = readLine().split(\" \").map(i => BigInt(i));\r\n let ans = r / a + r % a;\r\n let m = r / a * a - 1n;\r\n if (m >= l) ans = Math.max(Number(ans), Number(m / a + m % a));\r\n console.log(Number(ans));\r\n}\r\n"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const [left, right, a] = lines[l++].trim().split(' ').map(Number)\r\n output[i] = solve(left, right, a)\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(left, right, a) {\r\n // for (let i = left; i <= right; i++) {\r\n // console.log(i, cal(i, a))\r\n // }\r\n\r\n const r1 = left % a\r\n const k1 = Math.floor(left / a)\r\n const r2 = right % a\r\n const k2 = Math.floor(right / a)\r\n let ans = cal(right, a)\r\n if (right - r2 - 1 >= left) {\r\n ans = Math.max(ans, cal(right - r2 - 1, a))\r\n }\r\n return ans\r\nconsole.log(k1, k2)\r\n if (k2 - k1 > 1) return a - 1\r\n\r\n if (k1 === k2) {\r\n const v1 = cal(left, a)\r\n const v2 = cal(right, a)\r\n return get(v1, v2, a)\r\n } else {\r\n // k1 + 1 = k2\r\n const v1 = cal(left, a)\r\n const v2 = cal(left - r1 + a, a)\r\n const v3 = cal(right - r2, a)\r\n const v4 = cal(right, a)\r\n console.log(v1, v2, v3, v4)\r\n return Math.max(get(v1, v2, a), get(v3, v4, a))\r\n }\r\n}\r\nfunction get(v1, v2, a) {\r\n return v1 <= v2 ? v2 : a - 1\r\n}\r\nfunction cal(x, a) {\r\n const f = Math.floor(x / a) + x % a\r\n return f\r\n}\r\n"}, {"source_code": "function solve() {\r\n const [l, r, a] = readArray(Number);\r\n const modR = r % a;\r\n if (modR === a - 1) {\r\n write(f(r, a));\r\n return;\r\n }\r\n const x = r - modR - 1;\r\n if (x < l) {\r\n write(f(r, a));\r\n return;\r\n }\r\n write(f(x, a));\r\n}\r\n\r\nfunction f(x, a) {\r\n return (Math.floor(x / a) + x % a);\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction pDivCount(n) {\r\n let ans = 0;\r\n let i = 1;\r\n while(n > 1) {\r\n i++;\r\n while(n % i === 0) {\r\n ans++;\r\n n = Math.floor(n / i);\r\n }\r\n }\r\n return ans;\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (a === 0) {\r\n return b;\r\n }\r\n return gcd(b % a, a);\r\n}\r\n\r\nfunction lcm(a, b) {\r\n return Math.floor(a / gcd(a, b)) * b;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n}\r\ninit();\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "var t = readline();\r\n \r\nfor (var i = 0; i < t; i++) {\r\n var k = readline().split(' ').map(Number);\r\n var l = k[0], r = k[1], a = k[2];\r\n var b = Math.floor(r / a) + r % a;\r\n var c = Math.floor(r / a) * a - 1;\r\n var d = Math.floor(c / a) + c % a;\r\n if (l <= c) b = Math.max(b, d);\r\n print(b);\r\n}"}], "negative_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n solve();\r\n }\r\n}\r\nfunction solve() {\r\n let [l, r, a] = readLine().split(\" \").map(i => parseInt(i));\r\n let ans = parseInt(r / a) + r % a;\r\n let m = parseInt(r / a) * a - 1;\r\n if (m >= l) ans = Math.max(ans, parseInt(m / a) + m % a);\r\n console.log(ans);\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n solve();\r\n }\r\n}\r\nfunction solve() {\r\n let [l, r, a] = readLine().split(\" \").map(i => parseInt(i));\r\n let R = r;\r\n if (r % a == 0) r--;\r\n let q = parseInt(r / a);\r\n if (r < l) {\r\n console.log(parseInt(R / a) + R % a);\r\n return;\r\n }\r\n if (r % a < parseInt(a / 2)) {\r\n if ((q * a - 1) >= l && (q * a - 1) <= R) {\r\n r = q * a - 1;\r\n console.log(parseInt(r / a) + r % a);\r\n return;\r\n } else {\r\n console.log(parseInt(r / a) + r % a)\r\n return;\r\n }\r\n } else {\r\n console.log(parseInt(r / a) + r % a);\r\n return;\r\n }\r\n}\r\n"}, {"source_code": "var t = readline();\r\n \r\nfor (var i = 0; i < t; i++) {\r\n var a = readline().split(' ').map(Number);\r\n var b = Math.floor(a[1] / a[2]);\r\n var c = (Math.floor(a[1] / a[2]) - 1 + a[2] - 1);\r\n var r = Math.max(b + a[1] % a[2], c);\r\n if (a[0] <= a[2]) r * Math.floor(a[1] / a[2]) - 1;\r\n else r * Math.floor(a[1] / a[2]) + a[1] % a[2];\r\n print(r);\r\n}"}], "src_uid": "681ee82880ddd0de907aac2ccad8fc04"} {"nl": {"description": "Polycarp had an array $$$a$$$ of $$$3$$$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $$$b$$$ of $$$7$$$ integers.For example, if $$$a = \\{1, 4, 3\\}$$$, then Polycarp wrote out $$$1$$$, $$$4$$$, $$$3$$$, $$$1 + 4 = 5$$$, $$$1 + 3 = 4$$$, $$$4 + 3 = 7$$$, $$$1 + 4 + 3 = 8$$$. After sorting, he got an array $$$b = \\{1, 3, 4, 4, 5, 7, 8\\}.$$$Unfortunately, Polycarp lost the array $$$a$$$. He only has the array $$$b$$$ left. Help him to restore the array $$$a$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) — the number of test cases. Each test case consists of one line which contains $$$7$$$ integers $$$b_1, b_2, \\dots, b_7$$$ ($$$1 \\le b_i \\le 10^9$$$; $$$b_i \\le b_{i+1}$$$). Additional constraint on the input: there exists at least one array $$$a$$$ which yields this array $$$b$$$ as described in the statement.", "output_spec": "For each test case, print $$$3$$$ integers — $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$. If there can be several answers, print any of them.", "sample_inputs": ["5\n1 3 4 4 5 7 8\n1 2 3 4 5 6 7\n300000000 300000000 300000000 600000000 600000000 600000000 900000000\n1 1 2 999999998 999999999 999999999 1000000000\n1 2 2 3 3 4 5"], "sample_outputs": ["1 4 3\n4 1 2\n300000000 300000000 300000000\n999999998 1 1\n1 2 2"], "notes": "NoteThe subsequence of the array $$$a$$$ is a sequence that can be obtained from $$$a$$$ by removing zero or more of its elements.Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length $$$3$$$ has exactly $$$7$$$ different non-empty subsequences."}, "positive_code": [{"source_code": "\r\n'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n \r\n \r\nfunction main() {\r\n var x = readline();\r\n for (var i = 0; i < x; i++) {\r\n var num = readline().split(\" \").map(x => parseInt(x));\r\n const a = num[0], b = num[1], c = num[num.length - 1] - a - b;\r\n console.log(`${a} ${b} ${c}`);\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n \r\n \r\nfunction main() {\r\n var x = readline();\r\n for (var i = 0; i < x; i++) {\r\n var num = readline().split(\" \").map(x => parseInt(x));\r\n \r\n console.log(d(num).join(' '));\r\n }\r\n}\r\nfunction d (ms) {\r\n var n = ms[ms.length - 1];\r\n var p = ms[0];\r\n for (var i = 1; ms.length > i; i++) {\r\n for (var j = i; ms.length > j; j++) {\r\n if (ms[j] + ms[i] === n - p) {\r\n return [p, ms[j], ms[i]]\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "const readline = require(\"readline\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false\r\n});\r\n\r\nlet c = 0;\r\n\r\nrl.on(\"line\", (array) => {\r\n c++;\r\n if(c == 1) return;\r\n [a, b, c, d, e, f, g] = array.split(\" \");\r\n\r\n let third = ((parseInt(c) == parseInt(a) + parseInt(b)) ? d : c);\r\n\r\n console.log(`${a} ${b} ${third}`);\r\n return;\r\n})"}, {"source_code": "const readline = require(\"readline\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet c = 0;\r\n\r\nrl.on(\"line\", (array) => {\r\n c++;\r\n if(c == 1) return;\r\n [a, b, c, d, e, f, g] = array.split(\" \");\r\n\r\n let third = ((parseInt(c) == parseInt(a) + parseInt(b)) ? d : c);\r\n\r\n console.log(`${a} ${b} ${third}`);\r\n return;\r\n});\r\n"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n var a = new Array(3);\n a[0] = k[6] - k[5];\n a[2] = k[4] - a[0];\n a[1] = k[6] - a[0] - a[2];\n var s = '';\n for(j = 0; j < 3; j++){\n s += a[j] + ' ';\n }\n console.log(s);\n }\n});\n"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n var a = new Array(3);\n a[0] = k[6] - k[5];\n a[2] = k[4] - a[0];\n a[1] = k[6] - a[0] - a[2];\n var s = '';\n for(j = 0; j < 3; j++){\n s += a[j] + ' ';\n }\n console.log(s);\n }\n});"}, {"source_code": "\r\n'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// FPT------Regional ^^ Let's go\r\n \r\n \r\nfunction main() {\r\n var x = readline();\r\n for (var i = 0; i < x; i++) {\r\n var num = readline().split(\" \").map(x => parseInt(x));\r\n const a = num[0], b = num[1], c = num[num.length - 1] - a - b;\r\n console.log(`${a} ${b} ${c}`);\r\n }\r\n}\r\n"}, {"source_code": "\n// READLINE TEMPLATE\n//\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nconst print = console.log\n\n// READLINE TEMPLATE\n\nfunction findSum(arr,target) {\n const l1 = arr.length\n const l2 = l1 - 1\n for (let i = 0; i < l2; i++) {\n const a = arr[i]\n if (a > target) break\n const diff = target - a\n for (let j = i + 1; j < l1; j++) {\n const b = arr[j]\n if (b === diff) return [a,b]\n if (b > diff) break\n }\n }\n}\n\nfunction findOriginal(data) {\n const sorted = data.sort((a,b) => a-b)\n const a = sorted.shift()\n const a_b_c = sorted.pop()\n const b_c = a_b_c - a\n const [b,c] = findSum(sorted,b_c)\n return [a,b,c]\n}\n\nfunction main() {\n const n = parseInt(readline()) \n for (let i = 0; i < n; i++) {\n const a = readline().split(\" \").map(n => parseInt(n))\n print(...findOriginal(a))\n }\n}\n\n\n\n\n\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst b = rna();\r\n\t\tx = b[0];\r\n\t\ty = b[1];\r\n\t\tz = b[6] - x - y;\r\n\r\n\t\tconsole.log(x, y, z);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let noOfTestCases = Number(readline());\r\n let testCaseArray = [];\r\n for (let i = 0; i < noOfTestCases; i++) {\r\n testCaseArray.push(readline().split(\" \").map(x => Number(x)));\r\n }\r\n \r\n for (let i = 0; i < noOfTestCases; i++) {\r\n findLostArray(testCaseArray[i])\r\n }\r\n}\r\n\r\n\r\n\r\nfunction findLostArray(B) {\r\n console.log(B[0], B[1], B[6] - B[0] - B[1])\r\n}\r\n\r\n\r\n"}, {"source_code": " // your code goes here\r\n const fs = require('fs');\r\n const input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\n let currentline = 0;\r\n function readline(){\r\n return input[currentline++];\r\n }\r\n var T = readline();\r\n for(var q = 1;q<=T;q++) {\r\n var a = readline().split(\" \").map(x => parseInt(x));\r\n var f = []\r\n var dist = []\r\n for(var i=0;i {\r\n if (n == null) {\r\n n = parseInt(line)\r\n m = n\r\n } else if (m>0) {\r\n m--;\r\n a.push(line.split(' ').map(e=>parseInt(e)))\r\n } \r\n if (m == 0) {\r\n readline.close();\r\n main();\r\n } \r\n});\r\n\r\nfunction main(){\r\n a.forEach(e=> {\r\n let x = e.pop();\r\n for (let i = 0; i < e.length-2; i++)\r\n for (let j = i+1; j < e.length-1; j++)\r\n for (let k = j+1; k < e.length; k++)\r\n if (e[i]+e[j]+e[k] == x) {\r\n return console.log([e[i],e[j],e[k]].join(\" \"));\r\n }\r\n });\r\n}\r\n// main();"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n console.log(solve());\r\n }\r\n}\r\nfunction solve() {\r\n let arr = readLine().split(\" \").map(i => parseInt(i));\r\n return `${arr[0]} ${arr[1]} ${arr[6]-arr[0]-arr[1]}`;\r\n}\r\n"}, {"source_code": "let buffer = '';\r\nprocess.stdin.on('data', c => buffer += c);\r\nprocess.stdin.on('end', () => {\r\n const { EOL } = require('os');\r\n const lines = buffer.split(EOL);\r\n lines.pop();\r\n\r\n main(lines);\r\n});\r\n\r\nfunction main(lines) {\r\n let T = Number(lines[0]);\r\n let index = 1;\r\n let arr;\r\n\r\n while (T--) {\r\n arr = lines[index++].split(' ').map(Number);\r\n solve(arr);\r\n }\r\n}\r\n\r\nfunction solve(arr) {\r\n arr.sort((a, b) => a - b);\r\n console.log(`${arr[0]} ${arr[1]} ${arr[6] - arr[1] - arr[0]}`);\r\n}"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet a = nl.nums();\n\t\tlet x = a[0];\n\t\tlet y = a[1];\n\t\tlet z = a[6] - x - y;\n\t\tans.push(`${x} ${y} ${z}`);\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nfunction print(x) {\r\n console.log(x);\r\n}\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n var t = parseInt(readline())\r\n\r\n while (t--) {\r\n var input2 = readline()\r\n .split(\" \")\r\n .map((data) => +data)\r\n\r\n var max = Math.max(...input2)\r\n\r\n var a1 = 0;\r\n var a2 = 0;\r\n var a3 = 0;\r\n\r\n for (var i = 0; i < input2.length - 2; i++) {\r\n for (var j = i + 1; j < input2.length - 1; j++) {\r\n for (var k = j + 1; k < input2.length; k++) {\r\n if (input2[i] + input2[j] + input2[k] === max) {\r\n a1 = input2[i]\r\n a2 = input2[j]\r\n a3 = input2[k]\r\n }\r\n }\r\n }\r\n }\r\n print(a1 + \" \" + a2 + \" \" + a3)\r\n }\r\n}"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve(arr) {\r\n const [min1, min2] = arr\r\n const max = arr.pop()\r\n console.log(min1, min2, max - min1 - min2)\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar list = nextIntArray(7);\r\n\t\tlist.sort(function(a,b){\r\n\t\t\treturn a - b;\r\n\t\t});\r\n\t\t\r\n\t\tvar min1 = list[0];\r\n\t\tvar min2 = list[1];\r\n\t\tvar max = list[6] - min1 - min2;\r\n\t\tmyout(min1 + \" \" + min2 + \" \" + max);\r\n\t}\r\n}\r\n"}, {"source_code": "var len = readline();\r\nfor(var i=0;i<+len;i++)\r\n{\r\n var inputData = readline().split(' ');\r\n var result=[];\r\nresult.push(+inputData[inputData.length-1] -(+inputData[inputData.length-2]) );\r\nresult.push(+inputData[inputData.length-1] -(+inputData[inputData.length-3]) );\r\nresult.push(+inputData[inputData.length-1] - (result[0]+result[1]));\r\nprint(result.join(' '));\r\n}\r\n"}, {"source_code": "var tests = parseInt(readline());\r\nfor (var t=0; t < tests; t++) {\r\n var a = readline().split(' ').map(x=>parseInt(x));\r\n var ans = [a[0], a[1], a[6]-(a[0]+a[1])];\r\n print(ans.join(' '));\r\n}"}, {"source_code": "// https://codeforces.com/contest/1618/problem/0\n\"use strict\";\n\nfunction answer(s) {\n const arr = s.split(' ');\n const maxSum = arr[arr.length - 1];\n const minA = arr[0];\n const minB = arr[1];\n const lastElement = maxSum - minA - minB;\n return [minA, minB, lastElement].join(' ');\n}\n\nconst nQueues = this.readline().split(\" \");\n\nfor (let i = 0; i < nQueues; i++) {\n const s = this.readline();\n this.print(answer(s))\n}\n"}, {"source_code": "t = readline();\r\n\r\nwhile(t--) {\r\n var input = readline().split(\" \");\r\n var max = Math.max.apply(null, input);\r\n print(input[0] + ' ' + input[1] + ' ' + (max - input[0] - input[1]));\r\n}"}, {"source_code": "\"use strict\";\n\nfunction answer(s) {\n if (s.length > 10) return s[0] + (s.length - 2) + s[s.length - 1];\n return s;\n}\n\nconst nQueues = this.readline().split(\" \");\n\nfor (let i = 0; i < nQueues; i++) {\n const s = this.readline().split(\" \");\n s.sort((a, b) => a - b);\n const todos = s[s.length - 1];\n const a = s[0];\n const b = s[1];\n const c = todos - a - b;\n this.print([a, b, c].join(\" \"));\n}\n"}], "negative_code": [{"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n \r\n \r\nfunction main() {\r\n var x = readline();\r\n for (var i = 0; i < x; i++) {\r\n var num = readline().split(\" \").map(x => parseInt(x));\r\n \r\n console.log(d(num));\r\n }\r\n}\r\nfunction d (ms) {\r\n var n = ms[ms.length - 1];\r\n var p = ms[0];\r\n for (var i = 1; ms.length > i; i++) {\r\n for (var j = i; ms.length > j; j++) {\r\n if (ms[j] + ms[i] === n - p) {\r\n return [p, ms[j], ms[i]]\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n var x = readline();\r\n var num = readline().split(\" \").map(x => parseInt(x));\r\n \r\n console.log(d(num));\r\n}\r\nfunction d (ms) {\r\nvar n = ms[ms.length - 1];\r\nvar p = ms[0];\r\n for (var i = 1; ms.length > i; i++) {\r\n for (var j = i; ms.length > j; j++) {\r\n if (ms[j] + ms[i] === n - p) {\r\n return [p, ms[j], ms[i]]\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n var num = readline().split(\" \").map(x => parseInt(x));\r\n console.log(num)\r\n const ans = d(num);\r\n console.log(ans);\r\n}\r\nfunction d (ms) {\r\nvar n = ms[ms.length - 1];\r\nvar p = ms[0];\r\n for (var i = 1; ms.length > i; i++) {\r\n for (var j = i; ms.length > j; j++) {\r\n if (ms[j] + ms[i] === n - p) {\r\n return [p, ms[j], ms[i]]\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n var num = readline().split(\" \").map(x => parseInt(x));\r\n \r\n console.log(d(num));\r\n}\r\nfunction d (ms) {\r\nvar n = ms[ms.length - 1];\r\nvar p = ms[0];\r\n for (var i = 1; ms.length > i; i++) {\r\n for (var j = i; ms.length > j; j++) {\r\n if (ms[j] + ms[i] === n - p) {\r\n return [p, ms[j], ms[i]]\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "const readline = require(\"readline\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: true\r\n});\r\n\r\nlet c = 0;\r\n\r\nrl.on(\"line\", (array) => {\r\n c++;\r\n if(c == 1) return;\r\n [a, b, c, d, e, f, g] = array.split(\" \");\r\n\r\n let third = ((parseInt(c) == parseInt(a) + parseInt(b)) ? d : c);\r\n\r\n console.log(`${a} ${b} ${third}`);\r\n return;\r\n});\r\n"}, {"source_code": "const readline = require(\"readline\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet c = 0;\r\n\r\nrl.on(\"line\", (array) => {\r\n c++;\r\n if(c == 1) return;\r\n [a, b, c, d, e, f, g] = array.split(\" \");\r\n\r\n let third = c == a + b ? d : c;\r\n\r\n console.log(`${a} ${b} ${third}`);\r\n return;\r\n});\r\n"}, {"source_code": "const readline = require(\"readline\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\n// const rd = readline.createInterface({\r\n// input: process.stdin,\r\n// output: process.stdout\r\n// })\r\n\r\nfunction solve() {\r\n rl.on(\"line\", (array) => {\r\n [a, b, c, d, e, f, g] = array.split(' ');\r\n\r\n let third = (c == a + b) ? d : c\r\n\r\n console.log(`${a} ${b} ${third}`)\r\n });\r\n}\r\n\r\nrl.question(\"\", (reps) => {\r\n while (reps--) {\r\n solve()\r\n }\r\n});\r\n"}, {"source_code": "\nfunction findSum(arr,target) {\n const l1 = arr.length\n const l2 = l1 - 1\n for (let i = 0; i < l2; i++) {\n const a = arr[i]\n if (a > target) break\n const diff = target - a\n for (let j = i + 1; j < l1; j++) {\n const b = arr[j]\n if (b === diff) return [a,b]\n if (b > diff) break\n }\n }\n}\n\nfunction findOriginal(data) {\n const sorted = data.sort((a,b) => a-b)\n const a = sorted.shift()\n const a_b_c = sorted.pop()\n const b_c = a_b_c - a\n const [b,c] = findSum(sorted,b_c)\n return [a,b,c]\n}\n\n/*\nconst n = parseInt(readline()) \nfor (let i = 0; i < n; i++) {\n const a = readline().split(\" \").map(n => parseInt(n))\n print(...findOriginal(a))\n}\n*/\n\n\n\n\n\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst b = rna();\r\n\t\tconsole.log(...b.slice(0, 3));\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let noOfTestCases = Number(readline());\r\n let testCaseArray = [];\r\n for (let i = 0; i < noOfTestCases; i++) {\r\n testCaseArray.push(readline().split(\" \").map(x => Number(x)));\r\n }\r\n \r\n for (let i = 0; i < noOfTestCases; i++) {\r\n findLostArray(testCaseArray[i])\r\n }\r\n}\r\n\r\n\r\n\r\nfunction findLostArray(B) {\r\n console.log(B[0], B[0], B[6] - B[0] - B[1])\r\n}\r\n\r\n\r\n"}, {"source_code": "// your code goes here\r\nconst fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\nfor(var q = 1;q<=T;q++) {\r\n var a = readline().split(\" \").map(x => parseInt(x));\r\n var f = []\r\n var dist = []\r\n for(var i=0;i {\r\n if (n == null) {\r\n n = parseInt(line)\r\n m = n\r\n } else if (m>0) {\r\n m--;\r\n a.push(line.split(' ').map(e=>parseInt(e)))\r\n } \r\n if (m == 0) {\r\n readline.close();\r\n main();\r\n } \r\n});\r\n\r\nfunction main(){\r\n a.forEach(e=> {\r\n let x = e.pop();\r\n for (let i = 0; i < e.length-2; i++)\r\n for (let j = i+1; j < e.length-1; j++)\r\n for (let k = j+1; k < e.length; k++)\r\n if (e[i]+e[j]+e[k] == x) {\r\n return console.log([e[i],e[j],e[k]]);\r\n }\r\n });\r\n}\r\n// main();"}, {"source_code": "var len = readline();\r\nfor(var i=0;i<+len;i++)\r\n{\r\n var inputData = readline().split(' ');\r\n var result=[];\r\nresult.push(+inputData[inputData.length-1] -(+inputData[inputData.length-2]) );\r\nresult.push(+inputData[inputData.length-1] -(+inputData[inputData.length-3]) );\r\nresult.push(+inputData[inputData.length-1] - (result[0]+result[1]));\r\nprint(result.join(','));\r\n}\r\n"}, {"source_code": "var len = readline();\r\nfor(var i=0;i<+len;i++)\r\n{\r\n var inputData = readline().split(' ');\r\n var result=[];\r\nresult.push(+inputData[inputData.length-1] -(+inputData[inputData.length-2]) );\r\nresult.push(+inputData[inputData.length-1] -(+inputData[inputData.length-3]) );\r\nresult.push(+inputData[inputData.length-1] - (result[0]+result[1]));\r\nprint(result);\r\n}\r\n"}], "src_uid": "e0ec0cd81d2ec632ef89d207d80fa8a3"} {"nl": {"description": "Given an array $$$a$$$ of $$$n$$$ integers, find a range of values $$$[x, y]$$$ ($$$x \\le y$$$), and split $$$a$$$ into exactly $$$k$$$ ($$$1 \\le k \\le n$$$) subarrays in such a way that: Each subarray is formed by several continuous elements of $$$a$$$, that is, it is equal to $$$a_l, a_{l+1}, \\ldots, a_r$$$ for some $$$l$$$ and $$$r$$$ ($$$1 \\leq l \\leq r \\leq n$$$). Each element from $$$a$$$ belongs to exactly one subarray. In each subarray the number of elements inside the range $$$[x, y]$$$ (inclusive) is strictly greater than the number of elements outside the range. An element with index $$$i$$$ is inside the range $$$[x, y]$$$ if and only if $$$x \\le a_i \\le y$$$. Print any solution that minimizes $$$y - x$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 3 \\cdot 10^4$$$) — the number of test cases. 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 2 \\cdot 10^5$$$) — the length of the array $$$a$$$ and the number of subarrays required in the partition. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$) where $$$a_i$$$ is the $$$i$$$-th element 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 $$$k+1$$$ lines. In the first line, print $$$x$$$ and $$$y$$$ — the limits of the found range. Then print $$$k$$$ lines, the $$$i$$$-th should contain $$$l_i$$$ and $$$r_i$$$ ($$$1\\leq l_i \\leq r_i \\leq n$$$) — the limits of the $$$i$$$-th subarray. You can print the subarrays in any order.", "sample_inputs": ["3\n2 1\n1 2\n4 2\n1 2 2 2\n11 3\n5 5 5 1 5 5 1 5 5 5 1"], "sample_outputs": ["1 2\n1 2\n2 2\n1 3\n4 4\n5 5\n1 1\n2 2\n3 11"], "notes": "NoteIn the first test, there should be only one subarray, which must be equal to the whole array. There are $$$2$$$ elements inside the range $$$[1, 2]$$$ and $$$0$$$ elements outside, if the chosen range is $$$[1, 1]$$$, there will be $$$1$$$ element inside ($$$a_1$$$) and $$$1$$$ element outside ($$$a_2$$$), and the answer will be invalid.In the second test, it is possible to choose the range $$$[2, 2]$$$, and split the array in subarrays $$$(1, 3)$$$ and $$$(4, 4)$$$, in subarray $$$(1, 3)$$$ there are $$$2$$$ elements inside the range ($$$a_2$$$ and $$$a_3$$$) and $$$1$$$ element outside ($$$a_1$$$), in subarray $$$(4, 4)$$$ there is only $$$1$$$ element ($$$a_4$$$), and it is inside the range.In the third test, it is possible to choose the range $$$[5, 5]$$$, and split the array in subarrays $$$(1, 4)$$$, $$$(5, 7)$$$ and $$$(8, 11)$$$, in the subarray $$$(1, 4)$$$ there are $$$3$$$ elements inside the range and $$$1$$$ element outside, in the subarray $$$(5, 7)$$$ there are $$$2$$$ elements inside and $$$1$$$ element outside and in the subarray $$$(8, 11)$$$ there are $$$3$$$ elements inside and $$$1$$$ element outside."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n const n = rn(),\r\n k = rn(),\r\n a = new Array(n),\r\n b = new Array(n + 1).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = rn();\r\n b[a[i]]++;\r\n }\r\n for (let i = 1; i <= n; i++) b[i] += b[i - 1];\r\n let min = -Infinity,\r\n max = Infinity;\r\n for (let i = 1; i <= n; i++) {\r\n let l = i,\r\n r = n + 1;\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n const s = b[m] - b[i - 1];\r\n if (2 * s - n >= k) {\r\n r = m;\r\n } else {\r\n l = m + 1;\r\n }\r\n }\r\n if (l === n + 1) continue;\r\n if (l - i < max - min) [min, max] = [i, l];\r\n }\r\n let cnt = 0,\r\n c = new Array(n);\r\n for (let [i, num] of a.entries()) {\r\n if (num >= min && num <= max) cnt++;else cnt--;\r\n c[i] = cnt;\r\n }\r\n const ids = [];\r\n cnt = 1;\r\n for (let i = 0; i < n; i++) {\r\n if (ids.length === k - 1) break;\r\n if (c[i] === cnt) {\r\n ids.push(i);\r\n cnt++;\r\n }\r\n }\r\n const res = [`${min} ${max}`];\r\n if (k === 1) res.push(`1 ${n}`);else res.push(`1 ${ids[0] + 1}`);\r\n for (let i = 0; i < k - 1; i++) {\r\n if (i === k - 2) res.push(`${ids[i] + 2} ${n}`);else res.push(`${ids[i] + 2} ${ids[i + 1] + 1}`);\r\n }\r\n return res.join('\\n');\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= 100) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "321423f103e6d9c567079d2dde71b5bb"} {"nl": {"description": "This is the easy version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version all prices are different.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.", "input_spec": "The first line contains a single integer $$$n$$$ $$$(1 \\le n \\le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ different integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^9)$$$ — the prices of ice spheres.", "output_spec": "In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.", "sample_inputs": ["5\n1 2 3 4 5"], "sample_outputs": ["2\n3 1 4 2 5"], "notes": "NoteIn the example it's not possible to place ice spheres in any order so that Sage would buy $$$3$$$ of them. If the ice spheres are placed like this $$$(3, 1, 4, 2, 5)$$$, then Sage will buy two spheres: one for $$$1$$$ and one for $$$2$$$, because they are cheap."}, "positive_code": [{"source_code": "let readline=require('readline');\nlet rl=readline.createInterface({\n input:process.stdin,\n output:process.stdout\n});\nlet arr=[],n;\nrl.on('line',function(inp){\n arr.push(inp);\n let len=arr.length;\n if(len===1) n=parseInt(arr[0]);\n else{\n let a=arr[1].split(' ');\n for(let i=0;i {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let n = parseInt(readLine());\n\n let input = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n\n input = input.sort((a, b) => b - a);\n let output = [];\n let len = input.length;\n let grkl = true;\n for (let i = 0; i < len; i++) {\n if (grkl) {\n output.push(input.shift());\n } else {\n output.push(input.pop());\n }\n grkl = !grkl;\n }\n\n let anzahl = parseInt(Math.ceil(len / 2 - 1).toString());\n\n console.log(anzahl);\n console.log(output.join(\" \"));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nlet standardInputString = \"\";\nlet currentLine = 0;\n\nfunction readLine() {\n return standardInputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", (rawData) => {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let n = parseInt(readLine());\n\n let numbers = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n\n numbers = numbers.sort((a, b) => a - b);\n let nlen = numbers.length;\n\n let final = [];\n final[0] = numbers.pop();\n let finalnumber = numbers.pop();\n\n let arr1 = numbers.filter((el, i) => i < numbers.length / 2);\n let arr2 = numbers.filter((el, i) => i >= numbers.length / 2);\n arr2 = arr2.sort((a, b) => b - a);\n\n for (let i = 0; i < arr2.length; i++) {\n final.push(arr1[i]);\n final.push(arr2[i]);\n }\n if (arr1.length != arr2.length) final.push(arr1[arr1.length - 1]);\n +final.push(finalnumber);\n\n let count = 0;\n for (let i = 1; i < final.length - 1; i++) {\n if (final[i] < final[i - 1] && final[i] < final[i + 1]) count++;\n }\n\n console.log(count);\n console.log(final.join(\" \"));\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\n\nfunction main() {\n const len = +readLine();\n let arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n arr.sort((a, b) => a - b);\n\n for (let i = 0; i < len - 1; i++) {\n if (i % 2 === 0) [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];\n }\n\n console.log(Math.floor((len - 1) / 2));\n console.log(arr.join(\" \"));\n}\n"}, {"source_code": "\"use strict\";\nvar input = '';\nvar inputResolve;\nvar inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => {\n inputResolve();\n});\n(async () => {\n // var time = Date.now();\n await inputPromise;\n var inputs = input.split(/\\r?\\n/);\n var n = +inputs[0];\n var arr = inputs[1].split(' ').map(v => +v).sort((a, b) => a - b);\n console.log((n - 1) / 2 | 0);\n var minArr = arr.slice(0, n / 2 | 0);\n var maxArr = arr.slice(n / 2 | 0);\n var c = [];\n for (let i = 0; i < n; i++) {\n if (i % 2 == 0)\n c.push(maxArr[i / 2 | 0]);\n else\n c.push(minArr[i / 2 | 0]);\n }\n console.log(c.join(' '));\n})();\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this); }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this); }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this); }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0); };\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n};\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {});\n};\n"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nlet standardInputString = \"\";\nlet currentLine = 0;\n\nfunction readLine() {\n return standardInputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", (rawData) => {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let n = parseInt(readLine());\n\n let input = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n\n input = input.sort((a, b) => b - a);\n let output = [];\n let len = input.length;\n let grkl = true;\n for (let i = 0; i < len; i++) {\n if (grkl) {\n output.push(input.pop());\n } else {\n output.push(input.shift());\n }\n grkl = !grkl;\n }\n\n let anzahl = parseInt(Math.ceil(len / 2 - 1).toString());\n\n console.log(anzahl);\n console.log(output.join(\" \"));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nlet standardInputString = \"\";\nlet currentLine = 0;\n\nfunction readLine() {\n return standardInputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", (rawData) => {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let n = parseInt(readLine());\n\n let numbers = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n numbers = numbers.sort((a, b) => b - a);\n let final = [];\n for (let i = 0; i < Math.floor(numbers.length / 3); i++) {\n final.push(numbers[3 * i]);\n final.push(numbers[3 * i + 2]);\n final.push(numbers[3 * i + 1]);\n }\n numbers = numbers.sort();\n\n let finallen = final.length;\n for (let i = 0; i < numbers.length - finallen; i++) {\n final.push(numbers[i]);\n }\n\n let count = 0;\n for (let i = 1; i < final.length - 1; i++) {\n if (final[i] < final[i - 1] && final[i] < final[i + 1]) count++;\n }\n\n console.log(count);\n console.log(final.join(\" \"));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nlet standardInputString = \"\";\nlet currentLine = 0;\n\nfunction readLine() {\n return standardInputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", (rawData) => {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let n = parseInt(readLine());\n\n let input = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n\n input = input.sort((a, b) => b - a);\n let output = [];\n let len = input.length;\n let grkl = \"gross\";\n for (let i = 0; i < len; i++) {\n if (grkl == \"gross\") {\n let gr = Math.max(...input);\n output.push(gr);\n input = input.filter((el) => el != gr);\n grkl = \"klein\";\n } else if (grkl == \"klein\") {\n let kl = Math.min(...input);\n output.push(kl);\n input = input.filter((el) => el != kl);\n grkl = \"gross\";\n }\n }\n\n let anzahl = Math.ceil(len / 2 - 1);\n\n console.log(anzahl);\n console.log(output);\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nlet standardInputString = \"\";\nlet currentLine = 0;\n\nfunction readLine() {\n return standardInputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", (rawData) => {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let n = parseInt(readLine());\n\n let numbers = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n\n numbers = numbers.sort();\n let nlen = numbers.length;\n\n let final = [];\n final[0] = numbers.pop();\n let finalnumber = numbers.pop();\n\n let arr1 = numbers.filter((el, i) => i < numbers.length / 2);\n let arr2 = numbers.filter((el, i) => i > numbers.length / 2);\n arr2 = arr2.sort((a, b) => b - a);\n\n for (let i = 0; i < arr2.length; i++) {\n final.push(arr1[i]);\n final.push(arr2[i]);\n }\n if (arr1.length != arr2.length) final.push(arr1[arr1.length - 1]);\n +final.push(finalnumber);\n\n let count = 0;\n for (let i = 1; i < final.length - 1; i++) {\n if (final[i] < final[i - 1] && final[i] < final[i + 1]) count++;\n }\n\n console.log(count);\n console.log(final.join(\" \"));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nlet standardInputString = \"\";\nlet currentLine = 0;\n\nfunction readLine() {\n return standardInputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", (rawData) => {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let n = parseInt(readLine());\n\n let input = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n\n input = input.sort((a, b) => b - a);\n let output = [];\n let len = input.length;\n let grkl = \"gross\";\n for (let i = 0; i < len; i++) {\n if (grkl == \"gross\") {\n let gr = Math.max(...input);\n output.push(gr);\n input = input.filter((el) => el != gr);\n grkl = \"klein\";\n } else if (grkl == \"klein\") {\n let kl = Math.min(...input);\n output.push(kl);\n input = input.filter((el) => el != kl);\n grkl = \"gross\";\n }\n }\n\n let anzahl = Math.ceil(len / 2 - 1);\n\n console.log(anzahl);\n console.log(output.join(\" \"));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nlet standardInputString = \"\";\nlet currentLine = 0;\n\nfunction readLine() {\n return standardInputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", (rawData) => {\n standardInputString += rawData;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n standardInputString = standardInputString\n .trim()\n .split(\"\\n\")\n .map((line) => line.trim());\n\n main();\n});\n\nfunction main() {\n let len = parseInt(readLine());\n\n let input = readLine()\n .split(\" \")\n .map((el) => parseInt(el));\n /////////////////////////////////////////////\n\n input.sort();\n\n let output = [];\n let grkl = true;\n let l = input.length;\n for (let i = 0; i < l; i++) {\n if (grkl) output.push(input.pop());\n else output.push(input.shift());\n grkl = !grkl;\n }\n\n let n = Math.ceil(output.length / 2) - 1;\n console.log(n);\n console.log(output.join(\" \"));\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\n\nfunction main() {\n const len = +readLine();\n let arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n arr.sort((a, b) => a - b);\n\n for (let i = 0; i < len - 1; i++) {\n if (i % 2 === 0) [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];\n }\n\n console.log(len - 3);\n console.log(arr.join(\" \"));\n}\n"}], "src_uid": "bcd9439fbf6aedf6882612d5f7d6220f"} {"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)$$$ — 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": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var a = 1000000007;\n for(var j = 1; j <= n; j++){\n var k = lines[j];\n var answer = 1;\n for(var l = 3; l <= k * 2; l++){\n answer = answer * l % a;\n }\n console.log(answer);\n }\n}); "}], "negative_code": [], "src_uid": "19a2550af6a46308fd92c7a352f12a5f"} {"nl": {"description": "Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.", "input_spec": "The first line contains integer n (1 ≤ n ≤ 105) — the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 ≤ ai ≤ 104) — elements of array a. The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 — the binary representation of number m. Number m equals .", "output_spec": "Print a single integer — the maximum value of function f(x) for all .", "sample_inputs": ["2\n3 8\n10", "5\n17 0 10 2 1\n11010"], "sample_outputs": ["3", "27"], "notes": "NoteIn the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27."}, "positive_code": [{"source_code": "print(function(n, a, s) {\n\tvar i,\n\t\tp = new Int32Array(n + 5),\n\t\tq = new Int32Array(n + 5);\n\n\tfor (i = 1; i <= n; i++)\n\t\tp[i] = p[i - 1] + a[i - 1];\n\n\tfor (i = n - 1; i >= 0; i--)\n\t\tif (s[i] === '1')\n\t\t\tq[i] = q[i + 1] + a[i];\n\t\telse\n\t\t\tq[i] = q[i + 1];\n\n\n\tvar ans = q[0];\n\tfor (i = 0; i < n; i++)\n\t\tif (s[i] === '1')\n\t\t\tans = Math.max(ans, p[i] + q[i + 1]);\n\n\treturn ans;\n\n}(+readline(), readline().split(' ').map(Number), readline()));"}, {"source_code": "print(function(n, a, s) {\n\n\tvar i, b = [];\n\tfor (i = 0; i < n; i++)\n\t\tb[i] = a[i];\n\n\tvar sum = 0;\n\tfor (i = n - 1; i >= 0; i--)\n\t\tb[i] = s[i] === '1' ? sum += b[i] : sum;\n\n\tfor (i = 1; i < n; i++)\n\t\ta[i] += a[i - 1];\n\n\tvar ans = b[0];\n\tb.push(0);\n\ta[-1] = 0;\n\tvar x = s.lastIndexOf('1');\n\tfor (i = 0; i < n; i++)\n\t\tif (s[i] === '1')\n\t\t\tans = Math.max(ans, a[i - 1] + b[i + 1]);\n\n\treturn ans;\n\n}(+readline(), readline().split(' ').map(Number), readline()));"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar numItems = parseInt(readline(), 10);\n\tvar items = tokenizeIntegers(readline());\n\tvar bitmask = readline();\n\n\tvar sum = 0, remainder = 0;\n\n\tfor (var itemIndex = 0; itemIndex < numItems; ++itemIndex) {\n\t\tif (bitmask.charAt(itemIndex) == '0') {\n\t\t\tremainder += items[itemIndex];\n\t\t}\n\t\telse {\n\t\t\tsum += items[itemIndex];\n\t\t}\n\t}\n\n\tvar best = sum;\n\n\tfor (var position = numItems-1; position >= 0; --position) {\n\t\tif (bitmask.charAt(position) == '0') {\n\t\t\tremainder -= items[position];\n\t\t}\n\t\telse {\n\t\t\tbest = Math.max(best, sum - items[position] + remainder);\n\t\t}\n\t}\n\n\tprint(best);\n}\n\nmain();\n"}], "negative_code": [{"source_code": "print(function(n, a, s) {\n\n\tvar i, b = [];\n\tfor (i = 0; i < n; i++)\n\t\tb[i] = a[i];\n\n\tvar sum = 0;\n\tfor (i = n - 1; i >= 0; i--)\n\t\tb[i] = s[i] === '1' ? sum = b[i] : sum;\n\n\tfor (i = 1; i < n; i++)\n\t\ta[i] += a[i - 1];\n\n\tvar ans = b[0];\n\tb.push(0);\n\ta[-1] = 0;\n\tvar x = s.lastIndexOf('1');\n\tfor (i = 0; i <= x; i++)\n\t\tans = Math.max(ans, a[i - 1] + b[i + 1]);\n\n\treturn ans;\n\n}(+readline(), readline().split(' ').map(Number), readline()));"}, {"source_code": "print(function(n, a, s) {\n\n\tvar i, b = [];\n\tfor (i = 0; i < n; i++)\n\t\tb[i] = a[i];\n\n\tvar sum = 0;\n\tfor (i = n - 1; i >= 0; i--)\n\t\tb[i] = s[i] === '1' ? sum = b[i] : sum;\n\n\tfor (i = 1; i < n; i++)\n\t\ta[i] += a[i - 1];\n\n\tvar ans = 0;\n\tb.push(0);\n\ta[-1] = 0;\n\tvar x = s.lastIndexOf('1');\n\tfor (i = 0; i <= x; i++)\n\t\tans = Math.max(ans, a[i - 1] + b[i + 1]);\n\n\treturn ans;\n\n}(+readline(), readline().split(' ').map(Number), readline()));\n"}, {"source_code": "print(function(n, a, s) {\n\n\tvar i, b = [];\n\tfor (i = 0; i < n; i++)\n\t\tb[i] = a[i];\n\n\tvar sum = 0;\n\tfor (i = n - 1; i >= 0; i--)\n\t\tb[i] = s[i] === '1' ? sum += b[i] : sum;\n\n\tfor (i = 1; i < n; i++)\n\t\ta[i] += a[i - 1];\n\n\tvar ans = b[0];\n\tb.push(0);\n\ta[-1] = 0;\n\tvar x = s.lastIndexOf('1');\n\tfor (i = 0; i <= x; i++)\n\t\tans = Math.max(ans, a[i - 1] + b[i + 1]);\n\n\treturn ans;\n\n}(+readline(), readline().split(' ').map(Number), readline()));"}, {"source_code": "print(function(n, a, s) {\n\n\tvar v1 = a.reduce(function(sum, v, i) {\n\t\treturn s[i] === '1' ? sum + v : sum;\n\t});\n\n\tvar x = s.lastIndexOf('1');\n\tvar v2 = 0;\n\tfor (var i = 0; i < x; i++)\n\t\tv2 += a[i];\n\n\treturn Math.max(v1, v2);\n\n}(+readline(), readline().split(' ').map(Number), readline()));"}], "src_uid": "9366e1626b33b4f4e49cf35200c0448f"} {"nl": {"description": "Bethany would like to tile her bathroom. The bathroom has width $$$w$$$ centimeters and length $$$l$$$ centimeters. If Bethany simply used the basic tiles of size $$$1 \\times 1$$$ centimeters, she would use $$$w \\cdot l$$$ of them. However, she has something different in mind. On the interior of the floor she wants to use the $$$1 \\times 1$$$ tiles. She needs exactly $$$(w-2) \\cdot (l-2)$$$ of these. On the floor boundary she wants to use tiles of size $$$1 \\times a$$$ for some positive integer $$$a$$$. The tiles can also be rotated by $$$90$$$ degrees. For which values of $$$a$$$ can Bethany tile the bathroom floor as described? Note that $$$a$$$ can also be $$$1$$$. ", "input_spec": "Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\le t\\le 100$$$) — the number of test cases. The descriptions of the $$$t$$$ test cases follow. Each test case consist of a single line, which contains two integers $$$w$$$, $$$l$$$ ($$$3 \\leq w, l \\leq 10^{9}$$$) — the dimensions of the bathroom.", "output_spec": "For each test case, print an integer $$$k$$$ ($$$0\\le k$$$) — the number of valid values of $$$a$$$ for the given test case — followed by $$$k$$$ integers $$$a_1, a_2,\\dots, a_k$$$ ($$$1\\le a_i$$$) — the valid values of $$$a$$$. The values $$$a_1, a_2, \\dots, a_k$$$ have to be sorted from smallest to largest. It is guaranteed that under the problem constraints, the output contains at most $$$200\\,000$$$ integers. ", "sample_inputs": ["3\n\n3 5\n\n12 12\n\n314159265 358979323"], "sample_outputs": ["3 1 2 3\n3 1 2 11\n2 1 2"], "notes": "NoteIn the first test case, the bathroom is $$$3$$$ centimeters wide and $$$5$$$ centimeters long. There are three values of $$$a$$$ such that Bethany can tile the floor as described in the statement, namely $$$a=1$$$, $$$a=2$$$ and $$$a=3$$$. The three tilings are represented in the following pictures. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(w, l) {\r\n let set = new Set([1]);\r\n let nums = getDivisor(w);\r\n for (let a of nums) {\r\n if ((l - 2) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(w - 1);\r\n for (let a of nums) {\r\n if ((l - 1) % a === 0) set.add(a);\r\n if (l % a === 0 && (l - 2) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(w - 2);\r\n for (let a of nums) {\r\n if (l % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(l - 1);\r\n for (let a of nums) {\r\n if (w % a === 0 && (w - 2) % a === 0) set.add(a);\r\n }\r\n console.log(`${set.size} ${[...set].sort((a, b) => a - b).join(' ')}`);\r\n}\r\nfunction getDivisor(n) {\r\n let res = [1, n];\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n res.push(i);\r\n if (i !== n / i) res.push(n / i);\r\n }\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n solve(n, m);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m) {\r\n let set = new Set([1]);\r\n let nums = getDivisor(n);\r\n for (let a of nums) {\r\n if ((m - 2) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(n - 1);\r\n for (let a of nums) {\r\n if ((m - 1) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(n - 2);\r\n for (let a of nums) {\r\n if (m % a === 0) set.add(a);\r\n }\r\n console.log(`${set.size} ${[...set].sort((a, b) => a - b).join(' ')}`);\r\n}\r\nfunction getDivisor(n) {\r\n let res = [1, n];\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n res.push(i);\r\n if (i !== n / i) res.push(n / i);\r\n }\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n solve(n, m);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m) {\r\n if (n > m) return solve(m, n);\r\n let set = new Set([1]);\r\n let nums = getDivisor(n);\r\n for (let a of nums) {\r\n if ((m - 2) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(n - 1);\r\n for (let a of nums) {\r\n if ((m - 1) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(n - 2);\r\n for (let a of nums) {\r\n if (m % a === 0) set.add(a);\r\n }\r\n console.log(`${set.size} ${[...set].sort((a, b) => a - b).join(' ')}`);\r\n}\r\nfunction getDivisor(n) {\r\n let res = [1, n];\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n res.push(i);\r\n if (i !== n / i) res.push(n / i);\r\n }\r\n }\r\n return res.sort((a, b) => a - b);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n solve(n, m);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m) {\r\n if (n > m) return solve(m, n);\r\n let set = new Set([1]);\r\n let nums = getDivisor(n);\r\n for (let a of nums) {\r\n if ((m - 2) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(n - 1);\r\n for (let a of nums) {\r\n if ((m - 1) % a === 0) set.add(a);\r\n }\r\n nums = getDivisor(n - 2);\r\n for (let a of nums) {\r\n if (m % a === 0) set.add(a);\r\n }\r\n console.log([...set].sort((a, b) => a - b).join(' '));\r\n}\r\nfunction getDivisor(n) {\r\n let res = [1, n];\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n res.push(i);\r\n if (i !== n / i) res.push(n / i);\r\n }\r\n }\r\n return res.sort((a, b) => a - b);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n solve(n, m);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "src_uid": "fcfef9460f9e13af8f5288820d9f7376"} {"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·ki 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 ≤ n ≤ 105, 0 ≤ f ≤ n) 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, li (0 ≤ ki, li ≤ 109) 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, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 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": "var s = readline().split(\" \");\nvar n = Number(s[0]), f = Number(s[1]);\n\nvar profit = [];\nvar sum = 0;\nfor(var i=0; i b - a);\nfor(var i=0; i l) {\n sales.push(Math.max(l - k,0));\n }\n else {\n sales.push(k);\n }\n \n profit += Math.min(k,l);\n}\n\nsales.sort((a,b) => b-a);\nfor (var j = 0; j numberOfClients ? numberOfClients : numberOfProducts;\n var totalSalesPossible = Math.max(0, Math.min(numberOfProducts, numberOfClients - numberOfProducts));\n promotionalDays[i] = totalSalesPossible;\n}\n\n//quicksort(promotionalDays, 0, numberOfDays - 1);\npromotionalDays.sort((a, b) => b - a);\n\nfor (var i = 0; i < numberOfSaleDays; i++){\n numberOfSoldProducts += promotionalDays[i];\n}\n \nfor (var i = 0; i < numberOfDays; i++){\n numberOfSoldProducts += normalDays[i];\n}\n\nprint(numberOfSoldProducts);\n\nfunction quicksort(list, init, final){\n if (list.length > 1){\n var index = partition(list, init, final);\n if (init < index - 1)\n quicksort(list, init, index - 1);\n if (final > index)\n quicksort(list, index, final);\n }\n}\n\nfunction partition(list, init, final){\n var average = Math.floor((init + final)/2);\n var pivot = list[average];\n var i = init;\n var j = final;\n\n while (i < j){\n while (list[i] > pivot)\n i++;\n while (list[j] < pivot)\n j--;\n if (i < j){\n swap(list, i, j);\n i++;\n j--;\n }\n }\n return i;\n}\n\nfunction swap(list, firstIndex, secondIndex){\n var temp = list[firstIndex];\n list[firstIndex] = list[secondIndex];\n list[secondIndex] = temp;\n}"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar f = parseInt(arr[1]);\nvar k = [];\nvar l = [];\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline().split(' ');\n k.push(parseInt(arr[0]));\n l.push(parseInt(arr[1]));\n}\nvar b = [];\nvar sum = 0;\nfor (var i = 0; i < n; i ++)\n{\n sum += Math.min(k[i], l[i]);\n b.push(Math.min(k[i]*2, l[i]) - Math.min(k[i], l[i]));\n}\nb.sort(function(a,b){return b-a;});\nfor (var i = 0; i < f; i ++)\n{\n sum += b[i];\n}\nprint(sum);\n"}, {"source_code": "\n var bigInt=function(undefined){\"use strict\";var BASE=1e7,LOG_BASE=7,MAX_INT=9007199254740992,MAX_INT_ARR=smallToArray(MAX_INT),LOG_MAX_INT=Math.log(MAX_INT);function Integer(v,radix){if(typeof v===\"undefined\")return Integer[0];if(typeof radix!==\"undefined\")return+radix===10?parseValue(v):parseBase(v,radix);return parseValue(v)}function BigInteger(value,sign){this.value=value;this.sign=sign;this.isSmall=false}BigInteger.prototype=Object.create(Integer.prototype);function SmallInteger(value){this.value=value;this.sign=value<0;this.isSmall=true}SmallInteger.prototype=Object.create(Integer.prototype);function isPrecise(n){return-MAX_INT0)return Math.floor(n);return Math.ceil(n)}function add(a,b){var l_a=a.length,l_b=b.length,r=new Array(l_a),carry=0,base=BASE,sum,i;for(i=0;i=base?1:0;r[i]=sum-carry*base}while(i0)r.push(carry);return r}function addAny(a,b){if(a.length>=b.length)return add(a,b);return add(b,a)}function addSmall(a,carry){var l=a.length,r=new Array(l),base=BASE,sum,i;for(i=0;i0){r[i++]=carry%base;carry=Math.floor(carry/base)}return r}BigInteger.prototype.add=function(v){var n=parseValue(v);if(this.sign!==n.sign){return this.subtract(n.negate())}var a=this.value,b=n.value;if(n.isSmall){return new BigInteger(addSmall(a,Math.abs(b)),this.sign)}return new BigInteger(addAny(a,b),this.sign)};BigInteger.prototype.plus=BigInteger.prototype.add;SmallInteger.prototype.add=function(v){var n=parseValue(v);var a=this.value;if(a<0!==n.sign){return this.subtract(n.negate())}var b=n.value;if(n.isSmall){if(isPrecise(a+b))return new SmallInteger(a+b);b=smallToArray(Math.abs(b))}return new BigInteger(addSmall(b,Math.abs(a)),a<0)};SmallInteger.prototype.plus=SmallInteger.prototype.add;function subtract(a,b){var a_l=a.length,b_l=b.length,r=new Array(a_l),borrow=0,base=BASE,i,difference;for(i=0;i=0){value=subtract(a,b)}else{value=subtract(b,a);sign=!sign}value=arrayToSmall(value);if(typeof value===\"number\"){if(sign)value=-value;return new SmallInteger(value)}return new BigInteger(value,sign)}function subtractSmall(a,b,sign){var l=a.length,r=new Array(l),carry=-b,base=BASE,i,difference;for(i=0;i=0)};SmallInteger.prototype.minus=SmallInteger.prototype.subtract;BigInteger.prototype.negate=function(){return new BigInteger(this.value,!this.sign)};SmallInteger.prototype.negate=function(){var sign=this.sign;var small=new SmallInteger(-this.value);small.sign=!sign;return small};BigInteger.prototype.abs=function(){return new BigInteger(this.value,false)};SmallInteger.prototype.abs=function(){return new SmallInteger(Math.abs(this.value))};function multiplyLong(a,b){var a_l=a.length,b_l=b.length,l=a_l+b_l,r=createArray(l),base=BASE,product,carry,i,a_i,b_j;for(i=0;i0){r[i++]=carry%base;carry=Math.floor(carry/base)}return r}function shiftLeft(x,n){var r=[];while(n-->0)r.push(0);return r.concat(x)}function multiplyKaratsuba(x,y){var n=Math.max(x.length,y.length);if(n<=30)return multiplyLong(x,y);n=Math.ceil(n/2);var b=x.slice(n),a=x.slice(0,n),d=y.slice(n),c=y.slice(0,n);var ac=multiplyKaratsuba(a,c),bd=multiplyKaratsuba(b,d),abcd=multiplyKaratsuba(addAny(a,b),addAny(c,d));var product=addAny(addAny(ac,shiftLeft(subtract(subtract(abcd,ac),bd),n)),shiftLeft(bd,2*n));trim(product);return product}function useKaratsuba(l1,l2){return-.012*l1-.012*l2+15e-6*l1*l2>0}BigInteger.prototype.multiply=function(v){var n=parseValue(v),a=this.value,b=n.value,sign=this.sign!==n.sign,abs;if(n.isSmall){if(b===0)return Integer[0];if(b===1)return this;if(b===-1)return this.negate();abs=Math.abs(b);if(abs=0;shift--){quotientDigit=base-1;if(remainder[shift+b_l]!==divisorMostSignificantDigit){quotientDigit=Math.floor((remainder[shift+b_l]*base+remainder[shift+b_l-1])/divisorMostSignificantDigit)}carry=0;borrow=0;l=divisor.length;for(i=0;ib_l){highx=(highx+1)*base}guess=Math.ceil(highx/highy);do{check=multiplySmall(b,guess);if(compareAbs(check,part)<=0)break;guess--}while(guess);result.push(guess);part=subtract(part,check)}result.reverse();return[arrayToSmall(result),arrayToSmall(part)]}function divModSmall(value,lambda){var length=value.length,quotient=createArray(length),base=BASE,i,q,remainder,divisor;remainder=0;for(i=length-1;i>=0;--i){divisor=remainder*base+value[i];q=truncate(divisor/lambda);remainder=divisor-q*lambda;quotient[i]=q|0}return[quotient,remainder|0]}function divModAny(self,v){var value,n=parseValue(v);var a=self.value,b=n.value;var quotient;if(b===0)throw new Error(\"Cannot divide by zero\");if(self.isSmall){if(n.isSmall){return[new SmallInteger(truncate(a/b)),new SmallInteger(a%b)]}return[Integer[0],self]}if(n.isSmall){if(b===1)return[self,Integer[0]];if(b==-1)return[self.negate(),Integer[0]];var abs=Math.abs(b);if(absb.length?1:-1}for(var i=a.length-1;i>=0;i--){if(a[i]!==b[i])return a[i]>b[i]?1:-1}return 0}BigInteger.prototype.compareAbs=function(v){var n=parseValue(v),a=this.value,b=n.value;if(n.isSmall)return 1;return compareAbs(a,b)};SmallInteger.prototype.compareAbs=function(v){var n=parseValue(v),a=Math.abs(this.value),b=n.value;if(n.isSmall){b=Math.abs(b);return a===b?0:a>b?1:-1}return-1};BigInteger.prototype.compare=function(v){if(v===Infinity){return-1}if(v===-Infinity){return 1}var n=parseValue(v),a=this.value,b=n.value;if(this.sign!==n.sign){return n.sign?1:-1}if(n.isSmall){return this.sign?-1:1}return compareAbs(a,b)*(this.sign?-1:1)};BigInteger.prototype.compareTo=BigInteger.prototype.compare;SmallInteger.prototype.compare=function(v){if(v===Infinity){return-1}if(v===-Infinity){return 1}var n=parseValue(v),a=this.value,b=n.value;if(n.isSmall){return a==b?0:a>b?1:-1}if(a<0!==n.sign){return a<0?-1:1}return a<0?1:-1};SmallInteger.prototype.compareTo=SmallInteger.prototype.compare;BigInteger.prototype.equals=function(v){return this.compare(v)===0};SmallInteger.prototype.eq=SmallInteger.prototype.equals=BigInteger.prototype.eq=BigInteger.prototype.equals;BigInteger.prototype.notEquals=function(v){return this.compare(v)!==0};SmallInteger.prototype.neq=SmallInteger.prototype.notEquals=BigInteger.prototype.neq=BigInteger.prototype.notEquals;BigInteger.prototype.greater=function(v){return this.compare(v)>0};SmallInteger.prototype.gt=SmallInteger.prototype.greater=BigInteger.prototype.gt=BigInteger.prototype.greater;BigInteger.prototype.lesser=function(v){return this.compare(v)<0};SmallInteger.prototype.lt=SmallInteger.prototype.lesser=BigInteger.prototype.lt=BigInteger.prototype.lesser;BigInteger.prototype.greaterOrEquals=function(v){return this.compare(v)>=0};SmallInteger.prototype.geq=SmallInteger.prototype.greaterOrEquals=BigInteger.prototype.geq=BigInteger.prototype.greaterOrEquals;BigInteger.prototype.lesserOrEquals=function(v){return this.compare(v)<=0};SmallInteger.prototype.leq=SmallInteger.prototype.lesserOrEquals=BigInteger.prototype.leq=BigInteger.prototype.lesserOrEquals;BigInteger.prototype.isEven=function(){return(this.value[0]&1)===0};SmallInteger.prototype.isEven=function(){return(this.value&1)===0};BigInteger.prototype.isOdd=function(){return(this.value[0]&1)===1};SmallInteger.prototype.isOdd=function(){return(this.value&1)===1};BigInteger.prototype.isPositive=function(){return!this.sign};SmallInteger.prototype.isPositive=function(){return this.value>0};BigInteger.prototype.isNegative=function(){return this.sign};SmallInteger.prototype.isNegative=function(){return this.value<0};BigInteger.prototype.isUnit=function(){return false};SmallInteger.prototype.isUnit=function(){return Math.abs(this.value)===1};BigInteger.prototype.isZero=function(){return false};SmallInteger.prototype.isZero=function(){return this.value===0};BigInteger.prototype.isDivisibleBy=function(v){var n=parseValue(v);var value=n.value;if(value===0)return false;if(value===1)return true;if(value===2)return this.isEven();return this.mod(n).equals(Integer[0])};SmallInteger.prototype.isDivisibleBy=BigInteger.prototype.isDivisibleBy;function isBasicPrime(v){var n=v.abs();if(n.isUnit())return false;if(n.equals(2)||n.equals(3)||n.equals(5))return true;if(n.isEven()||n.isDivisibleBy(3)||n.isDivisibleBy(5))return false;if(n.lesser(25))return true}BigInteger.prototype.isPrime=function(){var isPrime=isBasicPrime(this);if(isPrime!==undefined)return isPrime;var n=this.abs(),nPrev=n.prev();var a=[2,3,5,7,11,13,17,19],b=nPrev,d,t,i,x;while(b.isEven())b=b.divide(2);for(i=0;i-MAX_INT)return new SmallInteger(value-1);return new BigInteger(MAX_INT_ARR,true)};var powersOfTwo=[1];while(powersOfTwo[powersOfTwo.length-1]<=BASE)powersOfTwo.push(2*powersOfTwo[powersOfTwo.length-1]);var powers2Length=powersOfTwo.length,highestPower2=powersOfTwo[powers2Length-1];function shift_isSmall(n){return(typeof n===\"number\"||typeof n===\"string\")&&+Math.abs(n)<=BASE||n instanceof BigInteger&&n.value.length<=1}BigInteger.prototype.shiftLeft=function(n){if(!shift_isSmall(n)){throw new Error(String(n)+\" is too large for shifting.\")}n=+n;if(n<0)return this.shiftRight(-n);var result=this;while(n>=powers2Length){result=result.multiply(highestPower2);n-=powers2Length-1}return result.multiply(powersOfTwo[n])};SmallInteger.prototype.shiftLeft=BigInteger.prototype.shiftLeft;BigInteger.prototype.shiftRight=function(n){var remQuo;if(!shift_isSmall(n)){throw new Error(String(n)+\" is too large for shifting.\")}n=+n;if(n<0)return this.shiftLeft(-n);var result=this;while(n>=powers2Length){if(result.isZero())return result;remQuo=divModAny(result,highestPower2);result=remQuo[1].isNegative()?remQuo[0].prev():remQuo[0];n-=powers2Length-1}remQuo=divModAny(result,powersOfTwo[n]);return remQuo[1].isNegative()?remQuo[0].prev():remQuo[0]};SmallInteger.prototype.shiftRight=BigInteger.prototype.shiftRight;function bitwise(x,y,fn){y=parseValue(y);var xSign=x.isNegative(),ySign=y.isNegative();var xRem=xSign?x.not():x,yRem=ySign?y.not():y;var xBits=[],yBits=[];var xStop=false,yStop=false;while(!xStop||!yStop){if(xRem.isZero()){xStop=true;xBits.push(xSign?1:0)}else if(xSign)xBits.push(xRem.isEven()?1:0);else xBits.push(xRem.isEven()?0:1);if(yRem.isZero()){yStop=true;yBits.push(ySign?1:0)}else if(ySign)yBits.push(yRem.isEven()?1:0);else yBits.push(yRem.isEven()?0:1);xRem=xRem.over(2);yRem=yRem.over(2)}var result=[];for(var i=0;i=0;i--){var top=restricted?range.value[i]:BASE;var digit=truncate(Math.random()*top);result.unshift(digit);if(digit\");digits.push(parseValue(text.slice(start+1,i)))}else throw new Error(c+\" is not a valid character\")}return parseBaseFromArray(digits,base,isNegative)};function parseBaseFromArray(digits,base,isNegative){var val=Integer[0],pow=Integer[1],i;for(i=digits.length-1;i>=0;i--){val=val.add(digits[i].times(pow));pow=pow.times(base)}return isNegative?val.negate():val}function stringify(digit){var v=digit.value;if(typeof v===\"number\")v=[v];if(v.length===1&&v[0]<=35){return\"0123456789abcdefghijklmnopqrstuvwxyz\".charAt(v[0])}return\"<\"+v+\">\"}function toBase(n,base){base=bigInt(base);if(base.isZero()){if(n.isZero())return\"0\";throw new Error(\"Cannot convert nonzero numbers to base 0.\")}if(base.equals(-1)){if(n.isZero())return\"0\";if(n.isNegative())return new Array(1-n).join(\"10\");return\"1\"+new Array(+n).join(\"01\")}var minusSign=\"\";if(n.isNegative()&&base.isPositive()){minusSign=\"-\";n=n.abs()}if(base.equals(1)){if(n.isZero())return\"0\";return minusSign+new Array(+n+1).join(1)}var out=[];var left=n,divmod;while(left.isNegative()||left.compareAbs(base)>=0){divmod=left.divmod(base);left=divmod.quotient;var digit=divmod.remainder;if(digit.isNegative()){digit=base.minus(digit).abs();left=left.next()}out.push(stringify(digit))}out.push(stringify(left));return minusSign+out.reverse().join(\"\")}BigInteger.prototype.toString=function(radix){if(radix===undefined)radix=10;if(radix!==10)return toBase(this,radix);var v=this.value,l=v.length,str=String(v[--l]),zeros=\"0000000\",digit;while(--l>=0){digit=String(v[l]);str+=zeros.slice(digit.length)+digit}var sign=this.sign?\"-\":\"\";return sign+str};SmallInteger.prototype.toString=function(radix){if(radix===undefined)radix=10;if(radix!=10)return toBase(this,radix);return String(this.value)};BigInteger.prototype.valueOf=function(){return+this.toString()};BigInteger.prototype.toJSNumber=BigInteger.prototype.valueOf;SmallInteger.prototype.valueOf=function(){return this.value};SmallInteger.prototype.toJSNumber=SmallInteger.prototype.valueOf;function parseStringValue(v){if(isPrecise(+v)){var x=+v;if(x===truncate(x))return new SmallInteger(x);throw\"Invalid integer: \"+v}var sign=v[0]===\"-\";if(sign)v=v.slice(1);var split=v.split(/e/i);if(split.length>2)throw new Error(\"Invalid integer: \"+split.join(\"e\"));if(split.length===2){var exp=split[1];if(exp[0]===\"+\")exp=exp.slice(1);exp=+exp;if(exp!==truncate(exp)||!isPrecise(exp))throw new Error(\"Invalid integer: \"+exp+\" is not a valid exponent.\");var text=split[0];var decimalPlace=text.indexOf(\".\");if(decimalPlace>=0){exp-=text.length-decimalPlace-1;text=text.slice(0,decimalPlace)+text.slice(decimalPlace+1)}if(exp<0)throw new Error(\"Cannot include negative exponent part for integers\");text+=new Array(exp+1).join(\"0\");v=text}var isValid=/^([0-9][0-9]*)$/.test(v);if(!isValid)throw new Error(\"Invalid integer: \"+v);var r=[],max=v.length,l=LOG_BASE,min=max-l;while(max>0){r.push(+v.slice(min,max));min-=l;if(min<0)min=0;max-=l}trim(r);return new BigInteger(r,sign)}function parseNumberValue(v){if(isPrecise(v)){if(v!==truncate(v))throw new Error(v+\" is not an integer.\");return new SmallInteger(v)}return parseStringValue(v.toString())}function parseValue(v){if(typeof v===\"number\"){return parseNumberValue(v)}if(typeof v===\"string\"){return parseStringValue(v)}return v}for(var i=0;i<1e3;i++){Integer[i]=new SmallInteger(i);if(i>0)Integer[-i]=new SmallInteger(-i)}Integer.one=Integer[1];Integer.zero=Integer[0];Integer.minusOne=Integer[-1];Integer.max=max;Integer.min=min;Integer.gcd=gcd;Integer.lcm=lcm;Integer.isInstance=function(x){return x instanceof BigInteger||x instanceof SmallInteger};Integer.randBetween=randBetween;Integer.fromArray=function(digits,base,isNegative){return parseBaseFromArray(digits.map(parseValue),parseValue(base||10),isNegative)};return Integer}();\n \n var tmp = readline().split(' ').map(x => parseInt(x));\n var n = tmp[0];\n var f = tmp[1];\n var d = [];\n var sum = bigInt();\n for(var i = 0; i < n; i += 1) {\n tmp = readline().split(' ').map(x => parseInt(x));\n d[i] = {\n k: tmp[0],\n l: tmp[1]\n };\n sum = sum.add(Math.min(d[i].k, d[i].l));\n }\n d.sort((b, a) => (Math.min(2 * a.k, a.l) - Math.min(a.k, a.l)) - (Math.min(2 * b.k, b.l) - Math.min(b.k, b.l)));\n for(var i = 0; i < f; i += 1) {\n sum = sum.add(Math.min(2 * d[i].k, d[i].l) - Math.min(d[i].k, d[i].l));\n }\n print(sum.toString());\n \n \n"}, {"source_code": "var readline = (function () {\n var lines = require(\"fs\")\n .readFileSync(0, \"utf-8\")\n .split(\"\\n\");\n var i = 0;\n return function () { return lines[i++]; };\n})();\nvar _a = readline()\n .split(\" \")\n .map(function (v) { return parseInt(v); }), n = _a[0], maxSellouts = _a[1];\nvar arr = [];\nfor (var i = 0; i < n; i++) {\n var line = readline().split(\" \");\n var products = parseInt(line[0]);\n var clients = parseInt(line[1]);\n arr.push({\n gain: Math.min(products, clients),\n doubleGain: Math.min(products * 2, clients)\n });\n}\nvar sorted = arr.sort(function (a, b) { return b.doubleGain - b.gain - (a.doubleGain - a.gain); });\nvar value = sorted.reduce(function (acc, _a, i) {\n var gain = _a.gain, doubleGain = _a.doubleGain;\n return acc + (i < maxSellouts ? doubleGain : gain);\n}, 0);\nconsole.log(value);\n"}], "negative_code": [{"source_code": "var s = readline().split(\" \");\nvar n = Number(s[0]), f = Number(s[1]);\n\nvar profit = [];\nvar sum = 0;\nfor(var i=0; i b - a);\nfor(var i=0; i numberOfClients ? numberOfClients : numberOfProducts;\n var totalSalesPossible = numberOfProducts * 2 > numberOfClients ? numberOfClients : numberOfProducts * 2;\n promotionalDays[i] = totalSalesPossible;\n}\n\nquicksort(promotionalDays, normalDays, 0, numberOfDays - 1);\n\nfor (var i = 0; i < numberOfSaleDays; i++){\n numberOfSoldProducts += promotionalDays[i];\n}\n \n\nfor (var i = numberOfSaleDays; i < numberOfDays; i++){\n numberOfSoldProducts += normalDays[i];\n}\n\nprint(numberOfSoldProducts);\n\nfunction quicksort(list1, list2, init, final){\n if (list1.length > 1){\n var index = partition(list1, list2, init, final);\n if (init < index -1)\n quicksort(list1, list2, init, index - 1);\n if (final > index)\n quicksort(list1, list2, index, final);\n }\n}\n\nfunction partition(list1, list2, init, final){\n var average = (init + final)/2;\n var pivot = list1[average];\n var i = init;\n var j = final;\n\n while (i < j){\n while (list1[i] > pivot)\n i++;\n while (list1[j] < pivot)\n j--;\n if (i < j){\n swap(list1, list2, i, j);\n i++;\n j--;\n }\n }\n return i;\n}\n\nfunction swap(list1, list2, firstIndex, secondIndex){\n var temp = list1[firstIndex];\n list1[firstIndex] = list1[secondIndex];\n list1[secondIndex] = temp;\n\n temp = list2[firstIndex];\n list2[firstIndex] = list2[secondIndex];\n list2[secondIndex] = temp;\n}"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar f = parseInt(arr[1]);\nvar k = [];\nvar l = [];\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline().split(' ');\n k.push(parseInt(arr[0]));\n l.push(parseInt(arr[1]));\n}\nvar b = [];\nvar sum = 0;\nfor (var i = 0; i < n; i ++)\n{\n sum += Math.min(k[i], l[i]);\n b.push(Math.max(Math.min(k[i]*2, l[i]) - k[i], 0));\n}\nb.sort();\nfor (var i = 0; i < f; i ++)\n{\n sum += b[n-i-1];\n}\nprint(sum);\n"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar f = parseInt(arr[1]);\nvar k = [];\nvar l = [];\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline().split(' ');\n k.push(parseInt(arr[0]));\n l.push(parseInt(arr[1]));\n}\nvar b = [];\nvar sum = 0;\nfor (var i = 0; i < n; i ++)\n{\n sum += Math.min(k[i], l[i]);\n b.push(Math.min(k[i]*2, l[i]) - Math.min(k[i], l[i]));\n}\nb=b.sort();\nfor (var i = 0; i < f; i ++)\n{\n sum += b[n-i-1];\n}\nprint(sum);\n"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar f = parseInt(arr[1]);\nvar k = [];\nvar l = [];\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline().split(' ');\n k.push(parseInt(arr[0]));\n l.push(parseInt(arr[1]));\n}\nvar b = [];\nvar sum = 0;\nfor (var i = 0; i < n; i ++)\n{\n sum += Math.min(k[i], l[i]);\n b.push(Math.min(k[i]*2, l[i]) - Math.min(k[i], l[i]));\n}\nb.sort();\nfor (var i = 0; i < f; i ++)\n{\n sum += b[n-i-1];\n}\nprint(sum);\n"}, {"source_code": "var arr = readline().split(' ');\nvar n = parseInt(arr[0]);\nvar f = parseInt(arr[1]);\nvar k = [];\nvar l = [];\nfor (var i = 0; i < n; i ++)\n{\n var arr = readline().split(' ');\n k.push(parseInt(arr[0]));\n l.push(parseInt(arr[1]));\n}\nvar b = [];\nvar sum = 0;\nfor (var i = 0; i < n; i ++)\n{\n sum += Math.min(k[i], l[i]);\n b.push(Math.min(k[i]*2, l[i]) - Math.min(k[i], l[i]));\n}\nb.sort();\nfor (var i = 0; i < f; i ++)\n{\n sum += b[n-i-1];\n}\nif (k[0]==9 && l[0]==10481002 && k[1]==3 && l[1]==268224257)\n{\n sum ++;\n}\nprint(sum);\n"}], "src_uid": "c9b322a9138410a82e541179272eb6bf"} {"nl": {"description": "In an ICPC contest, balloons are distributed as follows: Whenever a team solves a problem, that team gets a balloon. The first team to solve a problem gets an additional balloon. A contest has 26 problems, labelled $$$\\textsf{A}$$$, $$$\\textsf{B}$$$, $$$\\textsf{C}$$$, ..., $$$\\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) — the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.", "output_spec": "For each test case, output a single integer — the total number of balloons that the teams received.", "sample_inputs": ["6\n\n3\n\nABA\n\n1\n\nA\n\n3\n\nORZ\n\n5\n\nBAAAA\n\n4\n\nBKPT\n\n10\n\nCODEFORCES"], "sample_outputs": ["5\n2\n6\n7\n8\n17"], "notes": "NoteIn the first test case, $$$5$$$ balloons are given out: Problem $$$\\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\\textsf{A}$$$. Problem $$$\\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\\textsf{B}$$$. Problem $$$\\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\\textsf{A}$$$. The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\\textsf{A}$$$."}, "positive_code": [{"source_code": "\r\nprocess.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount * 2; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n console.log(getScore(test.trim()));\r\n }\r\n});\r\n\r\nfunction getScore(input) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < input.length; i++) {\r\n const char = input[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n return score;\r\n}\r\n"}, {"source_code": "\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0], e = 0, biggest = 0, g = 0, a = new Map()\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j]\n }else{\n g = 0\n a = new Map()\n var k = lines[j].split('')\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n temp = a.get(k[l])\n temp++\n \n a.set(k[l], temp)\n }else{\n a.set(k[l], 1)\n g++\n }\n }\n \n for(var [key, value] of a){\n g+=value\n }\n console.log(g)\n\n }\n }\n \n \n}); \n\n"}, {"source_code": "function Solution() {\n const N = Number(lines[0]);\n const res = [];\n for (let i = 1; i <= 2 * N; i += 2) {\n const n = Number(lines[i]);\n const str = lines[i + 1];\n res.push(new Set(str).size + n);\n }\n return res.join('\\n');\n}\n\nconst readline = require('readline')\n \nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n console.log(Solution());\n});"}, {"source_code": "function Solution() {\n const N = Number(lines[0]);\n const res = [];\n for (let i = 1; i <= 2 * N; i += 2) {\n const n = Number(lines[i]);\n const str = lines[i + 1];\n const set = new Set();\n let count = 0;\n for (let i = 0; i < n; i++) {\n if (set.has(str[i])) {\n count += 1;\n } else {\n count += 2;\n set.add(str[i]);\n }\n }\n res.push(count);\n }\n return res.join('\\n');\n}\n\nconst readline = require('readline')\n \nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n console.log(Solution());\n});"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (str) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2 !== 0) {\n c++;\n return;\n }\n\n const visited = {};\n let ans = 0;\n\n for (let i = 0; i < str.length; i++) {\n if (visited[str[i]]) {\n ans++;\n } else {\n ans += 2;\n }\n\n visited[str[i]] = true;\n }\n\n console.log(ans);\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "const readline = require('readline');\r\nconst { stdin: input, stdout: output } = require('process')\r\nconst rl = readline.createInterface({ input, output })\r\n\r\nlet lines = []\r\n\r\nconst createReadLine = () => {\r\n i = 0;\r\n return () => lines[i++]\r\n}\r\n\r\nrl.on('line', line => lines.push(line))\r\n\r\nrl.on(\"close\", () => {\r\n const readLine = createReadLine();\r\n // const alphabet = \"abcdefghijklmnopqrstuvwxyz\".toUpperCase();\r\n let t = parseInt(readLine());\r\n while (t--) {\r\n readLine()\r\n let str = readLine();\r\n let problems = {};\r\n let ans = 0;\r\n for (const pr of str) {\r\n if (problems[pr]) {\r\n ans++;\r\n } else {\r\n problems[pr] = true;\r\n ans += 2;\r\n }\r\n }\r\n\r\n console.log(ans)\r\n }\r\n});"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tnl.num();\n\t\tlet x = {};\n\t\tlet y = 0;\n\t\tnl.line().split('').forEach(e => \n\t\t{\n\t\t\tif (x[e]){\n\t\t\t\ty++;\n\t\t\t} else {\n\t\t\t\tx[e] = 1;\n\t\t\t\ty += 2;\n\t\t\t}\n\t\t});\n\t\tans.push(y);\n\t\t\n\t\t\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1) {\n n = lines[i];\n }else{\n var k = lines[i].split('');\n var a = new Map();\n var ans = 0;\n for(j = 0; j < n; j++){\n if(a.get(k[j]) === undefined){\n a.set(k[j], 1);\n ans += 2;\n }else{\n ans++;\n }\n }\n console.log(ans);\n }\n }\n});"}, {"source_code": "\r\n\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var tests = parseInt(readline());\r\n for (let t = 0;t < tests; ++t) {\r\n let n = parseInt(readline());\r\n let s = readline();\r\n let str = Array.from(s);\r\n let ans = 0;\r\n let hsh = Array(26).fill(false);\r\n\r\n for (let i = 0;i < s.length-1; ++i) {\r\n if (hsh[s.charCodeAt(i)-65]) {\r\n ans++;\r\n } else {\r\n hsh[s.charCodeAt(i)-65] = true;\r\n ans++;\r\n ans++;\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const str = lines[l++]\n output[i] = solve(n, str)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, str) {\n const map = {}\n for (let i = 0; i < str.length; i++) {\n map[str[i]] = 1\n }\n return str.length + Object.keys(map).length\n}\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\nfunction main(){\r\n let t = readline()-0\r\n while(t--){\r\n let n = readline()\r\n let str = readline()\r\n let s = new Set()\r\n let res = 0\r\n for(let i=0;i {\n if (lineNum === 0) {\n // skip\n } else {\n if (lineNum % 2 === 0) {\n map.clear();\n for (let char of line) {\n map.set(char, (map.get(char) || 0) + 1);\n }\n let cnt = 0;\n for (let c of map.values()) {\n cnt += c + 1;\n }\n console.log(cnt);\n }\n }\n\n lineNum++;\n});\n"}, {"source_code": "// https://stackoverflow.com/questions/20086849/how-to-read-from-stdin-line-by-line-in-node\r\n// // cat .\\input.txt | node .\\script.js\r\nconst state = {\r\n i: 0,\r\n acc: []\r\n}\r\nconst readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false\r\n});\r\nrl.on('line',\r\n function (line) {\r\n const alphabet = {\r\n A: 0,\r\n B: 0,\r\n C: 0,\r\n D: 0,\r\n E: 0,\r\n F: 0,\r\n G: 0,\r\n H: 0,\r\n I: 0,\r\n J: 0,\r\n K: 0,\r\n L: 0,\r\n M: 0,\r\n N: 0,\r\n O: 0,\r\n P: 0,\r\n Q: 0,\r\n R: 0,\r\n S: 0,\r\n T: 0,\r\n U: 0,\r\n V: 0,\r\n W: 0,\r\n X: 0,\r\n Y: 0,\r\n Z: 0\r\n }\r\n if (state.i > 0) {\r\n state.acc.push(line)\r\n if (state.acc.length == 2) {\r\n // \r\n let sum = 0\r\n let [t, n] = state.acc\r\n for (let i = 0; i < n.length; i++) {\r\n let current = n[i]\r\n if (alphabet[current] == 0) {\r\n sum++\r\n alphabet[current]++\r\n }\r\n sum++\r\n }\r\n console.log(sum)\r\n // \r\n state.acc = []\r\n }\r\n\r\n }\r\n state.i++\r\n })\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\n_input = \"\";\r\nprocess.stdin.on(\"data\", function (input) {\r\n _input += input; \r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n processData(_input);\r\n});\r\n\r\nfunction processData(input) {\r\n const lines = input.split(\"\\n\");\r\n for (let i = 1; i <= lines[0]; i++) {\r\n processTC(lines, (2*i-1));\r\n }\r\n}\r\n\r\nfunction processTC(lines, startLine) {\r\n const n = Number(lines[startLine]);\r\n const str = lines[startLine+1];\r\n checkSolved(str, n);\r\n}\r\n\r\nfunction checkSolved(str, n) {\r\n let map = {};\r\n let count = 0;\r\n for (let i = 0; i < n; i++) {\r\n const char = str.charAt(i);\r\n if (!map[char]) map[char]=0;\r\n map[char]++;\r\n if (map[char] === 1) count++;\r\n count++;\r\n }\r\n console.log(count);\r\n}"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n// console.log(input)\r\nvar T = readline();\r\n// var inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n // var nul = readline();\r\n var a = readline()\r\n var n = readline()//.split(' ').map((x) => parseInt(x));\r\n // var a = readline().split(' ').map((x) => parseInt(x));\r\n var ans = 0;\r\n var f = Alph();\r\n var mp = new Map();\r\n for(var i=0;i {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline().trim();\r\n let obj = {},\r\n sum = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (obj[arr[i]]) sum++;\r\n else {\r\n obj[arr[i]] = 1;\r\n sum += 2;\r\n }\r\n }\r\n console.log(sum);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split('\\n')\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let times = parseInt(readline());\r\n for (let i = 0; i < times; i++) {\r\n let len = parseInt(readline());\r\n let distinct = new Set(readline().split(''));\r\n console.log(distinct.size + len);\r\n }\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar S = next();\r\n\t\tvar output = 0;\r\n\t\tvar set = new Set();\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\toutput++;\r\n\t\t\tif(!set.has(S[i])){\r\n\t\t\t\toutput++;\r\n\t\t\t\tset.add(S[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let seen = {};\r\n let total = 0;\r\n readline();\r\n let solved = readline();\r\n for (let i = 0; i < solved.length; i++) {\r\n let c = solved[i];\r\n if (seen[c]) {\r\n total += 1;\r\n } else {\r\n seen[c] = true;\r\n total += 2;\r\n }\r\n }\r\n output(total);\r\n }\r\n}"}, {"source_code": "function getBalloons(numbers) {\r\n var balloons = [];\r\n for (var element of numbers) {\r\n if (balloons.indexOf(element) == -1) {\r\n balloons.push(element);\r\n }\r\n\r\n }\r\n return balloons.length;\r\n\r\n}\r\nvar test = readline();\r\nfor (var i = 1; i <= test; i++) {\r\n var n = readline();\r\n var numbers = readline().split('');\r\n print(parseInt(n) + getBalloons(numbers));\r\n}"}, {"source_code": "var test = readline();\r\nfor (var i = 1; i <= test; i++) {\r\n var n = readline();\r\n var numbers = readline().split('');\r\n var balloons = [];\r\n for (var element of numbers) {\r\n if (balloons.indexOf(element) == -1) {\r\n balloons.push(element);\r\n }\r\n\r\n }\r\n //var result = getBalloons(numbers) + parseInt(n);\r\n\r\n print(parseInt(n) + balloons.length);\r\n}"}, {"source_code": "var test = readline()\r\nfor(var i=0; i {\r\n set.add(el)\r\n })\r\n\r\n ans = set.size + str.length\r\n print(ans)\r\n}"}], "negative_code": [{"source_code": "\r\nprocess.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount * 2; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n console.log(getScore(test));\r\n }\r\n});\r\n\r\nfunction getScore(input) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < input.length; i++) {\r\n const char = input[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n return score;\r\n}"}, {"source_code": "\r\nprocess.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount * 2; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < test.length - 1; i++) {\r\n const char = test[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n console.log(score);\r\n }\r\n});\r\n"}, {"source_code": "\r\nprocess.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n console.log(\"tests:\", tests);\r\n\r\n for (let test of tests) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < test.length - 1; i++) {\r\n const char = test[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n console.log(score);\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < test.length - 1; i++) {\r\n const char = test[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n console.log(score);\r\n }\r\n});"}, {"source_code": "process.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < test.length - 1; i++) {\r\n console.log(\"Test:\", test, \"i:\", i, \"solved:\", solved, \"score:\", score);\r\n const char = test[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n console.log(score);\r\n }\r\n});"}, {"source_code": "process.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < test.length; i++) {\r\n console.log(\"Test:\", test, \"i:\", i, \"solved:\", solved, \"score:\", score);\r\n const char = test[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n console.log(score);\r\n }\r\n});"}, {"source_code": "process.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n let solved = \"\";\r\n let score = 0;\r\n for (let i = 0; i < test.length; i++) {\r\n const char = test[i];\r\n if (solved.includes(char)) {\r\n score += 1;\r\n } else {\r\n solved += char;\r\n score += 2;\r\n }\r\n }\r\n console.log(score);\r\n }\r\n});"}, {"source_code": "process.stdin.on(\"data\", (data) => {\r\n const [testCount, ...testCases] = data.toString().trim().split(\"\\n\");\r\n\r\n const tests = [];\r\n for (let i = 1; i < testCount; i += 2) {\r\n tests.push(testCases[i]);\r\n }\r\n\r\n for (let test of tests) {\r\n console.log(test);\r\n }\r\n});"}, {"source_code": "\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0], e = 0, biggest = 0, g = 0, a = new Map()\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j]\n }else{\n g = 0\n var k = lines[j].split('')\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n temp = a.get(k[l])\n temp++\n \n a.set(k[l], temp)\n }else{\n a.set(k[l], 1)\n g++\n }\n }\n \n for(var [key, value] of a){\n g+=value\n }\n console.log(g)\n\n }\n }\n \n \n}); \n\n"}, {"source_code": "\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0], e = 0, biggest = 0, g = 0, a = new Map()\n for(j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j]\n }else{\n var k = lines[j].split('').map(String)\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n temp = a.get(k[l])\n temp++\n if(temp == 2){\n g++\n }\n a.set(k[l], temp)\n }else{\n a.set(k[l], 1)\n }\n }\n \n for(var [key, value] of a){\n g++\n }\n }\n console.log(g)\n }\n \n \n}); \n\n"}, {"source_code": "\r\n/*\r\nfunction getBalloons(numbers) {\r\n var balloons = [];\r\n for (const element of numbers) {\r\n if (balloons.indexOf(element) == -1) {\r\n balloons.push(element);\r\n }\r\n\r\n }\r\n return balloons.length;\r\n\r\n}*/\r\nvar test = readline();\r\nfor (var i = 1; i <= test; i++) {\r\n var n = readline();\r\n var numbers = readline().split('');\r\n var balloons = [];\r\n for (const element of numbers) {\r\n if (balloons.indexOf(element) == -1) {\r\n balloons.push(element);\r\n }\r\n\r\n }\r\n //var result = getBalloons(numbers) + parseInt(n);\r\n\r\n print(parseInt(n) + balloons.length);\r\n}\r\n"}, {"source_code": " var t = readline()\r\n for (var i=0; i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, iii) => {\r\n var n = parseInt(readline())\r\n // var [n, k] = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // })\r\n // var s = new Array(n + 1).fill(0)\r\n\r\n //\r\n // var count = {}\r\n // var a = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // })\r\n var res = []\r\n for (let i = 0; i < n; i++) {\r\n for (let j = i + 1; j < n; j++) {\r\n var dif=(j-i)*2\r\n var add=dif === n ? 0: dif < n ? 1 : -1\r\n res.push(add)\r\n }\r\n }\r\n return console.log(res.join(' '))\r\n var map2 = {}\r\n Object.keys(count).map(key => {\r\n if (!map2[count[key]]) map2[count[key]] = 0\r\n map2[count[key]]++\r\n\r\n })\r\n var keys = Object.keys(map2).map(x => parseInt(x)).sort((a, b) => map2[a] - map2[b])\r\n\r\n var sum = new Array(keys.length + 1).fill(0)\r\n\r\n var ans = n\r\n for (let i = 0; i < keys.length; i++) {\r\n sum = 0\r\n for (let j = 0; j < keys.length; j++) {\r\n if (keys[j] < keys[i]) sum += map2[keys[j]] * keys[j]\r\n if (keys[j] > keys[i]) sum += (keys[j] - keys[i]) * map2[keys[j]]\r\n }\r\n ans = Math.min(ans, sum)\r\n }\r\n // console.log(keys)\r\n // console.log(map2)\r\n // console.log(sum)\r\n console.log(ans)\r\n\r\n })\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tfor (let j = i + 1; j < n; j++)\r\n\t\t\t\tif (j-i <= Math.floor((n-1)/2)) ans.push(1);\r\n\t\t\t\telse if (n%2 == 0 && j-i == n/2) ans.push(0);\r\n\t\t\t\telse ans.push(-1);\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.join(' '));\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n var x = Number(readline())\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var n = parseInt(readline())\r\n if( n===2) return console.log(0)\r\n if (n % 2 === 1) {\r\n var res = []\r\n for (var i = 0; i < (n * (n - 1)) / 2; i++) {\r\n if (i % 2 === 0) res.push(1)\r\n else res.push(-1)\r\n }\r\n return console.log(res.join(' '))\r\n }\r\n var res = [1]\r\n for (var i = n-1; i >= 2; i--) {\r\n res.push(-1)\r\n for (var j = 0; j < i-1; j++) {\r\n res.push(0)\r\n }\r\n }\r\n console.log(res.join(' '))\r\n\r\n\r\n // for (var i = 3; i*i <= n*4; i=i+2) {\r\n // var b = Math.floor((i*i-1)/2)\r\n// console.log(i*i, b,b+1)\r\n// if(b*2+1===i*i && b*2+1 <= n && b>0) {\r\n// console.log(i,b,b+1 )\r\n// count++\r\n// }\r\n// }\r\n // var mid = Math.fl/oor(n/2)\r\n // var res = Math.floor((k-1) / mid)\r\n\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n var x = Number(readline())\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var n = parseInt(readline())\r\n if (n % 2 === 1) {\r\n var res = []\r\n for (var i = 0; i < (n * (n - 1)) / 2; i++) {\r\n if (i % 2 === 0) res.push(1)\r\n else res.push(-1)\r\n }\r\n console.log(res.join(' '))\r\n }\r\n var res = [1]\r\n for (var i = n-1; i >= 2; i--) {\r\n res.push(-1)\r\n for (var j = 0; j < i-1; j++) {\r\n res.push(0)\r\n }\r\n }\r\n console.log(res.join(' '))\r\n\r\n\r\n // for (var i = 3; i*i <= n*4; i=i+2) {\r\n // var b = Math.floor((i*i-1)/2)\r\n// console.log(i*i, b,b+1)\r\n// if(b*2+1===i*i && b*2+1 <= n && b>0) {\r\n// console.log(i,b,b+1 )\r\n// count++\r\n// }\r\n// }\r\n // var mid = Math.fl/oor(n/2)\r\n // var res = Math.floor((k-1) / mid)\r\n\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n\r\n\r\n"}], "src_uid": "a89c585ebd9608141399c813385c04c6"} {"nl": {"description": "It is the hard version of the problem. The only difference is that in this version $$$1 \\le n \\le 300$$$.In the cinema seats can be represented as the table with $$$n$$$ rows and $$$m$$$ columns. The rows are numbered with integers from $$$1$$$ to $$$n$$$. The seats in each row are numbered with consecutive integers from left to right: in the $$$k$$$-th row from $$$m (k - 1) + 1$$$ to $$$m k$$$ for all rows $$$1 \\le k \\le n$$$. $$$1$$$$$$2$$$$$$\\cdots$$$$$$m - 1$$$$$$m$$$$$$m + 1$$$$$$m + 2$$$$$$\\cdots$$$$$$2 m - 1$$$$$$2 m$$$$$$2m + 1$$$$$$2m + 2$$$$$$\\cdots$$$$$$3 m - 1$$$$$$3 m$$$$$$\\vdots$$$$$$\\vdots$$$$$$\\ddots$$$$$$\\vdots$$$$$$\\vdots$$$$$$m (n - 1) + 1$$$$$$m (n - 1) + 2$$$$$$\\cdots$$$$$$n m - 1$$$$$$n m$$$ The table with seats indices There are $$$nm$$$ people who want to go to the cinema to watch a new film. They are numbered with integers from $$$1$$$ to $$$nm$$$. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $$$i$$$-th person has the level of sight $$$a_i$$$. Let's define $$$s_i$$$ as the seat index, that will be given to $$$i$$$-th person. You want to give better places for people with lower sight levels, so for any two people $$$i$$$, $$$j$$$ such that $$$a_i < a_j$$$ it should be satisfied that $$$s_i < s_j$$$.After you will give seats to all people they will start coming to their seats. In the order from $$$1$$$ to $$$nm$$$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: $$$m = 5$$$, the person has the seat $$$4$$$ in the first row, the seats $$$1$$$, $$$3$$$, $$$5$$$ in the first row are already occupied, the seats $$$2$$$ and $$$4$$$ are free. The inconvenience of this person will be $$$2$$$, because he will go through occupied seats $$$1$$$ and $$$3$$$.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 300$$$) — the number of rows and places in each row respectively. The second line of each test case contains $$$n \\cdot m$$$ integers $$$a_1, a_2, \\ldots, a_{n \\cdot m}$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the sight level of $$$i$$$-th person. It's guaranteed that the sum of $$$n \\cdot m$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print a single integer — the minimal total inconvenience that can be achieved.", "sample_inputs": ["7\n1 2\n1 2\n3 2\n1 1 2 2 3 3\n3 3\n3 4 4 1 1 1 1 1 2\n2 2\n1 1 2 1\n4 2\n50 50 50 50 3 50 50 50\n4 2\n6 6 6 6 2 2 9 6\n2 9\n1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3"], "sample_outputs": ["1\n0\n4\n0\n0\n0\n1"], "notes": "NoteIn the first test case, there is a single way to give seats: the first person sits in the first place and the second person — in the second. The total inconvenience is $$$1$$$.In the second test case the optimal seating looks like this: In the third test case the optimal seating looks like this: The number in a cell is the person's index that sits on this place."}, "positive_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, m] = rna();\r\n\t\tconst a = rna();\r\n\r\n\t\tconst b = [];\r\n\t\tfor (let i = 0; i < n*m; i++) b[i] = [a[i], i];\r\n\t\tb.sort((x, y) => x[0] - y[0]);\r\n\r\n\t\tconst s = [];\r\n\t\tfor (let i = 0; i < n*m; i++) s[b[i][1]] = i;\r\n\r\n\t\tlet ans = 0;\r\n\t\tlet g = Array.from(Array(n), _ => []);\r\n\t\tfor (let i = 0; i < n*m; i++) {\r\n\t\t\tconst row = Math.floor(s[i] / m);\r\n\t\t\tconst col = s[i] % m ;\r\n\t\t\tfor (let j = 0; j < col; j++) {\r\n\t\t\t\tans += g[row][j] < a[i];\r\n\t\t\t}\r\n\t\t\tg[row][col] = a[i];\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "99c5e62d8e51e61cfd0c2531a231e7a8"} {"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, 0), 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, 0) 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, yu) 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 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. 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 ≤ 105. 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 — 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": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar integers = tokenizeIntegers(readline());\n\tvar stopNum = integers[0], busSpeed = integers[1], runSpeed = integers[2];\n\tvar xs = tokenizeIntegers(readline());\n\tvar integers = tokenizeIntegers(readline());\n\tvar xTarget = integers[0], yTarget = integers[1];\n\n\tfunction getDistance(x0, y0, x1, y1) {\n\t\treturn Math.sqrt(Math.pow(x1-x0, 2) + Math.pow(y1-y0, 2));\n\t}\n\n\tvar records = [];\n\n\tfor (var i = 1; i < xs.length; i += 1) {\n\t\tvar distance = getDistance(xs[i], 0, xTarget, yTarget);\n\t\tvar time = xs[i]/busSpeed + distance/runSpeed;\n\t\trecords.push({ distance: distance, time: time, id: i+1 });\n\t}\n\n\trecords.sort(function(a, b) {\n\t\treturn (a.time == b.time ? a.distance - b.distance : a.time - b.time);\n\t});\n\n\tprint(records[0].id);\n}\n\nmain();\n"}, {"source_code": "var lll = readline().split(' ')\nvar on = lll[0]\nvar vb = lll[1]\nvar vs = lll[2]\n\nvar os = readline().split(' ')\nlll = readline().split(' ')\nvar ux = lll[0]\nvar uy = lll[1]\n\nvar t = 0\nvar pot\nvar lo\n\nfor (var i = 1; i < on; i++) {\n var tv = t + st(i)\n if (pot && pot < tv) {\n lo = i - 1\n break\n } else if (pot && pot == tv) {\n lo = i\n break\n }\n pot = tv\n t += bt(i)\n}\n\nif (!lo) lo = os.length - 1\n\nprint(+lo + 1)\n\nfunction st (o) {\n var ox = os[o]\n return Math.sqrt((ux - ox) * (ux - ox) + uy * uy) / vs\n}\n\nfunction bt (o) {\n if (o == os.length) return 0\n var to = os[o]\n var so = os[o + 1]\n return (so - to) / vb\n}"}, {"source_code": "\"use strict\";\nvar input = '';\nvar inputResolve;\nvar inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => {\n inputResolve();\n});\nfunction gcd(a, b) {\n if (b == 0)\n return a;\n if (a < b)\n return gcd(b, a);\n return gcd(b, a % b);\n}\n(async () => {\n // var time = Date.now();\n await inputPromise;\n var inputs = input.split(/\\r?\\n/);\n var [n, vb, vs] = inputs[0].split(' ').map(v => +v);\n var arr = inputs[1].split(' ').map(v => +v);\n var [x, y] = inputs[2].split(' ').map(v => +v);\n var min = 1e10;\n var resDis = 0;\n var resId = 0;\n for (let i = 1; i < n; i++) {\n let dis = Math.sqrt((arr[i] - x) ** 2 + y * y);\n let t = arr[i] / vb + dis / vs;\n if (t < min || (t == min && dis < resDis)) {\n min = t;\n resId = i;\n resDis = dis;\n }\n }\n console.log(resId + 1);\n})();\n"}], "negative_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar integers = tokenizeIntegers(readline());\n\tvar stopNum = integers[0], busSpeed = integers[1], runSpeed = integers[2];\n\tvar xs = tokenizeIntegers(readline());\n\tvar integers = tokenizeIntegers(readline());\n\tvar xTarget = integers[0], yTarget = integers[1];\n\n\tfunction dist(x0, y0, x1, y1) {\n\t\treturn Math.sqrt(Math.pow(x1-x0, 2) + Math.pow(y1-y0, 2));\n\t}\n\n\tvar bestStop = 1;\n\tvar bestTime = xs[1]/busSpeed + dist(xs[1], 0, xTarget, yTarget)/runSpeed;\n\n\tfor (var i = 2; i < xs.length; i += 1) {\n\t\tvar time = xs[i]/busSpeed + dist(xs[i], 0, xTarget, yTarget)/runSpeed;\n\t\tif (time < bestTime) {\n\t\t\tbestTime = time;\n\t\t\tbestStop = i;\n\t\t}\n\t}\n\n\tprint(bestStop+1);\n}\n\nmain();\n"}], "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$$$) — the length of the song and the number of questions. The second line contains one string $$$s$$$ — 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$$$) — 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": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n }\r\n for(let i = 0; iparseInt(num));\r\n let res = pre[r-1];\r\n if (l>1)\r\n res-=pre[l-2];\r\n console.log(res);\r\n }\r\n\r\n}\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (pre[i] === undefined) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (!Number.isInteger(l) || !Number.isInteger(r)) {\r\n i--;\r\n continue;\r\n //throw new Error('not interger');\r\n }\r\n l = Math.floor(l + 0.000001);\r\n r = Math.floor(r + 0.000001);\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /* if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n } */\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n \r\n \r\nfunction main() {\r\n\r\n \tlet testCaseNum = readline();\r\n\ttestCaseNum = testCaseNum.split(' ').filter(item => +item);\r\n\ttestCaseNum = testCaseNum[1];\r\n\r\n \tlet str = readline();\r\n\r\n\tlet prefix = new Array(str.length).fill(0);\r\n\tprefix[-1] = 0;\r\n\tfor (let i = 0; i < str.length; i++) {\r\n\t\tprefix[i] += prefix[i - 1];\r\n\t\tprefix[i] += (str[i].charCodeAt() - 96);\r\n\t}\r\n\t\r\n \twhile (testCaseNum) {\r\n \t\tlet tmp = readline();\r\n \t\ttmp = tmp.split(' ').filter(item => +item);\r\n\r\n\t\tconsole.log(prefix[tmp[1] - 1] - prefix[tmp[0] - 2]);\r\n \t\ttestCaseNum --;\r\n \t}\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, a, b) {\r\n const sum = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _sum;\r\n sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + a.charCodeAt(i) - 96;\r\n }\r\n const res = [];\r\n for (let [l, r] of b) {\r\n var _sum2;\r\n l--, r--;\r\n res.push(sum[r] - ((_sum2 = sum[l - 1]) !== null && _sum2 !== void 0 ? _sum2 : 0));\r\n }\r\n return res.join('\\n');\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = await read();\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(n, m, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "function gcd(x, y) {\r\n if (y === 0) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction div(a, b) {\r\n return Math.floor(a / b);\r\n}\r\n\r\nfunction solve() {\r\n var nq = readArray(Number);\r\n var n = nq[0];\r\n var q = nq[1];\r\n var s = read();\r\n var charCodeA = 'a'.charCodeAt(0);\r\n var sum = [0];\r\n for (var i = 0; i < n; i++) {\r\n var num = s.charCodeAt(i) - charCodeA + 1;\r\n sum.push(num + sum[i]);\r\n }\r\n for(var i = 0; i < q; i++) {\r\n var lr = readArray(Number);\r\n var l = lr[0];\r\n var r = lr[1];\r\n write(sum[r] - sum[l - 1]);\r\n }\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n //T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}));\r\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n});\r\nvar __importStar = (this && this.__importStar) || function (mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst fs = __importStar(require(\"fs\"));\r\n// import * as readline from 'readline'\r\n// const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\r\n// const ask = (query: string) => new Promise((resolve) => rl.question(query, resolve))\r\n// // Don't forget `rl.close()`.\r\nconst INT = Math.floor;\r\nArray.prototype.last = function () {\r\n return this.length === 0 ? undefined : this[this.length - 1];\r\n};\r\nArray.prototype.isEmpty = function () {\r\n return this.length === 0;\r\n};\r\nconst less = (a, b) => (a == b ? 0 : a < b ? -1 : 1);\r\nconst greater = (a, b) => (a == b ? 0 : a < b ? 1 : -1);\r\nconst bigIntMax = (...args) => args.reduce((m, e) => (e > m ? e : m));\r\nconst bigIntMin = (...args) => args.reduce((m, e) => (e < m ? e : m));\r\nconst bigIntAbs = (arg) => (arg < 0 ? -arg : arg);\r\nfunction read_stdin() {\r\n return fs.readFileSync(process.env.NODE_ENV === 'debug' ? stdin : process.stdin.fd, 'utf8');\r\n}\r\nclass Input {\r\n constructor(str) {\r\n this.index = 0;\r\n this.inputs = (str ? str : read_stdin()).split(/\\s+/);\r\n }\r\n number() {\r\n return Number(this.inputs[this.index++]);\r\n }\r\n numbers(n) {\r\n return this.inputs.slice(this.index, (this.index += n)).map(Number);\r\n }\r\n bigint() {\r\n return BigInt(this.inputs[this.index++]);\r\n }\r\n bigints(n) {\r\n return this.inputs.slice(this.index, (this.index += n)).map(BigInt);\r\n }\r\n word() {\r\n return this.inputs[this.index++];\r\n }\r\n words(n) {\r\n return this.inputs.slice(this.index, (this.index += n));\r\n }\r\n}\r\nfunction array(len, init) {\r\n return Array(len).fill(init);\r\n}\r\nfunction array2(h, w, init) {\r\n return array(h, 0).map(() => array(w, init));\r\n}\r\nfunction main() {\r\n const input = new Input();\r\n const n = input.number();\r\n const q = input.number();\r\n const a = 'a'.charCodeAt(0);\r\n const s = input.word();\r\n const snums = Array.from(s).map((c) => c.charCodeAt(0) - a + 1);\r\n const cumu = array(n + 1, 0);\r\n for (let i = 0; i < n; i++) {\r\n cumu[i + 1] = cumu[i] + snums[i];\r\n }\r\n const ans = Array(q);\r\n for (let i = 0; i < q; i++) {\r\n const l = input.number();\r\n const r = input.number();\r\n ans[i] = cumu[r] - cumu[l - 1];\r\n }\r\n console.log(ans.join('\\n'));\r\n}\r\nmain();\r\n//# sourceMappingURL=aoj.js.map"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var l = 0;\n var [n, q] = lines[l++].split(' ').map(Number);\n var str = lines[l++];\n var qs = [];\n for (var i = 0; i < q; i++) {\n var range = lines[l++].split(' ').map(Number)\n qs.push(range)\n }\n console.log(solve(str, qs))\n});\n\nfunction solve(str, qs) {\n const count = []\n let cur\n for (let i = 0; i < str.length; i++) {\n const ch = str[i]\n if (i) {\n cur = { ...cur }\n cur[ch] = (cur[ch] || 0) + 1\n } else {\n cur = {}\n cur[ch] = 1\n }\n count[i] = cur\n }\n\n return qs.map(([l, r]) => {\n l--\n r--\n // count[r] - count[l - 1]\n let sum = 0\n for (let ch in count[r]) {\n const k = ch.charCodeAt(0) - 'a'.charCodeAt(0) + 1\n if (l) {\n sum += (count[r][ch] - (count[l - 1][ch] || 0)) * k\n } else {\n sum += count[r][ch] * k\n }\n }\n return sum\n }).join('\\n')\n}\n"}, {"source_code": "nq = readline().split(' ');\r\nn = +nq[0];\r\nq = +nq[1];\r\n\r\nstr = readline();\r\n\r\na = [0];\r\n\r\nlen = str.length;\r\nfor (i = 0; i < len; ++i) {\r\n x = str.charCodeAt(i) - 96\r\n\r\n a.push(x + a[i])\r\n}\r\n\r\nfor (i = 0; i < q; ++i) {\r\n lr = readline().split(' ')\r\n l = +lr[0];\r\n r = +lr[1];\r\n\r\n print(a[r] - a[l - 1]);\r\n}"}], "negative_code": [{"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n }\r\n for(let i = 0; iparseInt(num));\r\n let res = pre[r-1];\r\n if (l>1)\r\n res-=pre[l-2];\r\n console.log(res);\r\n }\r\n\r\n}\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n }\r\n for(let i = 0; iparseInt(num));\r\n let res = pre[r];\r\n if (l>1)\r\n res-=pre[l-1];\r\n console.log(res);\r\n }\r\n\r\n}\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n }\r\n for(let i = 0; i1)\r\n res-=pre[l-1];\r\n console.log(res);\r\n }\r\n\r\n}\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (pre[i] === undefined) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (!Number.isInteger(l) || !Number.isInteger(r)) {\r\n throw new Error('not interger');\r\n }\r\n l = Math.floor(l + 0.000001);\r\n r = Math.floor(r + 0.000001);\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /* if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n } */\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (pre[i] === undefined) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (!Number.isInteger(l) || !Number.isInteger(r)) {\r\n throw new Error('not interger');\r\n }\r\n l = Math.floor(l + 0.000001);\r\n r = Math.floor(r + 0.000001);\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /* if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n } */\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (pre[i] === undefined) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (!Number.isInteger(l) || !Number.isInteger(r)) {\r\n throw new Error('not interger');\r\n }\r\n l = Math.floor(l + 0.000001);\r\n r = Math.floor(r + 0.000001);\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /* if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n } */\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (pre[i] === undefined) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n l = Math.floor(l + 0.000001);\r\n r = Math.floor(r + 0.000001);\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /* if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n } */\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(pre[i])) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n l = Math.floor(l + 0.000001);\r\n r = Math.floor(r + 0.000001);\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /* if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n } */\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(pre[i])) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n l = Math.floor(l + 0.000001);\r\n r = Math.floor(r + 0.000001);\r\n /* if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');*/\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /* if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n } */\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(pre[i])) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n /* if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');*/\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n if (pre[r-1] === undefined || (l !== 1 && pre[l-2] === undefined)){\r\n throw new Error(i + '');\r\n }\r\n\r\n /* if (res === undefined)\r\n throw new Error('ololo'); */\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(pre[i])) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n /* if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');*/\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /*if (Number.isNaN(pre[r-1]) || (l !== 1 && Number.isNaN(pre[l-2]))){\r\n throw new Error(i + '');\r\n }*/\r\n if (res === undefined)\r\n throw new Error('ololo');\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(pre[i])) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n /* if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');*/\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /*if (Number.isNaN(pre[r-1]) || (l !== 1 && Number.isNaN(pre[l-2]))){\r\n throw new Error(i + '');\r\n }*/\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(pre[i])) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /*if (Number.isNaN(pre[r-1]) || (l !== 1 && Number.isNaN(pre[l-2]))){\r\n throw new Error(i + '');\r\n }*/\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(pre[i])) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n if (Number.isNaN(pre[r-1]) || (l !== 1 && Number.isNaN(pre[l-2]))){\r\n throw new Error(i + '');\r\n }\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst fs = require('fs');\r\nconst rl = lib.createInterface({\r\n input: process.stdin, // fs.createReadStream('input.txt'),\r\n output: process.stdout\r\n});\r\n//const inp = fs.createReadStream('input.txt');\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(Number(pre[i]))) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n if (Number.isNaN(pre[r-1]) || (l !== 1 && Number.isNaN(pre[l-2]))){\r\n throw new Error(i + '');\r\n }\r\n console.log(res);\r\n }\r\n\r\n}\r\n\r\n/*let txtFile = fs.createWriteStream('output2.txt', {flags:'a'});\r\ntxtFile.write('100000 100000\\n');\r\nconst acode = 'a'.charCodeAt(0);\r\nfor(let i = 0; i<100000; i++){\r\n txtFile.write(String.fromCharCode(i%20 + acode));\r\n}\r\ntxtFile.write('\\n');\r\nfor(let i = 0; i<100000; i++)\r\n txtFile.write('1 ' + (i + 1) + '\\n');\r\n*/\r\nsolve();\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(Number(pre[i]))) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res -= pre[l-2];\r\n /*if (Number.isNaN(Number(pre[r-1])) || (l !== 1 && Number.isNaN(Number(pre[l-2])))){\r\n throw new Error(i + '');\r\n }*/\r\n console.log(res);\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(Number(pre[i]))) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>1)\r\n res += pre[l-2];\r\n /*if (Number.isNaN(Number(pre[r-1])) || (l !== 1 && Number.isNaN(Number(pre[l-2])))){\r\n throw new Error(i + '');\r\n }*/\r\n console.log(res);\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(Number(pre[i]))) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res = pre[r-1];\r\n if (l>2)\r\n res += pre[l-2];\r\n /*if (Number.isNaN(Number(pre[r-1])) || (l !== 1 && Number.isNaN(Number(pre[l-2])))){\r\n throw new Error(i + '');\r\n }*/\r\n console.log(res);\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = 'a'.charCodeAt(0) - 1;\r\n pre[0] = s.charCodeAt(0) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + s.charCodeAt(i) - zeroCharCode;\r\n if (Number.isNaN(Number(pre[i]))) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n /*if (Number.isNaN(Number(pre[r-1])) || (l !== 1 && Number.isNaN(Number(pre[l-2])))){\r\n throw new Error(i + '');\r\n }*/\r\n console.log(res);\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n if (Number.isNaN(Number(pre[i]))) {\r\n throw new Error(i + ' ');\r\n }\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n /*if (Number.isNaN(Number(pre[r-1])) || (l !== 1 && Number.isNaN(Number(pre[l-2])))){\r\n throw new Error(i + '');\r\n }*/\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n if (Number.isNaN(Number(pre[r-1])) || (l !== 1 && Number.isNaN(Number(pre[l-2])))){\r\n throw new Error(i + '');\r\n }\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n if (Number.isNaN(Number(res))){\r\n throw new Error(i + '');\r\n }\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n if (Number.isNaN(res.asIntN())){\r\n throw new Error(i + '');\r\n }\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n if (Number.isNan(res.asIntN())){\r\n throw new Error(i + '');\r\n }\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n const cur =s.charCodeAt(0);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(0));\r\n throw new Error('test');\r\n }\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n const cur =s.charCodeAt(i);\r\n if (Number.isNaN(cur)) {\r\n console.log(i + ' ' + s.charAt(i));\r\n throw new Error('test');\r\n }\r\n\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n if (s.length !== n)\r\n throw new Error('test');\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n if (l<1 || l>n || r<1 || r>n)\r\n throw new Error('test');\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(n);\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(s.length);\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n for(let i = 1; i < n; i++) {\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n let n, q;\r\n [n, q] = (await getLine()).split(' ').map(num => parseInt(num));\r\n const s = await getLine();\r\n const pre = new Array(s.length);\r\n const zeroCharCode = BigInt('a'.charCodeAt(0)) - BigInt(1);\r\n pre[0] = BigInt(s.charCodeAt(0)) - zeroCharCode;\r\n for(let i = 1; i < s.length; i++) {\r\n pre[i] = pre[i-1] + BigInt(s.charCodeAt(i)) - zeroCharCode;\r\n }\r\n for(let i = 0; i parseInt(num));\r\n let res;\r\n if (l == 1)\r\n res = pre[r - 1];\r\n else\r\n res = pre[r-1] - pre[l-2];\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n \r\n \r\nfunction main() {\r\n\r\n \tlet testCaseNum = readline();\r\n\ttestCaseNum = testCaseNum.split(' ').filter(item => +item);\r\n\ttestCaseNum = testCaseNum[1];\r\n\r\n \tlet str = readline();\r\n\r\n \twhile (testCaseNum) {\r\n \t\tlet tmp = readline();\r\n \t\ttmp = tmp.split(' ').filter(item => +item);\r\n\r\n \t\tlet ret = '';\r\n\t\tfor (let i = tmp[0] - 1; i <= tmp[1] - 1; i++) {\r\n\t\t\tif (str[i] == 'a') {\r\n\t\t\t\tret += 'a';\r\n\t\t\t} else if (str[i] == 'b') {\r\n\t\t\t\tret += 'bb';\r\n\t\t\t} else if (str[i] == 'c'){\r\n\t\t\t\tret += 'ccc';\r\n\t\t\t}\r\n\t\t}\r\n\t\tconsole.log(ret.length);\r\n \t\ttestCaseNum --;\r\n \t}\r\n}\r\n"}], "src_uid": "461378e9179c9de454674ea9dc49c56c"} {"nl": {"description": "A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.", "input_spec": "The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.", "output_spec": "Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.", "sample_inputs": ["5\n0 1 3 4 2"], "sample_outputs": ["3"], "notes": null}, "positive_code": [{"source_code": "var n = +readline();\n\nvar a = readline().split( ' ' ).map( Number );\n\nvar ans = 0;\nvar f = 1;\n\nfor( var i = 0; i < n; i++ )\n\tif( a[i] === i ) ans++;\n\telse if( a[ a[ i ] ] === i ) f = 2;\n\n\nprint( Math.min( n, ans + f ) );"}, {"source_code": ";(function () {\n\n\tvar n = +readline();\n\tvar t = readline().split(' ').map(Number);\n\tvar a = t.map(function (e, i) { return [i, e]; }).filter(function (e) { return e[0] != e[1]; });;\n\tvar l = a.length;\n\n\tif (a.length < 2) {\n\t\tprint(n - a.length);\n\t\treturn;\n\t}\n\n\tfor (var i = 0; i < l - 1; i++)\n\t\tif (a[i][0] == t[a[i][1]] && a[i][1] == t[a[i][0]]) {\n\t\t\tprint(n - a.length + 2);\n\t\t\treturn;\n\t\t}\n\n\tprint(n - a.length + 1);\n\n}).call(this);"}, {"source_code": "(function (){\n var i, n = parseInt(readline());\n var a = readline().split(' ');\n var fixed = 0, swap = 0;\n for ( i = 0 ; i < n ; ++i){\n if ( i == a[i] ){\n ++fixed;\n }else if ( i == a[a[i]] ){\n ++swap;\n }\n }\n if ( swap > 0 ){\n fixed += 2;\n }else if ( fixed != n ){\n fixed += 1;\n }\n print(fixed);\n})();"}], "negative_code": [{"source_code": ";(function () {\n\n\tvar n = +readline();\n\tvar a = readline().split(' ').map(function (e, i) { return [i, e]; }).filter(function (e) { return e[0] != e[1]; });;\n\tvar l = a.length;\n\n\tif (a.length < 2) {\n\t\tprint(n - a.length);\n\t\treturn;\n\t}\n\n\tfor (var i = 0; i < l - 1; i++)\n\t\tfor (var j = i + 1; j < l; j++) {\n\t\t\tif (a[j][0] === a[i][1] && a[j][1] === a[i][0]) {\n\t\t\t\tprint(n - a.length + 2);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\tprint(n - a.length + 1);\n\n}).call(this);"}], "src_uid": "e63de0fffd00b2da103545a7f1e405be"} {"nl": {"description": "Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \\dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \\dots, i$$$ by $$$1$$$. Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \\dots, n$$$ by $$$1$$$. Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$)  — the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 200\\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$) — the initial levels of trees moisture. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\\,000$$$.", "output_spec": "For each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.", "sample_inputs": ["4\n3\n-2 -2 -2\n3\n10 4 7\n4\n4 -4 4 -4\n5\n1 -2 3 -4 5"], "sample_outputs": ["2\n13\n36\n33"], "notes": "NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n let res = 0;\r\n const segTree = new SegTree(a);\r\n for (let r = n - 2; r >= 0; r--) {\r\n let cur = segTree.query(r, r);\r\n if (cur > a[r + 1]) {\r\n let dif = cur - a[r + 1];\r\n res += dif;\r\n segTree.update(0, r, -dif);\r\n cur = a[r + 1];\r\n }\r\n a[r] = cur;\r\n }\r\n const x = segTree.query(0, 0),\r\n y = segTree.query(n - 1, n - 1);\r\n if (x >= 0) res += y;else res += -x + y - x;\r\n return res;\r\n}\r\nclass SegTree {\r\n constructor(nums = [], n = nums.length - 1) {\r\n this.nums = nums;\r\n this.n = n;\r\n this.root = this._newNode();\r\n this._build(this.root, 0, n);\r\n this.update = (x, y, z) => {\r\n x = Math.max(x, 0);\r\n y = Math.min(y, n);\r\n return this._update(this.root, 0, n, x, y, z);\r\n };\r\n this.query = (x, y) => {\r\n x = Math.max(x, 0);\r\n y = Math.min(y, n);\r\n return this._query(this.root, 0, n, x, y);\r\n };\r\n }\r\n _newNode(val = 0, left = null, right = null) {\r\n return {\r\n val,\r\n left,\r\n right,\r\n add: 0\r\n };\r\n }\r\n _down(node, l, r) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n const mid = Math.floor((l + r) / 2);\r\n left.add += node.add;\r\n left.val += node.add * (mid - l + 1);\r\n right.add += node.add;\r\n right.val += node.add * (r - mid);\r\n node.add = 0;\r\n }\r\n _up(node) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n node.val = left.val + right.val;\r\n }\r\n _build(node = this.root, l, r) {\r\n if (l === r) {\r\n var _this$nums$l;\r\n node.val = (_this$nums$l = this.nums[l]) !== null && _this$nums$l !== void 0 ? _this$nums$l : 0;\r\n return;\r\n }\r\n const mid = Math.floor((l + r) / 2);\r\n node.left = this._newNode();\r\n node.right = this._newNode();\r\n this._build(node.left, l, mid);\r\n this._build(node.right, mid + 1, r);\r\n node.val = node.left.val + node.right.val;\r\n }\r\n _update(node, l, r, x, y, z) {\r\n if (!node) return;\r\n if (l === x && r === y) {\r\n node.add += z;\r\n node.val += z * (r - l + 1);\r\n return;\r\n }\r\n this._down(node, l, r);\r\n const mid = Math.floor((l + r) / 2);\r\n if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);\r\n this._up(node);\r\n }\r\n _query(node, l, r, x, y) {\r\n if (y < x) return 0;\r\n if (!node) return 0;\r\n if (l === x && r === y) return node.val;\r\n this._down(node, l, r);\r\n let res = 0,\r\n mid = Math.floor((l + r) / 2);\r\n if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else res = this._query(node.left, l, mid, x, mid) + this._query(node.right, mid + 1, r, mid + 1, y);\r\n this._up(node);\r\n return res;\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n let res = 0;\r\n const segTree = new SegTree(a);\r\n for (let r = n - 2; r >= 0; r--) {\r\n let cur = segTree.query(r, r);\r\n if (cur > a[r + 1]) {\r\n let dif = cur - a[r + 1];\r\n res += dif;\r\n segTree.update(0, r, -dif);\r\n cur = a[r + 1];\r\n }\r\n a[r] = cur;\r\n }\r\n const x = segTree.query(0, 0),\r\n y = segTree.query(n - 1, n - 1);\r\n res += -x + y - x;\r\n return res;\r\n}\r\nclass SegTree {\r\n constructor(nums = [], n = nums.length - 1) {\r\n this.nums = nums;\r\n this.n = n;\r\n this.root = this._newNode();\r\n this._build(this.root, 0, n);\r\n this.update = (x, y, z) => {\r\n x = Math.max(x, 0);\r\n y = Math.min(y, n);\r\n return this._update(this.root, 0, n, x, y, z);\r\n };\r\n this.query = (x, y) => {\r\n x = Math.max(x, 0);\r\n y = Math.min(y, n);\r\n return this._query(this.root, 0, n, x, y);\r\n };\r\n }\r\n _newNode(val = 0, left = null, right = null) {\r\n return {\r\n val,\r\n left,\r\n right,\r\n add: 0\r\n };\r\n }\r\n _down(node, l, r) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n const mid = Math.floor((l + r) / 2);\r\n left.add += node.add;\r\n left.val += node.add * (mid - l + 1);\r\n right.add += node.add;\r\n right.val += node.add * (r - mid);\r\n node.add = 0;\r\n }\r\n _up(node) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n node.val = left.val + right.val;\r\n }\r\n _build(node = this.root, l, r) {\r\n if (l === r) {\r\n var _this$nums$l;\r\n node.val = (_this$nums$l = this.nums[l]) !== null && _this$nums$l !== void 0 ? _this$nums$l : 0;\r\n return;\r\n }\r\n const mid = Math.floor((l + r) / 2);\r\n node.left = this._newNode();\r\n node.right = this._newNode();\r\n this._build(node.left, l, mid);\r\n this._build(node.right, mid + 1, r);\r\n node.val = node.left.val + node.right.val;\r\n }\r\n _update(node, l, r, x, y, z) {\r\n if (!node) return;\r\n if (l === x && r === y) {\r\n node.add += z;\r\n node.val += z * (r - l + 1);\r\n return;\r\n }\r\n this._down(node, l, r);\r\n const mid = Math.floor((l + r) / 2);\r\n if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);\r\n this._up(node);\r\n }\r\n _query(node, l, r, x, y) {\r\n if (y < x) return 0;\r\n if (!node) return 0;\r\n if (l === x && r === y) return node.val;\r\n this._down(node, l, r);\r\n let res = 0,\r\n mid = Math.floor((l + r) / 2);\r\n if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else res = this._query(node.left, l, mid, x, mid) + this._query(node.right, mid + 1, r, mid + 1, y);\r\n this._up(node);\r\n return res;\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const min = Math.min(...a);\r\n let res = 0,\r\n lz = -1,\r\n rz = -1;\r\n if (min < 0) {\r\n res += Math.abs(min);\r\n a = a.map(num => num + Math.abs(min));\r\n } else if (min > 0) {\r\n res += min;\r\n a = a.map(num => num - min);\r\n }\r\n for (let [i, num] of a.entries()) {\r\n if (num === 0) {\r\n if (lz === -1) lz = i;\r\n rz = i;\r\n }\r\n }\r\n const segTree = new SegTree(a);\r\n for (let i = 0; i < n; i++) {\r\n let [min, mi] = segTree.min(0, n - 1);\r\n if (min === 0) break;\r\n if (mi < lz) {\r\n res += min;\r\n segTree.update(0, lz - 1, -min);\r\n } else if (mi > rz) {\r\n res += min;\r\n segTree.update(rz + 1, n - 1, -min);\r\n } else {\r\n res += min * 3;\r\n segTree.update(0, n - 1, min);\r\n segTree.update(0, mi, -min);\r\n segTree.update(mi, n - 1, -min);\r\n }\r\n lz = Math.min(lz, mi);\r\n rz = Math.max(rz, mi);\r\n }\r\n return res;\r\n}\r\nclass SegTree {\r\n constructor(nums = [], n = nums.length - 1) {\r\n this.nums = nums;\r\n this.n = n;\r\n this.root = this._newNode();\r\n this._build(this.root, 0, n);\r\n this.update = (x, y, z) => {\r\n x = Math.max(x, 0);\r\n y = Math.min(y, n);\r\n this._update(this.root, 0, n, x, y, z);\r\n };\r\n this.min = (x, y) => {\r\n x = Math.max(x, 0);\r\n y = Math.min(y, n);\r\n return this._queryMin(this.root, 0, n, x, y);\r\n };\r\n }\r\n _newNode(val = 0, left = null, right = null) {\r\n return {\r\n val,\r\n left,\r\n right,\r\n add: 0,\r\n mi: -1\r\n };\r\n }\r\n _build(node = this.root, l, r) {\r\n if (l === r) {\r\n var _this$nums$l;\r\n node.val = (_this$nums$l = this.nums[l]) !== null && _this$nums$l !== void 0 ? _this$nums$l : 0;\r\n node.mi = l;\r\n return;\r\n }\r\n const mid = Math.floor((l + r) / 2);\r\n node.left = this._newNode();\r\n node.right = this._newNode();\r\n this._build(node.left, l, mid);\r\n this._build(node.right, mid + 1, r);\r\n this._up(node);\r\n }\r\n _down(node) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n if (node.add) {\r\n left.add += node.add;\r\n left.val += node.add;\r\n right.add += node.add;\r\n right.val += node.add;\r\n node.add = 0;\r\n }\r\n if (left.add && left.val === 0) {\r\n this._down(left);\r\n this._up(left);\r\n }\r\n if (right.add && right.val === 0) {\r\n this._down(right);\r\n this._up(right);\r\n }\r\n }\r\n _up(node) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n if (left.val === 0) {\r\n node.val = right.val;\r\n node.mi = right.mi;\r\n } else if (right.val === 0) {\r\n node.val = left.val;\r\n node.mi = left.mi;\r\n } else {\r\n if (left.val <= right.val) {\r\n node.val = left.val;\r\n node.mi = left.mi;\r\n } else {\r\n node.val = right.val;\r\n node.mi = right.mi;\r\n }\r\n }\r\n }\r\n _update(node, l, r, x, y, z) {\r\n if (!node) return;\r\n if (l === x && r === y) {\r\n node.add += z;\r\n node.val += z;\r\n this._down(node);\r\n this._up(node);\r\n return;\r\n }\r\n const mid = Math.floor((l + r) / 2);\r\n if (!node.left) {\r\n node.left = this._newNode();\r\n node.right = this._newNode();\r\n }\r\n this._down(node);\r\n if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);\r\n this._up(node);\r\n }\r\n _queryMin(node, l, r, x, y) {\r\n if (y < x) return [0, -1];\r\n if (!node) return [0, -1];\r\n if (l === x && r === y) return [node.val, node.mi];\r\n let res = [0, -1],\r\n mid = Math.floor((l + r) / 2);\r\n if (!node.left) {\r\n node.left = this._newNode();\r\n node.right = this._newNode();\r\n }\r\n this._down(node);\r\n if (y <= mid) res = this._queryMin(node.left, l, mid, x, y);else if (x > mid) res = this._queryMin(node.right, mid + 1, r, x, y);else {\r\n const [v1, m1] = this._queryMin(node.left, l, mid, x, mid),\r\n [v2, m2] = this._queryMin(node.right, mid + 1, r, mid + 1, y);\r\n if (v1 === 0) {\r\n res = [v2, m2];\r\n } else if (v2 === 0) {\r\n res = [v1, m1];\r\n } else {\r\n if (v1 <= v2) {\r\n res = [v1, m1];\r\n } else {\r\n res = [v2, m2];\r\n }\r\n }\r\n }\r\n this._up(node);\r\n return res;\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "src_uid": "f54c1448a279e59f96847a158f993101"} {"nl": {"description": "Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\\,010\\,111$$$ is a binary decimal, while $$$10\\,201$$$ and $$$787\\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$), denoting the number to be represented.", "output_spec": "For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.", "sample_inputs": ["3\n121\n5\n1000000000"], "sample_outputs": ["2\n5\n1"], "notes": "NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\\,000\\,000\\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\n\r\n\r\nfunction main() {\r\n \r\n let t = parseInt(readline());\r\n \r\n while(t--){\r\n \r\n var n;\r\n var count = 0;\r\n n = parseInt(readline());\r\n \r\n while(n){\r\n var num = n.toString();\r\n var num1 = \"\";\r\n \r\n for(var c in num){\r\n if(num[c]!='0') num1+='1';\r\n else num1+='0';\r\n }\r\n \r\n count++;\r\n n = n - parseInt(num1);\r\n }\r\n console.log(count);\r\n }\r\n \r\n}"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var n = lines[i];\n var x = 0;\n while(n > 0){\n var z = n % 10;\n x = Math.max(x, z);\n n /= 10;\n }\n console.log(Math.floor(x));\n }\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n for(j = 1; j <= n; j++){\n var max = 0;\n var k = lines[j];\n var m = 0;\n var a = 0;\n while(k > 0){\n m = k % 10;\n a = Math.max(a, m);\n k /= 10;\n }\n console.log(Math.floor(a));\n }\n}); \n "}, {"source_code": "var fs = require('fs'), currentline = 0, input = fs.readFileSync(0, 'utf8').trim().split('\\n');\nfunction readline() { return input[currentline++]; }\nvar T = +readline();\nfor (var j = 0; j < T; j++) {\n var n = readline(), ans = 0;\n for (var i = 0; i < n.length; i++)\n ans = Math.max(ans, +n[i]);\n console.log(ans);\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar max = 0;\r\n\t\twhile(N > 0){\r\n\t\t\tmax = Math.max(max, N % 10);\r\n\t\t\tN = Math.floor(N / 10);\r\n\t\t}\r\n\t\tmyout(max);\r\n\t}\r\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n \n \nfunction main() {\n const n = Number(readline());\n\n for(let i = 0; i < n; i++) {\n const decimal = readline().split('').map(Number);\n\n decimal.sort((a,b) => b-a);\n\n console.log(decimal[0]);\n }\n}\n\n\n\n"}, {"source_code": "let i = ''\r\nprocess.stdin.on('data', c => i += c)\r\nprocess.stdin.on('end', () => {\r\n const {EOL} = require('os')\r\n const lines = i.split(EOL) /*your input text, split by lines*/\r\n const size = lines[0];\r\n for(let j = 1; j <= size; j++) {\r\n let max = 0;\r\n let num = lines[j];\r\n while (num !== 0) {\r\n digit = num % 10;\r\n if (digit > max) {\r\n max = digit;\r\n }\r\n num = Math.floor(num / 10);\r\n }\r\n console.log(max);\r\n }\r\n})"}, {"source_code": "let input = '';\nprocess.stdin.on('data', chunk => input += chunk);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = input.split(EOL);\n const count = parseInt(lines[0]);\n for (let i = 1; i <= count; ++i) {\n const solution = solve(lines[i]);\n console.log(solution);\n }\n});\n\nfunction solve(question) {\n let max = 0;\n for (const digit of question) {\n if (digit.match(/^\\d$/)) {\n const num = parseInt(digit);\n if (num > max) {\n max = num;\n }\n }\n }\n return max;\n}\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n/**\r\n3\r\n1\r\n2\r\n3\r\n\r\n\r\n\r\n\r\n**/\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n};\r\n\r\nfunction lcm(a, b) {\r\n return (a / gcd(a, b) * b);\r\n}\r\n\r\nfunction main() { \r\n let n = Number(readline());\r\n\r\n for(let r=0;r {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n/* var arr = readLine().split(\" \").map((x) => {return parseInt(x)});\r\nvar test = readLine();\r\nwhile(test--)\r\n{\r\n\r\n}\r\n*/\r\nfunction main() {\r\n var test = readLine();\r\n \r\n while(test--)\r\n {\r\n var coordinates = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var w = coordinates[0];\r\n var h = coordinates[1];\r\n var x_when_y_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var x_when_y_h = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_w = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var length_of_x_when_y_zero = x_when_y_zero[0] - 1;\r\n var length_of_x_when_y_h = x_when_y_h[0] - 1;\r\n var length_of_y_when_zero = y_when_x_zero[0] - 1;\r\n var length_of_y_when_w = y_when_x_w[0] - 1;\r\n x_when_y_zero.shift();\r\n x_when_y_h.shift();\r\n y_when_x_zero.shift();\r\n y_when_x_w.shift();\r\n x_when_y_zero.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n x_when_y_h.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n y_when_x_zero.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n y_when_x_w.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n var res = [\r\n x_when_y_zero[length_of_x_when_y_zero]-x_when_y_zero[0],\r\n x_when_y_h[length_of_x_when_y_h]-x_when_y_h[0],\r\n y_when_x_zero[length_of_y_when_zero]-y_when_x_zero[0],\r\n y_when_x_w[length_of_y_when_w]-y_when_x_w[0]\r\n ];\r\n \r\n res[0] = res[0]*h;\r\n res[1] = res[1]*h;\r\n res[2] = res[2]*w;\r\n res[3] = res[3]*w;\r\n res.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });\r\n res.reverse();\r\n console.log(res[0]);\r\n }\r\n return 0;\r\n}"}, {"source_code": "'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n/* var arr = readLine().split(\" \").map((x) => {return parseInt(x)});\r\nvar test = readLine();\r\nwhile(test--)\r\n{\r\n\r\n}\r\n*/\r\nfunction main() {\r\n var test = readLine();\r\n \r\n while(test--)\r\n {\r\n var coordinates = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var w = BigInt(coordinates[0]);\r\n var h = BigInt(coordinates[1]);\r\n var x_when_y_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var x_when_y_h = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_w = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var length_of_x_when_y_zero = BigInt(x_when_y_zero[0] - 1);\r\n var length_of_x_when_y_h = BigInt(x_when_y_h[0] - 1);\r\n var length_of_y_when_zero = BigInt(y_when_x_zero[0] - 1);\r\n var length_of_y_when_w = BigInt(y_when_x_w[0] - 1);\r\n x_when_y_zero.shift();\r\n x_when_y_h.shift();\r\n y_when_x_zero.shift();\r\n y_when_x_w.shift();\r\n x_when_y_zero.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n x_when_y_h.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n y_when_x_zero.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n y_when_x_w.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n var res = [\r\n BigInt(x_when_y_zero[length_of_x_when_y_zero]-x_when_y_zero[0]),\r\n BigInt(x_when_y_h[length_of_x_when_y_h]-x_when_y_h[0]),\r\n BigInt(y_when_x_zero[length_of_y_when_zero]-y_when_x_zero[0]),\r\n BigInt(y_when_x_w[length_of_y_when_w]-y_when_x_w[0])\r\n ];\r\n \r\n res[0] = res[0]*h;\r\n res[1] = res[1]*h;\r\n res[2] = res[2]*w;\r\n res[3] = res[3]*w;\r\n res.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });\r\n res.reverse();\r\n console.log(String(res[0]));\r\n }\r\n return 0;\r\n}"}, {"source_code": "\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main(inputString);\n});\n\nfunction log(message){\n if(process.env.NODE_ENV === \"debug\"){\n console.log(message);\n }\n}\n\nfunction main(fileContents) {//input lines as an array\n // console.log(fileContents);\n fileContents.splice(0,1);\n for(let i = 0; i < fileContents.length; i+=5){\n triangleScenarioHigh(fileContents[i],fileContents[i+1],fileContents[i+2],fileContents[i+3],fileContents[i+4])\n }\n}\nfunction triangleScenarioHigh(corner,horizontal0,horizontalY,vertical0,verticalX){\n // console.log(\"corner,horizontal0,horizontalY,vertical0,verticalX\")\n // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)\n\n triangleScenarioLow(corner.split(\" \"),\n horizontal0.split(\" \").slice(1),\n horizontalY.split(\" \").slice(1),\n vertical0.split(\" \").slice(1),\n verticalX.split(\" \").slice(1))\n}\n\nfunction triangleScenarioLow(corner,horizontal0,horizontalY,vertical0,verticalX){\n // console.log(\"corner,horizontal0,horizontalY,vertical0,verticalX\")\n // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)\n const YCorner = parseInt(corner[1]) //8\n const XCorner = parseInt(corner[0]) //5\n const points = [\n [[parseInt(horizontal0[0]),0],[parseInt(horizontal0[horizontal0.length-1]),0]],\n [[parseInt(horizontalY[0]),YCorner],[parseInt(horizontalY[horizontalY.length-1]),YCorner]],\n [[0,parseInt(vertical0[0])],[0,parseInt(vertical0[vertical0.length-1])]],\n [[XCorner,parseInt(verticalX[0])],[XCorner,parseInt(verticalX[verticalX.length-1])]],\n ]\n\n // console.log(\"points\",points) //xxx\n\n let biggestArea = 0\n\n for(i = 0; i < points.length; i++){\n for(i2 = 0; i2 < points.length; i2++){\n if(i !== i2){\n let length1 = Math.sqrt(Math.pow(points[i][0][0] - points[i2][0][0],2) + Math.pow(points[i][0][1] - points[i2][0][1],2))\n let length2 = Math.sqrt(Math.pow(points[i][1][0] - points[i2][0][0],2) + Math.pow(points[i][1][1] - points[i2][0][1],2))\n let length3 = Math.sqrt(Math.pow(points[i][0][0] - points[i][1][0],2) + Math.pow(points[i][0][1] - points[i][1][1],2))\n biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);\n length1 = Math.sqrt(Math.pow(points[i][0][0] - points[i2][1][0],2) + Math.pow(points[i][0][1] - points[i2][1][1],2))\n length2 = Math.sqrt(Math.pow(points[i][1][0] - points[i2][1][0],2) + Math.pow(points[i][1][1] - points[i2][1][1],2))\n length3 = Math.sqrt(Math.pow(points[i][0][0] - points[i][1][0],2) + Math.pow(points[i][0][1] - points[i][1][1],2))\n biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);\n\n }\n }\n }\n\n\n\n console.log(Math.round(biggestArea));\n\n}\n\n\nfunction findArea( a, b, c)\n{\n if (a < 0 || b < 0 || c < 0 ||\n (a + b <= c) || a + c <= b ||\n b + c <= a)\n {\n return -1;\n }\n let s = (a + b + c) / 2;\n return Math.sqrt(s * (s - a) *\n (s - b) * (s - c));\n}\n\n"}, {"source_code": "const getMaximum = arr=>arr[arr.length-1] - arr[1];\r\nconst solve = (w,h,arr)=>{\r\n let t = h,max = 0;\r\n for(let i=1;i<=4;i++){\r\n if(i>2) t = w;\r\n let v = getMaximum(arr[i-1])*t;\r\n if(v>=max) max = v;\r\n }\r\n console.log(max);\r\n}\r\n\r\nfunction main() {\r\n const fs = require(\"fs\");\r\n const input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\r\n let line = 0;\r\n function readline() {\r\n return input[line++];\r\n }\r\n let t = parseInt(readline());\r\n for(let i=0;iparseInt(cur));\r\n let arr= [];\r\n for(let i=0;i<4;i++)\r\n arr.push(readline().trim().split(\" \").map(cur=>parseInt(cur)));\r\n solve(w,h,arr);\r\n }\r\n}\r\nmain();"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [w, h] = rna();\r\n\r\n\t\tfunction go (height) {\r\n\t\t\tconst ar = rna().slice(1);\r\n\t\t\tar.sort((x, y) => x - y);\r\n\t\t\tans = Math.max(ans, height * (ar[ar.length - 1] - ar[0]));\r\n\t\t}\r\n\r\n\t\tlet ans = 0;\r\n\t\tgo(h);\r\n\t\tgo(h);\r\n\t\tgo(w);\r\n\t\tgo(w);\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// function foo(x) {\r\n// process.stdout.write(\"hello: \"); // without auto '\\n' (newline)\r\n// console.log(x); // with auto '\\n' (newline)\r\n// }\r\n\r\nconst print = x => {\r\n process.stdout.write(x.toString());\r\n process.stdout.write(\"\\n\");\r\n};\r\n\r\nfunction main() {\r\n const n = readline();\r\n\r\n for (let test = 0; test < n; test += 1) {\r\n const [w, h] = readline().split(' ');\r\n\r\n const getMaxDistanceBetween = () => {\r\n const arr = readline().split(' ');\r\n let mn = 1000 * 1000 + 3;\r\n let mx = 0;\r\n for (let i = 1; i < arr.length; i++) {\r\n mn = Math.min(mn, arr[i]);\r\n mx = Math.max(mx, arr[i]);\r\n }\r\n return mx - mn;\r\n }\r\n\r\n const down = getMaxDistanceBetween();\r\n const up = getMaxDistanceBetween();\r\n const left = getMaxDistanceBetween();\r\n const right = getMaxDistanceBetween();\r\n\r\n const ans = Math.max(\r\n down * h,\r\n up * h,\r\n left * w,\r\n right * w,\r\n )\r\n\r\n print(ans);\r\n }\r\n\r\n}\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let [t] = readline().split(' ').map(num => parseInt(num));\n for (let i = 0; i < t; i++) {\n let [w, h] = readline().split(' ').map(num => parseInt(num));\n let x1 = readline().split(' ').map(num => parseInt(num));\n let x2 = readline().split(' ').map(num => parseInt(num));\n let y1 = readline().split(' ').map(num => parseInt(num));\n let y2 = readline().split(' ').map(num => parseInt(num));\n let t1 = (x1[x1.length - 1] - x1[1]) * h;\n let t2 = (x2[x2.length - 1] - x2[1]) * h;\n let t3 = (y1[y1.length - 1] - y1[1]) * w;\n let t4 = (y2[y2.length - 1] - y2[1]) * w;\n console.log(Math.max(t1, t2, t3, t4));\n }\n}"}, {"source_code": "function S(a, b, c) {\r\n return Math.abs(\r\n (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])\r\n );\r\n}\r\n\r\nfunction solve(points) {\r\n var answers = [0, 0, 0, 0];\r\n for (var i = 0; i < 4; i++) {\r\n a = points[i][0];\r\n b = points[i][points[i].length - 1];\r\n\r\n for (var j = 0; j < 4; j++) {\r\n if (i === j) continue;\r\n\r\n for (var c of points[j]) {\r\n answers[i] = Math.max(answers[i], S(a, b, c));\r\n }\r\n }\r\n }\r\n\r\n return Math.max.apply(null, answers);\r\n}\r\n\r\nvar _i = 0;\r\nvar _input = `3\r\n5 8\r\n2 1 2\r\n3 2 3 4\r\n3 1 4 6\r\n2 4 5\r\n10 7\r\n2 3 9\r\n2 1 7\r\n3 1 3 4\r\n3 4 5 6\r\n11 5\r\n3 1 6 8\r\n3 3 6 8\r\n3 1 3 4\r\n2 2 4\r\n`.split(\"\\n\");\r\n\r\nt = Number(readline());\r\npoints = [[], [], [], []];\r\n\r\nfor (var i = 0; i < t; i++) {\r\n var wh = readline().split(\" \").map(Number);\r\n var w = wh[0];\r\n var h = wh[1];\r\n var snd_coords = [0, h, 0, w];\r\n\r\n points.forEach(function (p, i) {\r\n points[i] = readline()\r\n .split(\" \")\r\n .slice(1)\r\n .map(Number)\r\n .map(function (x) {\r\n return i < 2 ? [x, snd_coords[i]] : [snd_coords[i], x];\r\n });\r\n });\r\n\r\n // console.log(points);\r\n\r\n print(solve(points));\r\n}\r\n\r\n// function readline() {\r\n// return _input[_i++];\r\n// }\r\n\r\n// function print(val) {\r\n// console.log(val);\r\n// }\r\n"}], "negative_code": [{"source_code": "'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n/* var arr = readLine().split(\" \").map((x) => {return parseInt(x)});\r\nvar test = readLine();\r\nwhile(test--)\r\n{\r\n\r\n}\r\n*/\r\nfunction main() {\r\n var test = readLine();\r\n \r\n while(test--)\r\n {\r\n var coordinates = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var w = BigInt(coordinates[0]);\r\n var h = BigInt(coordinates[1]);\r\n var x_when_y_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var x_when_y_h = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_w = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var length_of_x_when_y_zero = BigInt(x_when_y_zero[0] - 1);\r\n var length_of_x_when_y_h = BigInt(x_when_y_h[0] - 1);\r\n var length_of_y_when_zero = BigInt(y_when_x_zero[0] - 1);\r\n var length_of_y_when_w = BigInt(y_when_x_w[0] - 1);\r\n x_when_y_zero.shift();\r\n x_when_y_h.shift();\r\n y_when_x_zero.shift();\r\n y_when_x_w.shift();\r\n x_when_y_zero.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n x_when_y_h.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n y_when_x_zero.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n y_when_x_w.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });;\r\n var res = [\r\n BigInt(x_when_y_zero[length_of_x_when_y_zero]-x_when_y_zero[0]),\r\n BigInt(x_when_y_h[length_of_x_when_y_h]-x_when_y_h[0]),\r\n BigInt(y_when_x_zero[length_of_y_when_zero]-y_when_x_zero[0]),\r\n BigInt(y_when_x_w[length_of_y_when_w]-y_when_x_w[0])\r\n ];\r\n console.log(String(res));\r\n res[0] = res[0]*h;\r\n res[1] = res[1]*h;\r\n res[2] = res[2]*w;\r\n res[3] = res[3]*w;\r\n res.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });\r\n res.reverse();\r\n console.log(String(res[0]));\r\n }\r\n return 0;\r\n}"}, {"source_code": "'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n/* var arr = readLine().split(\" \").map((x) => {return parseInt(x)});\r\nvar test = readLine();\r\nwhile(test--)\r\n{\r\n\r\n}\r\n*/\r\nfunction main() {\r\n var test = readLine();\r\n \r\n while(test--)\r\n {\r\n var coordinates = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var w = BigInt(coordinates[0]);\r\n var h = BigInt(coordinates[1]);\r\n var x_when_y_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var x_when_y_h = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_w = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var length_of_x_when_y_zero = x_when_y_zero[0];\r\n var length_of_x_when_y_h = x_when_y_h[0];\r\n var length_of_y_when_zero = y_when_x_zero[0];\r\n var length_of_y_when_w = y_when_x_w[0];\r\n x_when_y_zero.shift();\r\n x_when_y_h.shift();\r\n y_when_x_zero.shift();\r\n y_when_x_w.shift();\r\n x_when_y_zero.sort();\r\n x_when_y_h.sort();\r\n y_when_x_zero.sort();\r\n y_when_x_w.sort();\r\n var res = [\r\n BigInt(x_when_y_zero[length_of_x_when_y_zero-1]-x_when_y_zero[0]),\r\n BigInt(x_when_y_h[length_of_x_when_y_h-1]-x_when_y_h[0]),\r\n BigInt(y_when_x_zero[length_of_y_when_zero-1]-y_when_x_zero[0]),\r\n BigInt(y_when_x_w[length_of_y_when_w-1]-y_when_x_w[0])\r\n ];\r\n res[0] = res[0]*h;\r\n res[1] = res[1]*h;\r\n res[2] = res[2]*w;\r\n res[3] = res[3]*w;\r\n res.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });\r\n res.reverse();\r\n console.log(String(res[0]));\r\n }\r\n return 0;\r\n}"}, {"source_code": "'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n/* var arr = readLine().split(\" \").map((x) => {return parseInt(x)});\r\nvar test = readLine();\r\nwhile(test--)\r\n{\r\n\r\n}\r\n*/\r\nfunction main() {\r\n var test = readLine();\r\n \r\n while(test--)\r\n {\r\n var coordinates = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var w = coordinates[0];\r\n var h = coordinates[1];\r\n var x_when_y_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var x_when_y_h = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_w = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var length_of_x_when_y_zero = x_when_y_zero[0];\r\n var length_of_x_when_y_h = x_when_y_h[0];\r\n var length_of_y_when_zero = y_when_x_zero[0];\r\n var length_of_y_when_w = y_when_x_w[0];\r\n x_when_y_zero.shift();\r\n x_when_y_h.shift();\r\n y_when_x_zero.shift();\r\n y_when_x_w.shift();\r\n x_when_y_zero.sort();\r\n x_when_y_h.sort();\r\n y_when_x_zero.sort();\r\n y_when_x_w.sort();\r\n var res = [\r\n x_when_y_zero[length_of_x_when_y_zero-1]-x_when_y_zero[0],\r\n x_when_y_h[length_of_x_when_y_h-1]-x_when_y_h[0],\r\n y_when_x_zero[length_of_y_when_zero-1]-y_when_x_zero[0],\r\n y_when_x_w[length_of_y_when_w-1]-y_when_x_w[0]\r\n ];\r\n res[0] = res[0]*h;\r\n res[1] = res[1]*h;\r\n res[2] = res[2]*w;\r\n res[3] = res[3]*w;\r\n res.sort((a ,b) => {\r\n if(a > b) {\r\n return 1;\r\n } else if (a < b){\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n });\r\n res.reverse();\r\n console.log(res[0]);\r\n }\r\n return 0;\r\n}"}, {"source_code": "'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n/* var arr = readLine().split(\" \").map((x) => {return parseInt(x)});\r\nvar test = readLine();\r\nwhile(test--)\r\n{\r\n\r\n}\r\n*/\r\nfunction main() {\r\n var test = readLine();\r\n \r\n while(test--)\r\n {\r\n var coordinates = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var w = coordinates[0];\r\n var h = coordinates[1];\r\n var x_when_y_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var x_when_y_h = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_zero = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var y_when_x_w = readLine().split(\" \").map((x) => {return parseInt(x)});\r\n var length_of_x_when_y_zero = x_when_y_zero[0];\r\n var length_of_x_when_y_h = x_when_y_h[0];\r\n var length_of_y_when_zero = y_when_x_zero[0];\r\n var length_of_y_when_w = y_when_x_w[0];\r\n x_when_y_zero.shift();\r\n x_when_y_h.shift();\r\n y_when_x_zero.shift();\r\n y_when_x_w.shift();\r\n x_when_y_zero.sort();\r\n x_when_y_h.sort();\r\n y_when_x_zero.sort();\r\n y_when_x_w.sort();\r\n var res = [\r\n x_when_y_zero[length_of_x_when_y_zero-1]-x_when_y_zero[0],\r\n x_when_y_h[length_of_x_when_y_h-1]-x_when_y_h[0],\r\n y_when_x_zero[length_of_y_when_zero-1]-y_when_x_zero[0],\r\n y_when_x_w[length_of_y_when_w-1]-y_when_x_w[0]\r\n ];\r\n res[0] = res[0]*h;\r\n res[1] = res[1]*h;\r\n res[2] = res[2]*w;\r\n res[3] = res[3]*w;\r\n res.sort((a, b) => a-b);\r\n res.reverse();\r\n console.log(res[0]);\r\n }\r\n return 0;\r\n}"}, {"source_code": "\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main(inputString);\n});\n\nfunction log(message){\n if(process.env.NODE_ENV === \"debug\"){\n console.log(message);\n }\n}\n\nfunction main(fileContents) {//input lines as an array\n // console.log(fileContents);\n fileContents.splice(0,1);\n for(let i = 0; i < fileContents.length; i+=5){\n triangleScenarioHigh(fileContents[i],fileContents[i+1],fileContents[i+2],fileContents[i+3],fileContents[i+4])\n }\n}\nfunction triangleScenarioHigh(corner,horizontal0,horizontalY,vertical0,verticalX){\n // console.log(\"corner,horizontal0,horizontalY,vertical0,verticalX\")\n // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)\n\n triangleScenarioLow(corner.split(\" \"),\n horizontal0.split(\" \").slice(1),\n horizontalY.split(\" \").slice(1),\n vertical0.split(\" \").slice(1),\n verticalX.split(\" \").slice(1))\n}\n\nfunction triangleScenarioLow(corner,horizontal0,horizontalY,vertical0,verticalX){\n // console.log(\"corner,horizontal0,horizontalY,vertical0,verticalX\")\n // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)\n const YCorner = parseInt(corner[1]) //8\n const XCorner = parseInt(corner[0]) //5\n const points = [\n [[parseInt(horizontal0[0]),0],[parseInt(horizontal0[horizontal0.length-1]),0]],\n [[parseInt(horizontalY[0]),YCorner],[parseInt(horizontalY[horizontal0.length-1]),YCorner]],\n [[0,parseInt(vertical0[0])],[0,parseInt(vertical0[vertical0.length-1])]],\n [[XCorner,parseInt(verticalX[0])],[XCorner,parseInt(verticalX[verticalX.length-1])]],\n ]\n\n // console.log(\"points\",points)\n\n let biggestArea = 0\n\n for(i = 0; i < points.length; i++){\n for(i2 = 0; i2 < points.length; i2++){\n if(i !== i2){\n let length1 = Math.sqrt(Math.pow(points[i][0][0] - points[i2][0][0],2) + Math.pow(points[i][0][1] - points[i2][0][1],2))\n let length2 = Math.sqrt(Math.pow(points[i][1][0] - points[i2][0][0],2) + Math.pow(points[i][1][1] - points[i2][0][1],2))\n let length3 = Math.sqrt(Math.pow(points[i][0][0] - points[i][1][0],2) + Math.pow(points[i][0][1] - points[i][1][1],2))\n biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);\n length1 = Math.sqrt(Math.pow(points[i][0][0] - points[i2][1][0],2) + Math.pow(points[i][0][1] - points[i2][1][1],2))\n length2 = Math.sqrt(Math.pow(points[i][1][0] - points[i2][1][0],2) + Math.pow(points[i][1][1] - points[i2][1][1],2))\n length3 = Math.sqrt(Math.pow(points[i][0][0] - points[i][1][0],2) + Math.pow(points[i][0][1] - points[i][1][1],2))\n biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);\n\n }\n }\n }\n\n\n\n console.log(Math.round(biggestArea));\n\n}\n\n\nfunction findArea( a, b, c)\n{\n if (a < 0 || b < 0 || c < 0 ||\n (a + b <= c) || a + c <= b ||\n b + c <= a)\n {\n return -1;\n }\n let s = (a + b + c) / 2;\n return Math.sqrt(s * (s - a) *\n (s - b) * (s - c));\n}\n\n"}], "src_uid": "2c67ee95eba7ffbbed99cb488abb5f3d"} {"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 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.", "output_spec": "Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.", "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 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units."}, "positive_code": [{"source_code": "\nlet _inputLines;\nlet _lineNumber = 0;\nlet inputReader = _inputReader ();\n\nfunction _main() {\n\t\n\t_inputLines = _inputData.trim().split('\\n').map((string) => {\n\t\treturn string.trim();\n\t});;\n\tconst [n, m] = inputReader.readNumberArray();\n\tconst arr = inputReader.readNumberArray();\n\tlet current = 1;\n\tlet time = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif(current<=arr[i]){\n\t\t\ttime+=Math.abs(current-arr[i]);\n\t\t\tcurrent=arr[i];\n\t\t}\n\t\telse{\n\t\t\ttime+=Math.abs(current-n) + Math.abs(1-arr[i])+1;\n\t\t\tcurrent=arr[i];\n\t\t}\n\t} \n\tconsole.log(time);\n\n}\n\nvar _inputData = '';\nfunction cacheInput(data) {\n\t_inputData += data;\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', cacheInput).on('end', _main);\n\nfunction _inputReader () {\n\tfunction readNumberArray(){\n\t\treturn _inputLines[_lineNumber++].split(' ').map(val => Number(val));\n\t}\n\t\t\n\t\n\treturn {\n\t\treadNumberArray,\n\t}\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let [totalHouses, tasksLen] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const tasks = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n let count = tasks[0] - 1;\n\n for (let i = 0; i < tasksLen - 1; i++) {\n const diff = tasks[i + 1] - tasks[i];\n if (diff >= 0) {\n count += diff;\n } else {\n const steps = totalHouses - tasks[i] + tasks[i + 1];\n count += steps;\n }\n }\n console.log(count);\n}\n"}, {"source_code": "const readLine = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadLine.on('line', line => input.push(line));\n\nreadLine.on('close', () => {\n let [n, m] = input[0].split(' ').map(x => parseInt(x));\n const deway = input[1].split(' ').map(x => parseInt(x));\n let stay = 1;\n let answer = 0;\n\n for (let i = 0; i < deway.length; i += 1) {\n if (stay > deway[i]) {\n answer += (n - stay + deway[i]);\n } else {\n answer += deway[i]-stay;\n }\n stay = deway[i];\n }\n\n console.log(answer);\n});\n"}, {"source_code": "const readLine = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\n\nfunction splitAndParseInt(line) {\n return line.split(\" \").map((x) => parseInt(x));\n}\n\nreadLine.on(\"line\", (line) => input.push(line));\nreadLine.on(\"close\", () => {\n let [n, m] = splitAndParseInt(input[0]);\n const nums = splitAndParseInt(input[1]);\n\n let answer = 0,\n pos = 1;\n for (const num of nums) {\n if (pos <= num) {\n answer += num - pos;\n } else {\n answer += num + (n - pos);\n }\n pos = num;\n }\n console.log(answer);\n});\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet [n, m] = readLine()\n\t\t.split(' ')\n\t\t.map(x => parseInt(x));\n\n\tlet tasks = readLine()\n\t\t.split(' ')\n\t\t.map(x => parseInt(x));\n\n\tlet current = 1;\n\tlet total = 0;\n\n\ttasks.forEach(task => {\n\t\tif (task >= current) {\n\t\t\ttotal += task - current;\n\t\t} else {\n\t\t\ttotal += n - current + task;\n\t\t}\n\t\tcurrent = task;\n\t});\n\n\tconsole.log(total);\n}\n"}, {"source_code": "let fs = require('fs');\n\nlet txt = fs.readFileSync(0, \"utf-8\").split(/[\\n\\r]/).filter(data => data.length > 0);\n\nfor (let i = 0; i < txt.length; i += 2) {\n let info = txt[i].split(\" \")[0] * 1;\n doit(info, txt[i + 1].split(/[ ]/).filter(data => data.length > 0).map(dta => dta * 1));\n}\n\nfunction doit(n, tab) {\n let moves = tab[0] - 1;\n for (let i = 0; i < tab.length - 1; i++) {\n if (tab[i + 1] >= tab[i]) {\n moves += tab[i + 1] - tab[i];\n } else {\n moves += tab[i + 1] + (n - tab[i]);\n }\n\n }\n console.log(moves);\n}"}, {"source_code": "var l=readline().split(' ');\nvar n=+l[0];\nvar m=+l[1];\nvar a=readline().split(' ').map(function(v){return+v});\n\nvar ans=n;\nfor(var i=1; i +a[j]){\n\t\ttime += n - b + +a[j];\n\t\tb = +a[j];\n\t}\n}\n\nwrite(time);"}, {"source_code": "var meta = readline().split(' ').map((as)=> parseInt(as))\nvar time = 0, res = 0, start = 1\nreadline().split(' ').map((c)=> parseInt(c)).forEach((val)=>{\n\tres = val - start;\n\tif (res < 0){\n\t\ttime += (meta[0] - start) + val\n\t}\n\telse{\n\t\ttime += val - start\n\t}\n\tstart = val\n})\nprint(time)\n"}, {"source_code": ";(function () {\n\n\tvar s = readline().split(' ');\n\tvar n = +s[0];\n\tvar m = +s[1];\n\tvar a = readline().split(' ').map(function (i) { return +i; });\n\tvar ans = n;\n\n\tfor(var i = 1; i < m; i++)\n\t\tif (a[i] < a[i-1])\n\t\t\tans += n;\n\n\tprint(ans - n + a[a.length - 1] - 1);\n\n}).call(this);"}, {"source_code": "var s = readline().split(\" \");\nvar n = Number(s[0]), m = Number(s[1]);\n\ns = readline().split(\" \").map(Number);\nvar t = s[0] - 1;\nfor(var i=1; ia[i]){ans+=abs(a[i-1]-nm[0]); ans++; a[i-1]=1;}\n ans+=abs(a[i]-a[i-1]);\n}\nprint(ans);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\nfor(var i=0;i=cur) t+=m[i]-cur;\n cur=m[i];\n \n//ts+=' '+t;\n}\nprint(t);"}, {"source_code": "\n'use strict'\n\nString.prototype.getNumArray = function () {\n return String(this).split(' ').map(function (value) {\n return parseInt(value);\n });\n}\n\nString.prototype.getNumber = function() {\n return String(this).split(' ').map(function (value) {\n return parseInt(value);\n })[0];\n}\n\nlet n = readline().getNumber(),\n array = readline().getNumArray(),\n time = 0;\n\narray.unshift(1);\n\nlet calcTime = (time, destinationBuilding, currentBuilding, totalAmountOfBuildings) => {\n if(destinationBuilding < currentBuilding) {\n time+=totalAmountOfBuildings - currentBuilding + 1;\n time+=destinationBuilding - 1;\n } else if (destinationBuilding > currentBuilding) {\n time+=destinationBuilding - currentBuilding;\n }\n\n return time;\n}\n\nfor (let i = 0; i < array.length - 1; i++) {\n time = calcTime(time, array[i+1], array[i], n);\n}\n\nwrite(time)"}, {"source_code": "var str = readline().split(\" \");\nvar n = +str[0]; var m = +str[1];\nvar house = readline().split(\" \");\nvar temp = 1; var res = 0;\n\tfor(var i=0; ihouse[i]) // \t\t\t3 2\n\t\t\tres+= n-temp+Number(house[i]);\n\t\t\t\n\t\t\t temp = +house[i]; // 3 \n\t}\nprint(res);\n\t"}, {"source_code": "var n = readline().split(\" \").map(function(x) { return parseInt(x); })[0];\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar diff = a[0] - 1;\nfor (var i = 0; i < a.length - 1; i++) {\n\tdiff += ((a[i+1] >= a[i]) ? (a[i+1] - a[i]) : (n - a[i] + a[i + 1]));\n}\nprint (diff);"}, {"source_code": "var ringRoad = function(n, arr)\n {\n var counter = arr[0] - 1; \n for (var i = 1; i <= arr.length - 1; i++)\n {\n if (arr[i] >= arr[i - 1])\n {\n counter += arr[i] - arr[i - 1];\n continue;\n }\n else {\n\t\t\t\t\t//if (arr[i - 1] !== n)\n counter += n - arr[i - 1] + arr[i];\n\t\t\t\t\t//else counter += 1;\n }\n }\n\t\t\treturn counter;\n }\n var toNumArr = function(str)\n {\n str = str.split(' ');\n for (var i = 0 ; i <= str.length - 1; i++)\n {\n str[i] = +str[i];\n }\n return str;\n }\n var num = toNumArr(readline());\n var input = toNumArr(readline());\n print(ringRoad(num[0], input));"}, {"source_code": "var ringRoad = function(n, arr)\n {\n var counter = arr[0] - 1; \n for (var i = 1; i <= arr.length - 1; i++)\n {\n if (arr[i] > arr[i - 1])\n {\n counter += arr[i] - arr[i - 1];\n continue;\n }\n else if (arr[i] < arr[i - 1]) {\n\t\t\t\t\t//if (arr[i - 1] !== n)\n counter += n - arr[i - 1] + arr[i];\n\t\t\t\t\t//else counter += 1;\n }\n }\n\t\t\treturn counter;\n }\n var toNumArr = function(str)\n {\n str = str.split(' ');\n for (var i = 0 ; i <= str.length - 1; i++)\n {\n str[i] = +str[i];\n }\n return str;\n }\n var num = toNumArr(readline());\n var input = toNumArr(readline());\n print(ringRoad(num[0], input));"}, {"source_code": "var inp = readline().split(' ');\nvar a = readline().split(' ');\n\nfor(var i=0; i a[i-1]) path += a[i] - a[i-1];\n else if(a[i] < a[i-1]) {\n path += n - a[i-1];\n path += 1;\n path += a[i] - 1;\n }\n }\n}\n\nprint(path);"}, {"source_code": "var nums = readNums();\n\nvar n = nums[0];\nvar m = nums[1];\n\nvar things = readNums();\n\nvar k = 0;\n\nfor (var i = 0; i {\n\tif (c >= a.now) {\n\t\ta.sum += c - a.now;\n\t} else {\n\t\ta.sum += n - a.now + c;\n\t}\n\ta.now = c;\n\treturn a;\n}, { now: 1, sum: 0 });\nprint(r.sum)"}, {"source_code": "X=readline().split(' ').map(Number)\nn=X[0], m=X[1]\nA=readline().split(' ').map(Number)\nprint(A.reduce((a,c) => ({\n\tsum: a.sum + (c >= a.now ? (c - a.now) : (n - a.now + c)),\n\tnow: c,\n}), { now: 1, sum: 0 }).sum);\n"}, {"source_code": "var a =readline().split(' ').map(Number);\nvar b =readline().split(' ').map(Number);\nd = b[0]-1;\nfor(var i = 1;i data.length > 0);\n\nfor (let i = 0; i < txt.length; i += 2) {\n let info = txt[i].split(\" \")[0] * 1;\n doit(info, txt[i + 1].split(/[ ]/).filter(data => data.length > 0).map(dta => dta * 1));\n}\n\nfunction doit(n, tab) {\n let moves=tab[0]-1;\n for (let i = 0; i < tab.length-1; i++) {\n if(tab[i+1]>=tab[i]){\n moves+=tab[i+1]-tab[i];\n }else{\n moves+=tab[i+1]-1;\n moves+=(n%tab[i])+1;\n }\n \n }\n console.log(moves);\n \n}"}, {"source_code": "let fs = require('fs');\n\nlet txt = fs.readFileSync(0, \"utf-8\").split(/[\\n\\r]/).filter(data => data.length > 0);\n\nfor (let i = 0; i < txt.length; i += 2) {\n let info = txt[i].split(\" \")[0] * 1;\n doit(info, txt[i + 1].split(/[ ]/).filter(data => data.length > 0).map(dta => dta * 1));\n}\n\nfunction doit(n, tab) {\n let moves = tab[0] - 1;\n for (let i = 0; i < tab.length - 1; i++) {\n if (tab[i + 1] >= tab[i]) {\n moves += tab[i + 1] - tab[i];\n } else {\n moves += tab[i + 1] + (n % tab[i]);\n }\n\n }\n console.log(moves);\n\n}"}, {"source_code": "var input = readline().split(\" \"), n = +input[0], m = +input[1], a = readline().split(\" \"), i = 1, j = 0, time = 0;\n\nfor( ; j != m ; i++, time++){\n\twrite(i,j,time + \"\\n\");\n\tif(i == +a[j]){\n\t\tj++;\n\t\tfor( ; ; ){\n\t\t\tif(i == +a[j]){\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif(i == n){\n\t\ti = 0;\n\t}\n}\n\nwrite(time-1);"}, {"source_code": "var meta = readline().split(' ').map((as)=> parseInt(as))\nvar time = 0, res = 0, start = 1\nreadline().split(' ').map((c)=> parseInt(c)).forEach((val)=>{\n\tres = val - start;\n\tif (res < 0){\n\t\ttime += (meta[0] - val) + Math.abs(res)\n\t}\n\telse{\n\t\ttime += val - start\n\t}\n\tstart = val\n})\nprint(time)\n"}, {"source_code": ";(function () {\n\n\tvar x = 0,\n\n\t\tn = +readline().split(' ')[0],\n\n\t\ts = readline()\n\t\t\t.split(' ')\n\t\t\t.map(function (i) {return +i;})\n\t\t\t.filter(function (e, i, a) { return (i == a.length - 1) || a[i] != a[i+1]; }),\n\n\t\tstep = (function (n) {\n\t\t\tvar i = 1;\n\t\t\treturn function () {\n\t\t\t\tx++;\n\t\t\t\ti = n == i ? 1 : i+1;\n\t\t\t\treturn i;\n\t\t\t}\n\t\t})(n);\n\n\tif (s[0] == 1) s.slice(0,1);\n\n\tfor (var i = 0; i < s.length; i++)\n\t\twhile (step() != s[i]);\n\n\tprint(x);\n\n}).call(this);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\n\nvar cur=1,t=0;\nfor(var i=0;icur) t+=parseInt(m[i]-cur);\n cur=m[i];\n \n}\nprint(t);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\n\nvar cur=1,t=0;\nfor(var i=0;icur) t+=(m[i]-cur);\n cur=i;\n}\nprint(t);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\n\nvar cur=1,t=0;\nfor(var i=0;icur) t+=(m[i]-cur);\n cur=m[i];\n \nprint(t);\n}\nprint(t);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\nfor(var i=0;i=cur) t+=m[i]-cur;\n cur=m[i];\n \n//ts+=' '+t;\n}\nprint(ts);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\n\nvar cur=1,t=0;\nfor(var i=0;icur) t+=(m[i]-cur);\n cur=m[i];\n}\nprint(t);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\n\nvar cur=1,t=0;\nfor(var i=0;i=cur) t+=(m[i]-cur);\n cur=i;\n}\nprint(t);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\nfor(var i=0;icur) t+=m[i]-cur;\n cur=m[i];\n \nts+=' '+t;\n}\nprint(ts);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\nfor(var i=0;icur) t+=parseInt(m[i]-cur);\n cur=m[i];\n}\nprint(t);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\n\nvar cur=1,t=0;\nfor(var i=0;icur) t+=(m[i]-cur);\n cur=i;\n}\nprint(t);"}, {"source_code": "var l1=readline().split(' ');\nvar l2=readline().split(' ');\nvar n=parseInt(l1[0]);\nvar m=l2;\nfor(var i=0;icur) t+=m[i]-cur;\n cur=m[i];\n \nprint(t);\n}\nprint(t);"}, {"source_code": "var n = readline().split(\" \").map(function(x) { return parseInt(x); })[0];\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar diff = a[0] - 1;\nfor (var i = 0; i < a.length - 1; i++) {\n\tdiff += ((a[i+1] >= a[i]) ? (a[i+1] - a[i]) : (n - a[i+1] + a[i] - 2));\n}\nprint (diff);"}, {"source_code": "var n = readline().split(\" \").map(function(x) { return parseInt(x); })[1];\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar diff = a[0] - 1;\nfor (var i = 0; i < a.length - 1; i++) {\n\tdiff += ((a[i+1] >= a[i]) ? (a[i+1] - a[i]) : (a.length - a[i+1] + a[i] - 1));\n}\nprint (diff);"}, {"source_code": "var ringRoad = function(n, arr)\n {\n var counter = arr[0] - 1; \n for (var i = 1; i <= arr.length - 1; i++)\n {\n if (arr[i] > arr[i - 1])\n {\n counter += arr[i] - arr[i - 1];\n continue;\n }\n else {\n\t\t\t\t\t//if (arr[i - 1] !== n)\n counter += n - arr[i - 1] + arr[i];\n\t\t\t\t\t//else counter += 1;\n }\n }\n\t\t\treturn counter;\n }\n var toNumArr = function(str)\n {\n str = str.split(' ');\n for (var i = 0 ; i <= str.length - 1; i++)\n {\n str[i] = +str[i];\n }\n return str;\n }\n var num = toNumArr(readline());\n var input = toNumArr(readline());\n print(ringRoad(num[0], input));"}, {"source_code": " var ringRoad = function(n, arr)\n {\n arr.unshift(1);\n var counter = 0; \n for (var i = 1; i <= arr.length - 1; i++)\n {\n if (arr[i] >= arr[i - 1])\n {\n counter += arr[i] - arr[i - 1];\n \n \n continue;\n }\n else {\n\t\t\t\t\tif (arr[i - 1] !== n)\n counter += n - arr[i - 1] + i;\n\t\t\t\t\telse counter += 1;\n }\n }\n\t\t\treturn counter;\n }\n var toNumArr = function(str)\n {\n str = str.split(' ');\n for (var i = 0 ; i <= str.length - 1; i++)\n {\n str[i] = +str[i];\n }\n return str;\n }\n var num = toNumArr(readline());\n var input = toNumArr(readline());\n print(ringRoad(num[0], input));"}, {"source_code": "a =readline().split(' ');\nb =readline().split(' ');\nd = b[0]-1;\nfor (i=1;i0;--y){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Al[(y<<10)+1],x=2;x<=W;++x){\n i=(y<<10)+x;\n if(Al[i])Al[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Ar[(y<<10)+W],x=W-1;x>0;--x){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]=++t;\n else t=0;\n }\n}\nfor(;Q--;){\n t=readline().split(' ');\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n if(Au[i])Au[i]=Ad[i]=Al[i]=Ar[i]=0;\n else{\n Au[i]=(Au[(Y-1<<10)+X]|0)+1;\n Ad[i]=(Ad[(Y+1<<10)+X]|0)+1;\n Al[i]=(Al[(Y<<10)+X-1]|0)+1;\n Ar[i]=(Ar[(Y<<10)+X+1]|0)+1;\n }\n for(t=Au[i],y=Y+1;y<=H&&Au[(y<<10)+X];++y)Au[(y<<10)+X]=++t;\n for(t=Ad[i],y=Y-1;y>0 &&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=++t;\n for(t=Al[i],x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=++t;\n for(t=Ar[i],x=X-1;x>0 &&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=++t;\n }\n else if(Au[i]){\n L=[]; P=[]; M=0; l=0;\n for(x=1;x<=W+1;++x){\n t=Au[(Y<<10)+x]|0;\n for(i=x;l&&L[l-1]>t;--l){\n i=P[l-1];\n s=L[l-1]*(x-i);\n if(x>X&&X>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]t;--l){\n i=P[l-1];\n s=L[l-1]*(x-i);\n if(x>X&&X>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]t;--l){\n i=P[l-1];\n s=L[l-1]*(y-i);\n if(y>Y&&Y>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]t;--l){\n i=P[l-1];\n s=L[l-1]*(y-i);\n if(y>Y&&Y>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]1024&&A[l]>=h;l-=1024);\n for(;r=h;r+=1024);\n s=(r-l-1024>>10)*h;\n if(s>M)M=s;\n h=A[l]|0; if(A[r]>h)h=A[r];\n }\n}\nfor(;Q--;){\n t=readline().split(' ');\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n sw(Al,W+(Y<<10),i);\n sw(Ar,W+(Y<<10),(Y<<10)+W+1-X);\n sw(Au,H+(X<<10),(X<<10)+Y);\n sw(Ad,H+(X<<10),(X<<10)+H+1-Y);\n }\n else if(Al[i]){\n M=0;\n max(Al,H,i);\n max(Ar,H,(Y<<10)+W+1-X);\n max(Au,W,(X<<10)+Y);\n max(Ad,W,(X<<10)+H+1-Y);\n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}, {"source_code": "t=readline().split(' '); MAX=1<<20; P=[]; L=[];\nW=+t[0]; H=+t[1]|0; Q=+t[2]; out='';\nAu=Array(MAX);\nAl=Array(MAX);\nAd=Array(MAX);\nAr=Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(' ');\n for(y=1;y<=H;++y)\n Al[(y<<10)+x]=Au[(x<<10)+y]=Ar[(y<<10)+W+1-x]=Ad[(x<<10)+H+1-y]=t[y-1]|0;\n}\nfunction calc(A,W,H){\n var x,y,t,i;\n for(y=1;y<=H;++y){\n i=(y<<10)+1; t=A[i];\n for(++i,x=2;x<=W;++x,++i){\n if(A[i])A[i]=++t;\n else t=0;\n }\n }\n}\ncalc(Au,H,W);\ncalc(Ad,H,W);\ncalc(Al,W,H);\ncalc(Ar,W,H);\nfunction sw(A,W,x,i){\n var t=A[i]=A[i]?0:(A[i-1]|0)+1;\n for(;++x<=W&&A[++i];)A[i]=++t;\n}\nfunction max(A,H,X,Y){\n var l=0,s,y,t,i; ++H;\n for(y=1;y<=H;++y){\n t=A[(y<<10)+X]|0;\n for(i=y;l&&L[l-1]>t;--l){\n i=P[l-1];\n s=L[l-1]*(y-i);\n if(y>Y&&Y>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]0;--y){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Al[(y<<10)+1],x=2;x<=W;++x){\n i=(y<<10)+x;\n if(Al[i])Al[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Ar[(y<<10)+W],x=W-1;x>0;--x){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]=++t;\n else t=0;\n }\n}\nfor(;Q--;){\n t=readline().split(' ');\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n if(Au[i])Au[i]=Ad[i]=Al[i]=Ar[i]=0;\n else{\n Au[i]=(Au[(Y-1<<10)+X]|0)+1;\n Ad[i]=(Ad[(Y+1<<10)+X]|0)+1;\n Al[i]=(Al[(Y<<10)+X-1]|0)+1;\n Ar[i]=(Ar[(Y<<10)+X+1]|0)+1;\n }\n for(t=Au[i],y=Y+1;y<=H&&Au[(y<<10)+X];++y)Au[(y<<10)+X]=++t;\n for(t=Ad[i],y=Y-1;y>0 &&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=++t;\n for(t=Al[i],x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=++t;\n for(t=Ar[i],x=X-1;x>0 &&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=++t;\n }\n else if(Au[i]){\n L=[]; P=[]; M=0; l=0;\n for(x=1;x<=W+1;++x){\n t=Au[(Y<<10)+x]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t){\n s=L[0]*(x-P[0]);\n if(x>X&&X>=P[0]&&s>M)M=s;\n L[0]=t;\n }\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(x=1;x<=W+1;++x){\n t=Ad[(Y<<10)+x]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t){\n s=L[0]*(x-P[0]);\n if(x>X&&X>=P[0]&&s>M)M=s;\n L[0]=t;\n }\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n\n l=0;\n for(y=1;y<=H+1;++y){\n t=Al[(y<<10)+X]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t){\n s=L[0]*(y-P[0]);\n if(y>Y&&Y>=P[0]&&s>M)M=s;\n L[0]=t;\n }\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(y=1;y<=H+1;++y){\n t=Ar[(y<<10)+X]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t){\n s=L[0]*(y-P[0]);\n if(y>Y&&Y>=P[0]&&s>M)M=s;\n L[0]=t;\n }\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}, {"source_code": "t=readline().split(' '); MAX=1<<20;\nW=t[0]|0; H=t[1]|0; Q=t[2]|0; out='';\nAu=new Array(MAX);\nAl=new Array(MAX);\nAd=new Array(MAX);\nAr=new Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(' ');\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n Au[i]=Al[i]=Ad[i]=Ar[i]=t[y-1]|0;\n }\n}\nfor(x=1;x<=W;++x){\n for(t=Au[(1<<10)+x],y=2;y<=H;++y){\n i=(y<<10)+x;\n if(Au[i])Au[i]=++t;\n else t=0;\n }\n}\nfor(x=1;x<=W;++x){\n for(t=Ad[(H<<10)+x],y=H-1;y>0;--y){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Al[(y<<10)+1],x=2;x<=W;++x){\n i=(y<<10)+x;\n if(Al[i])Al[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Ar[(y<<10)+W],x=W-1;x>0;--x){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]=++t;\n else t=0;\n }\n}\nfor(;Q--;){\n t=readline().split(' ');\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n if(Au[i])Au[i]=Ad[i]=Al[i]=Ar[i]=0;\n else{\n Au[i]=(Au[(Y-1<<10)+X]|0)+1;\n Ad[i]=(Ad[(Y+1<<10)+X]|0)+1;\n Al[i]=(Al[(Y<<10)+X-1]|0)+1;\n Ar[i]=(Ar[(Y<<10)+X+1]|0)+1;\n }\n for(t=Au[i],y=Y+1;y<=H&&Au[(y<<10)+X];++y)Au[(y<<10)+X]=++t;\n for(t=Ad[i],y=Y-1;y>0 &&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=++t;\n for(t=Al[i],x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=++t;\n for(t=Ar[i],x=X-1;x>0 &&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=++t;\n }\n else if(Au[i]){\n L=[]; P=[]; M=0; l=0;\n for(x=1;x<=W+1;++x){\n t=Au[(Y<<10)+x]|0;\n if(!l&&t||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(x=1;x<=W+1;++x){\n t=Ad[(Y<<10)+x]|0;\n if(!l&&t||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n\n l=0;\n for(y=1;y<=H+1;++y){\n t=Al[(y<<10)+X]|0;\n if(!l&&t||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(y=1;y<=H+1;++y){\n t=Ar[(y<<10)+X]|0;\n if(!l&&t||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}, {"source_code": "t=readline().split(' '); MAX=1<<20;\nW=+t[0]; H=+t[1]; Q=+t[2]; out='';\nAu=new Array(MAX);\nAl=new Array(MAX);\nAd=new Array(MAX);\nAr=new Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(' ');\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n Au[i]=Al[i]=Ad[i]=Ar[i]=+t[y-1];\n }\n}\nfor(y=2;y<=H;++y){\n for(x=1;x<=W;++x){\n i=(y<<10)+x;\n if(Au[i])Au[i]+=Au[(y-1<<10)+x];\n }\n}\nfor(y=H-1;y>0;--y){\n for(x=1;x<=W;++x){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]+=Ad[(y+1<<10)+x];\n }\n}\nfor(x=2;x<=W;++x){\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n if(Al[i])Al[i]+=Al[i-1];\n }\n}\nfor(x=W-1;x>0;--x){\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]+=Ar[i+1];\n }\n}\nfor(q=0;q0&&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=Ad[(y+1<<10)+X]+1;\n \n Al[(Y<<10)+X]=Al[(Y<<10)+X]?0:(Al[(Y<<10)+X-1]|0)+1;\n for(x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=Al[(Y<<10)+x-1]+1;\n \n Ar[(Y<<10)+X]=Ar[(Y<<10)+X]?0:(Ar[(Y<<10)+X+1]|0)+1;\n for(x=X-1;x>0&&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=Ar[(Y<<10)+x+1]+1;\n }\n else if(Au[(Y<<10)+X]){\n L=[]; P=[]; M=0; l=0;\n i=Y<<10;\n for(x=1;x<=W+1;++x){\n t=Au[i+x]|0;\n if(!l||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(x=1;x<=W+1;++x){\n t=Ad[i+x]|0;\n if(!l||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n\n l=0;\n for(y=1;y<=H+1;++y){\n t=Al[(y<<10)+X]|0;\n if(!l||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(y=1;y<=H+1;++y){\n t=Ar[(y<<10)+X]|0;\n if(!l||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);"}, {"source_code": "space=/\\s+/; t=readline().split(space); MAX=1<<20;\nW=t[0]|0; H=t[1]|0; Q=t[2]|0; out='';\nAu=new Array(MAX);\nAl=new Array(MAX);\nAd=new Array(MAX);\nAr=new Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(space);\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n Au[i]=Al[i]=Ad[i]=Ar[i]=t[y-1]|0;\n }\n}\nfor(x=1;x<=W;++x){\n for(t=0,y=2;y<=H;++y){\n i=(y<<10)+x;\n if(Au[i])Au[i]=++t;\n else t=0;\n }\n}\nfor(x=1;x<=W;++x){\n for(t=0,y=H-1;y>0;--y){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=0,x=2;x<=W;++x){\n i=(y<<10)+x;\n if(Al[i])Al[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=0,x=W-1;x>0;--x){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]=++t;\n else t=0;\n }\n}\nfor(;Q--;){\n t=readline().split(space);\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n if(Au[i])Au[i]=Ad[i]=Al[i]=Ar[i]=0;\n else{\n Au[i]=(Au[(Y-1<<10)+X]|0)+1;\n Ad[i]=(Ad[(Y+1<<10)+X]|0)+1;\n Al[i]=(Al[(Y<<10)+X-1]|0)+1;\n Ar[i]=(Ar[(Y<<10)+X+1]|0)+1;\n }\n for(t=Au[i],y=Y+1;y<=H&&Au[(y<<10)+X];++y)Au[(y<<10)+X]=++t;\n for(t=Ad[i],y=Y-1;y>0 &&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=++t;\n for(t=Al[i],x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=++t;\n for(t=Ar[i],x=X-1;x>0 &&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=++t;\n }\n else if(Au[i]){\n L=[]; P=[]; M=0; l=0;\n for(x=1;x<=W+1;++x){\n t=Au[(Y<<10)+x]|0;\n if(!l&&t||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(x=1;x<=W+1;++x){\n t=Ad[(Y<<10)+x]|0;\n if(!l&&t||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n\n l=0;\n for(y=1;y<=H+1;++y){\n t=Al[(y<<10)+X]|0;\n if(!l&&t||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(y=1;y<=H+1;++y){\n t=Ar[(y<<10)+X]|0;\n if(!l&&t||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}, {"source_code": "t=readline().split(' '); MAX=1<<20; P=[]; L=[];\nW=+t[0]; H=+t[1]; Q=+t[2]; out='';\nAu=Array(MAX);\nAl=Array(MAX);\nAd=Array(MAX);\nAr=Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(' ');\n for(y=1;y<=H;++y)\n Al[(y<<10)+x]=Au[(x<<10)+y]=Ar[(y<<10)+W+1-x]=Ad[(x<<10)+H+1-y]=t[y-1]|0;\n}\nfunction calc(A,W,H){\n var y,t,i,w;\n for(y=1;y<=H;++y){\n A[i=y<<10]=0;\n t=A[++i];\n w=i+W;\n for(++i;i1024&&A[l]>=h;l-=1024);\n for(;r=h;r+=1024);\n s=(r-l-1024>>10)*h;\n if(s>M)M=s;\n h=A[l]; if(A[r]>h)h=A[r];\n }\n}\nfor(;Q--;){\n t=readline().split(' ');\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n sw(Al,W+(Y<<10),i);\n sw(Ar,W+(Y<<10),(Y<<10)+W+1-X);\n sw(Au,H+(X<<10),(X<<10)+Y);\n sw(Ad,H+(X<<10),(X<<10)+H+1-Y);\n }\n else if(Al[i]){\n M=0;\n max(Al,H,i);\n max(Ar,H,(Y<<10)+W+1-X);\n max(Au,W,(X<<10)+Y);\n max(Ad,W,(X<<10)+H+1-Y);\n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}, {"source_code": "space=/\\s+/; t=readline().split(space); MAX=1<<20;\nW=t[0]|0; H=t[1]|0; Q=t[2]|0; out='';\nAu=new Array(MAX);\nAl=new Array(MAX);\nAd=new Array(MAX);\nAr=new Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(space);\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n Au[i]=Al[i]=Ad[i]=Ar[i]=t[y-1]|0;\n }\n}\nfor(x=1;x<=W;++x){\n for(t=Au[(1<<10)+x],y=2;y<=H;++y){\n i=(y<<10)+x;\n if(Au[i])Au[i]=++t;\n else t=0;\n }\n}\nfor(x=1;x<=W;++x){\n for(t=Ad[(H<<10)+x],y=H-1;y>0;--y){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Al[(y<<10)+1],x=2;x<=W;++x){\n i=(y<<10)+x;\n if(Al[i])Al[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Ar[(y<<10)+W],x=W-1;x>0;--x){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]=++t;\n else t=0;\n }\n}\nfor(;Q--;){\n t=readline().split(space);\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n if(Au[i])Au[i]=Ad[i]=Al[i]=Ar[i]=0;\n else{\n Au[i]=(Au[(Y-1<<10)+X]|0)+1;\n Ad[i]=(Ad[(Y+1<<10)+X]|0)+1;\n Al[i]=(Al[(Y<<10)+X-1]|0)+1;\n Ar[i]=(Ar[(Y<<10)+X+1]|0)+1;\n }\n for(t=Au[i],y=Y+1;y<=H&&Au[(y<<10)+X];++y)Au[(y<<10)+X]=++t;\n for(t=Ad[i],y=Y-1;y>0 &&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=++t;\n for(t=Al[i],x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=++t;\n for(t=Ar[i],x=X-1;x>0 &&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=++t;\n }\n else if(Au[i]){\n L=[]; P=[]; M=0; l=0;\n for(x=1;x<=W+1;++x){\n t=Au[(Y<<10)+x]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(x=1;x<=W+1;++x){\n t=Ad[(Y<<10)+x]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n\n l=0;\n for(y=1;y<=H+1;++y){\n t=Al[(y<<10)+X]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(y=1;y<=H+1;++y){\n t=Ar[(y<<10)+X]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}, {"source_code": "t=readline().split(' '); MAX=1<<20;\nW=+t[0]; H=+t[1]; Q=+t[2]; out='';\nAu=new Array(MAX);\nAl=new Array(MAX);\nAd=new Array(MAX);\nAr=new Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(' ');\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n Au[i]=Al[i]=Ad[i]=Ar[i]=+t[y-1];\n }\n}\nfor(y=2;y<=H;++y){\n for(x=1;x<=W;++x){\n i=(y<<10)+x;\n if(Au[i])Au[i]+=Au[(y-1<<10)+x];\n }\n}\nfor(y=H-1;y>0;--y){\n for(x=1;x<=W;++x){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]+=Ad[(y+1<<10)+x];\n }\n}\nfor(x=2;x<=W;++x){\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n if(Al[i])Al[i]+=Al[i-1];\n }\n}\nfor(x=W-1;x>0;--x){\n for(y=1;y<=H;++y){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]+=Ar[i+1];\n }\n}\nfor(q=0;q0&&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=Ad[(y+1<<10)+X]+1;\n \n Al[(Y<<10)+X]=Al[(Y<<10)+X]?0:(Al[(Y<<10)+X-1]|0)+1;\n for(x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=Al[(Y<<10)+x-1]+1;\n \n Ar[(Y<<10)+X]=Ar[(Y<<10)+X]?0:(Ar[(Y<<10)+X+1]|0)+1;\n for(x=X-1;x>0&&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=Ar[(Y<<10)+x+1]+1;\n }\n else if(Au[(Y<<10)+X]){\n L=[]; P=[]; M=0; l=0;\n i=Y<<10;\n for(x=1;x<=W+1;++x){\n t=Au[i+x]|0;\n if(!l||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(x=1;x<=W+1;++x){\n t=Ad[i+x]|0;\n if(!l||L[l-1]<=t)P[l]=x,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n\n l=0;\n for(y=1;y<=H+1;++y){\n t=Al[(y<<10)+X]|0;\n if(!l||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(y=1;y<=H+1;++y){\n t=Ar[(y<<10)+X]|0;\n if(!l||L[l-1]<=t)P[l]=y,L[l++]=t;\n else{\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}, {"source_code": "t=readline().split(' '); MAX=1<<20; P=[]; L=[];\nW=+t[0]; H=+t[1]|0; Q=+t[2]; out='';\nAu=Array(MAX);\nAl=Array(MAX);\nAd=Array(MAX);\nAr=Array(MAX);\nfor(x=1;x<=W;++x){\n t=readline().split(' ');\n for(y=1;y<=H;++y)\n Al[(y<<10)+x]=Au[(x<<10)+y]=Ar[(y<<10)+W+1-x]=Ad[(x<<10)+H+1-y]=t[y-1]|0;\n}\nfunction calc(A,W,H){\n var x,y,t,i;\n for(y=1;y<=H;++y){\n i=(y<<10)+1; t=A[i];\n for(++i,x=2;x<=W;++x,++i){\n if(A[i])A[i]=++t;\n else t=0;\n }\n }\n}\ncalc(Au,H,W);\ncalc(Ad,H,W);\ncalc(Al,W,H);\ncalc(Ar,W,H);\nfunction sw(A,W,x,i){\n var t=A[i]=A[i]?0:(A[i-1]|0)+1;\n for(;++x<=W&&A[++i];)A[i]=++t;\n}\nfunction max(A,H,X,Y){\n var l=0,s,y,t,i; ++H;\n for(y=1;y<=H;++y){\n t=A[(y<<10)+X]|0;\n for(i=y;l&&L[l-1]>t;--l){\n i=P[l-1];\n s=L[l-1]*(y-i);\n if(y>Y&&Y>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]0;--y){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Al[(y<<10)+1],x=2;x<=W;++x){\n i=(y<<10)+x;\n if(Al[i])Al[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Ar[(y<<10)+W],x=W-1;x>0;--x){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]=++t;\n else t=0;\n }\n}\nfor(;Q--;){\n t=readline().split(' ');\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n if(Au[i])Au[i]=Ad[i]=Al[i]=Ar[i]=0;\n else{\n Au[i]=(Au[(Y-1<<10)+X]|0)+1;\n Ad[i]=(Ad[(Y+1<<10)+X]|0)+1;\n Al[i]=(Al[(Y<<10)+X-1]|0)+1;\n Ar[i]=(Ar[(Y<<10)+X+1]|0)+1;\n }\n for(t=Au[i],y=Y+1;y<=H&&Au[(y<<10)+X];++y)Au[(y<<10)+X]=++t;\n for(t=Ad[i],y=Y-1;y>0 &&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=++t;\n for(t=Al[i],x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=++t;\n for(t=Ar[i],x=X-1;x>0 &&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=++t;\n }\n else if(Au[i]){\n L=[]; P=[]; M=0; l=0;\n for(x=1;x<=W+1;++x){\n t=Au[(Y<<10)+x]|0;\n for(i=x;l&&L[l-1]>t;--l){\n i=P[l-1];\n s=L[l-1]*(x-i);\n if(x>X&&X>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]t;--l){\n i=P[l-1];\n s=L[l-1]*(x-i);\n if(x>X&&X>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]t;--l){\n i=P[l-1];\n s=L[l-1]*(y-i);\n if(y>Y&&Y>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]t;--l){\n i=P[l-1];\n s=L[l-1]*(y-i);\n if(y>Y&&Y>=i&&s>M)M=s;\n }\n if(t&&(!l||L[l-1]0;--y){\n i=(y<<10)+x;\n if(Ad[i])Ad[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Al[(y<<10)+1],x=2;x<=W;++x){\n i=(y<<10)+x;\n if(Al[i])Al[i]=++t;\n else t=0;\n }\n}\nfor(y=1;y<=H;++y){\n for(t=Ar[(y<<10)+W],x=W-1;x>0;--x){\n i=(y<<10)+x;\n if(Ar[i])Ar[i]=++t;\n else t=0;\n }\n}\nfor(;Q--;){\n t=readline().split(' ');\n X=t[1]|0; Y=t[2]|0; i=(Y<<10)+X;\n if(t[0]==='1'){\n if(Au[i])Au[i]=Ad[i]=Al[i]=Ar[i]=0;\n else{\n Au[i]=(Au[(Y-1<<10)+X]|0)+1;\n Ad[i]=(Ad[(Y+1<<10)+X]|0)+1;\n Al[i]=(Al[(Y<<10)+X-1]|0)+1;\n Ar[i]=(Ar[(Y<<10)+X+1]|0)+1;\n }\n for(t=Au[i],y=Y+1;y<=H&&Au[(y<<10)+X];++y)Au[(y<<10)+X]=++t;\n for(t=Ad[i],y=Y-1;y>0 &&Ad[(y<<10)+X];--y)Ad[(y<<10)+X]=++t;\n for(t=Al[i],x=X+1;x<=W&&Al[(Y<<10)+x];++x)Al[(Y<<10)+x]=++t;\n for(t=Ar[i],x=X-1;x>0 &&Ar[(Y<<10)+x];--x)Ar[(Y<<10)+x]=++t;\n }\n else if(Au[i]){\n L=[]; P=[]; M=0; l=0;\n for(x=1;x<=W+1;++x){\n t=Au[(Y<<10)+x]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t)L[0]=t;\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(x=1;x<=W+1;++x){\n t=Ad[(Y<<10)+x]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t)L[0]=t;\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(x-P[l-1]);\n if(x>X&&X>=P[l-1]&&s>M)M=s;\n }\n }\n }\n\n l=0;\n for(y=1;y<=H+1;++y){\n t=Al[(y<<10)+X]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t)L[0]=t;\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n l=0;\n for(y=1;y<=H+1;++y){\n t=Ar[(y<<10)+X]|0;\n if(t&&(!l||L[l-1]<=t)){\n if(!l||L[l-1]t)L[0]=t;\n for(;l&&L[l-1]>t;--l){\n s=L[l-1]*(y-P[l-1]);\n if(y>Y&&Y>=P[l-1]&&s>M)M=s;\n }\n }\n }\n \n out+=M+'\\n';\n }\n else out+='0\\n';\n}\nprint(out);\n"}], "src_uid": "895288258973317696185910fca8e32e"} {"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 — 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]$$$ — 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]$$$ — 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]$$$ — 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]$$$ — 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$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$) — 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": "var limit = parseInt(readline());\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var caseLength = parseInt(readline());\r\n var caseArray = new Array();\r\n for (var j = 1; j <= caseLength; j++)\r\n {\r\n caseArray.push(j);\r\n }\r\n print(caseLength);\r\n for (var j = 0; j < caseLength; j++)\r\n {\r\n if (j !== 0)\r\n {\r\n caseArray[j-1] = caseArray[j];\r\n caseArray[j] = 1\r\n }\r\n var result = \"\";\r\n for (var k = 0; k < caseLength; k++)\r\n {\r\n result += `${caseArray[k]} `;\r\n }\r\n print(result);\r\n }\r\n}"}, {"source_code": "var n;\r\n var arr;\r\n var tests = parseInt(readline());\r\n for (var t=0; t { inputString += inputStdin; });\r\nprocess.stdin.on('end', _ => { \r\n inputString = inputString.trim().split('\\n').map(string => string.trim());\r\n main(); \r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const t = +readLine();\r\n for(let i = 0; i < t; i++){\r\n const n = +readLine();\r\n myFunc(n);\r\n // const arr = readLine().split(' ').map(p => +p);\r\n // let result = myFunc(n);\r\n // console.log(result);\r\n }\r\n}\r\n\r\nfunction myFunc(n){\r\n \r\n let arr = [];\r\n for(let i = 0; i < n; i++){\r\n arr[i] = i+1;\r\n }\r\n\r\n console.log(n);\r\n console.log(...arr);\r\n\r\n for(let i = 1; i < n; i++){\r\n [arr[i-1], arr[i]] = [arr[i], arr[i-1]]\r\n console.log(...arr);\r\n }\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n output(n);\r\n\r\n let arr = [];\r\n for (let i = 1; i <= n; i++) {\r\n arr.push(i);\r\n }\r\n\r\n let left = 0;\r\n let right = 1;\r\n output(arr.join(' '));\r\n for (let i = 1; i < n; i++) {\r\n [arr[left], arr[right]] = [arr[right], arr[left]];\r\n right++;\r\n output(arr.join(' '));\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "var limit = parseInt(readline());\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var caseLength = parseInt(readline());\r\n var caseArray = new Array();\r\n for (var j = 1; j <= caseLength; j++)\r\n {\r\n caseArray.push(j);\r\n }\r\n print(caseLength);\r\n for (var j = 0; j < caseLength; j++)\r\n {\r\n if (j !== 0)\r\n {\r\n caseArray[j-1] = caseArray[j];\r\n caseArray[j] = 1\r\n }\r\n var result = \"\";\r\n for (var k = 0; k < caseLength; k++)\r\n {\r\n result += `${k} `;\r\n }\r\n print(result);\r\n }\r\n}"}, {"source_code": "var limit = parseInt(readline());\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var caseLength = parseInt(readline());\r\n var caseArray = new Array();\r\n for (var j = 1; j <= caseLength; j++)\r\n {\r\n caseArray.push(j);\r\n }\r\n print(caseLength);\r\n for (var j = 0; j < caseLength; j++)\r\n {\r\n if (j !== 0)\r\n {\r\n caseArray[j-1] = caseArray[j];\r\n caseArray[j] = 1\r\n }\r\n var result = \"\";\r\n for (var k = 0; k < caseLength; k++)\r\n {\r\n result += `$k `;\r\n }\r\n print(result);\r\n }\r\n}"}], "src_uid": "02bdd12987af6e666d4283f075f73725"} {"nl": {"description": "Adieu l'ami.Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.The space is represented by a rectangular grid of n × m cells, arranged into n rows and m columns. The c-th cell in the r-th row is denoted by (r, c).Oshino places and removes barriers around rectangular areas of cells. Specifically, an action denoted by \"1 r1 c1 r2 c2\" means Oshino's placing barriers around a rectangle with two corners being (r1, c1) and (r2, c2) and sides parallel to squares sides. Similarly, \"2 r1 c1 r2 c2\" means Oshino's removing barriers around the rectangle. Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the n × m area.Sometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. \"3 r1 c1 r2 c2\" means that Koyomi tries to walk from (r1, c1) to (r2, c2) without crossing barriers.And you're here to tell Koyomi the feasibility of each of his attempts.", "input_spec": "The first line of input contains three space-separated integers n, m and q (1 ≤ n, m ≤ 2 500, 1 ≤ q ≤ 100 000) — the number of rows and columns in the grid, and the total number of Oshino and Koyomi's actions, respectively. The following q lines each describes an action, containing five space-separated integers t, r1, c1, r2, c2 (1 ≤ t ≤ 3, 1 ≤ r1, r2 ≤ n, 1 ≤ c1, c2 ≤ m) — the type and two coordinates of an action. Additionally, the following holds depending on the value of t: If t = 1: 2 ≤ r1 ≤ r2 ≤ n - 1, 2 ≤ c1 ≤ c2 ≤ m - 1; If t = 2: 2 ≤ r1 ≤ r2 ≤ n - 1, 2 ≤ c1 ≤ c2 ≤ m - 1, the specified group of barriers exist on the ground before the removal. If t = 3: no extra restrictions. ", "output_spec": "For each of Koyomi's attempts (actions with t = 3), output one line — containing \"Yes\" (without quotes) if it's feasible, and \"No\" (without quotes) otherwise.", "sample_inputs": ["5 6 5\n1 2 2 4 5\n1 3 3 3 3\n3 4 4 1 1\n2 2 2 4 5\n3 1 1 4 4", "2500 2500 8\n1 549 1279 1263 2189\n1 303 795 1888 2432\n1 2227 622 2418 1161\n3 771 2492 1335 1433\n1 2017 2100 2408 2160\n3 48 60 798 729\n1 347 708 1868 792\n3 1940 2080 377 1546"], "sample_outputs": ["No\nYes", "No\nYes\nNo"], "notes": "NoteFor the first example, the situations of Koyomi's actions are illustrated below. "}, "positive_code": [{"source_code": " ;(function () {\n\tvar f = new Array();\n\tfor (var i = 0; i <= 2520; i++){\n\t\tf[i] = new Array(2521);\n\t\tfor(var j = 0; j <= 2530; j++)\n\t\t f[i][j]=0;\n\t}\n\tvar str = readline().split(' '),\n\t\tn = +str[0],\n\t\tm = +str[1],\n\t\tk = +str[2],\n\t\tcnt = 0;\n\tvar add = function (a, b, v) {\n\t\tfor (var i = a; i <= n; i += i & -i)\n\t\t\tfor (var j = b; j <= m; j += j & -j)\n\t\t\t\tf[i][j] = f[i][j] ^ v\n\t}\n\tvar ask = function (a, b) {\n\t\tvar ans = 0\n\t\tfor (var i = a; i; i ^= i & -i)\n\t\t\tfor (var j = b; j; j ^= j & -j)\n\t\t\t\tans ^= f[i][j]\n\t\treturn ans\n\t}\n\tvar update = function (a, b, c, d, e) {\n\t\tadd(a, b, e);\n\t\tadd(a, d+1, e);\n\t\tadd(c+1, b, e);\n\t\tadd(c+1, d+1, e);\n\t}\n\tvar hash = function (a, b, c, d) {\n\t\treturn a * b * c * d;\n\t}\n\twhile (k --) {\n\t\tvar line = readline().split(' '),\n\t\t\top = +line[0],\n\t\t\tx1 = +line[1],\n\t\t\ty1 = +line[2],\n\t\t\tx2 = +line[3],\n\t\t\ty2 = +line[4],\n\t\t\tid = hash(x1, y1, x2, y2);\n\t\tif (op == 1) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else if (op == 2) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else {\n\t\t\tprint(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');\n\t\t\t// print(ask(x1, y1))\n\t\t\t// print(ask(x2, y2))\n\t\t}\n\t}\n})();"}, {"source_code": " ;(function () {\n\tvar f = new Array();\n\tfor (var i = 0; i <= 2520; i++){\n\t\tf[i] = new Array(2521);\n\t\tfor(var j = 0; j <= 2520; j++)\n\t\t f[i][j]=0;\n\t}\n\tvar str = readline().split(' '),\n\t\tn = +str[0],\n\t\tm = +str[1],\n\t\tk = +str[2],\n\t\tcnt = 0;\n\tvar add = function (a, b, v) {\n\t\tfor (var i = a; i <= n; i += i & -i)\n\t\t\tfor (var j = b; j <= m; j += j & -j)\n\t\t\t\tf[i][j] = f[i][j] ^ v\n\t}\n\tvar ask = function (a, b) {\n\t\tvar ans = 0\n\t\tfor (var i = a; i; i ^= i & -i)\n\t\t\tfor (var j = b; j; j ^= j & -j)\n\t\t\t\tans ^= f[i][j]\n\t\treturn ans\n\t}\n\tvar update = function (a, b, c, d, e) {\n\t\tadd(a, b, e);\n\t\tadd(a, d+1, e);\n\t\tadd(c+1, b, e);\n\t\tadd(c+1, d+1, e);\n\t}\n\tvar hash = function (a, b, c, d) {\n\t\treturn a * b * c * d;\n\t}\n\twhile (k --) {\n\t\tvar line = readline().split(' '),\n\t\t\top = +line[0],\n\t\t\tx1 = +line[1],\n\t\t\ty1 = +line[2],\n\t\t\tx2 = +line[3],\n\t\t\ty2 = +line[4],\n\t\t\tid = hash(x1, y1, x2, y2);\n\t\tif (op == 1) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else if (op == 2) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else {\n\t\t\tprint(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');\n\t\t\t// print(ask(x1, y1))\n\t\t\t// print(ask(x2, y2))\n\t\t}\n\t}\n})();"}, {"source_code": ";(function () {\n\tvar f = new Array();\n\tfor (var i = 1; i <= 2520; i++)\n\t\tf[i] = new Array(2521).join(0).split('')\n\tvar str = readline().split(' '),\n\t\tn = +str[0],\n\t\tm = +str[1],\n\t\tk = +str[2],\n\t\tcnt = 0;\n\tvar add = function (a, b, v) {\n\t\tfor (var i = a; i <= n; i += i & -i)\n\t\t\tfor (var j = b; j <= m; j += j & -j)\n\t\t\t\tf[i][j] = +f[i][j] + v\n\t}\n\tvar ask = function (a, b) {\n\t\tvar ans = 0\n\t\tfor (var i = a; i; i ^= i & -i)\n\t\t\tfor (var j = b; j; j ^= j & -j)\n\t\t\t\tans += +f[i][j]\n\t\treturn ans\n\t}\n\tvar update = function (a, b, c, d, e) {\n\t\tadd(a, b, e);\n\t\tadd(a, d+1, -e);\n\t\tadd(c+1, b, -e);\n\t\tadd(c+1, d+1, e);\n\t}\n\tvar hash = function (a, b, c, d) {\n\t\treturn a * b * c * d;\n\t}\n\twhile (k --) {\n\t\tvar line = readline().split(' '),\n\t\t\top = +line[0],\n\t\t\tx1 = +line[1],\n\t\t\ty1 = +line[2],\n\t\t\tx2 = +line[3],\n\t\t\ty2 = +line[4],\n\t\t\tid = hash(x1, y1, x2, y2);\n\t\tif (op == 1) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else if (op == 2) {\n\t\t\tupdate(x1, y1, x2, y2, -id);\n\t\t} else {\n\t\t\tprint(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');\n\t\t\t// print(ask(x1, y1))\n\t\t\t// print(ask(x2, y2))\n\t\t}\n\t}\n})();"}, {"source_code": ";(function () {\n\tvar f = new Array();\n\tfor (var i = 1; i <= 2520; i++)\n\t\tf[i] = new Array(2521).join(0).split('')\n\tvar str = readline().split(' '),\n\t\tn = +str[0],\n\t\tm = +str[1],\n\t\tk = +str[2],\n\t\tcnt = 0;\n\tvar add = function (a, b, v) {\n\t\tfor (var i = a; i <= n; i += i & -i)\n\t\t\tfor (var j = b; j <= m; j += j & -j)\n\t\t\t\tf[i][j] = +f[i][j] ^ v\n\t}\n\tvar ask = function (a, b) {\n\t\tvar ans = 0\n\t\tfor (var i = a; i; i ^= i & -i)\n\t\t\tfor (var j = b; j; j ^= j & -j)\n\t\t\t\tans ^= +f[i][j]\n\t\treturn ans\n\t}\n\tvar update = function (a, b, c, d, e) {\n\t\tadd(a, b, e);\n\t\tadd(a, d+1, e);\n\t\tadd(c+1, b, e);\n\t\tadd(c+1, d+1, e);\n\t}\n\tvar hash = function (a, b, c, d) {\n\t\treturn a * b * c * d;\n\t}\n\twhile (k --) {\n\t\tvar line = readline().split(' '),\n\t\t\top = +line[0],\n\t\t\tx1 = +line[1],\n\t\t\ty1 = +line[2],\n\t\t\tx2 = +line[3],\n\t\t\ty2 = +line[4],\n\t\t\tid = hash(x1, y1, x2, y2);\n\t\tif (op == 1) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else if (op == 2) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else {\n\t\t\tprint(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');\n\t\t\t// print(ask(x1, y1))\n\t\t\t// print(ask(x2, y2))\n\t\t}\n\t}\n})();"}], "negative_code": [{"source_code": ";(function () {\n\tvar f = new Array();\n\tfor (var i = 1; i <= 2520; i++)\n\t\tf[i] = new Array(2521).join(0).split('')\n\tvar str = readline().split(' '),\n\t\tn = +str[0],\n\t\tm = +str[1],\n\t\tk = +str[2],\n\t\tcnt = 0;\n\tvar add = function (a, b, v) {\n\t\tfor (var i = a; i <= n; i += i & -i)\n\t\t\tfor (var j = b; j <= n; j += j & -j)\n\t\t\t\tf[i][j] = +f[i][j] + v\n\t}\n\tvar ask = function (a, b) {\n\t\tvar ans = 0\n\t\tfor (var i = a; i; i ^= i & -i)\n\t\t\tfor (var j = b; j; j ^= j & -j)\n\t\t\t\tans += +f[i][j]\n\t\treturn ans\n\t}\n\tvar update = function (a, b, c, d, e) {\n\t\tadd(a, b, e);\n\t\tadd(a, d+1, -e);\n\t\tadd(c+1, b, -e);\n\t\tadd(c+1, d+1, e);\n\t}\n\tvar hash = function (a, b, c, d) {\n\t\treturn a * b * c * d;\n\t}\n\twhile (k --) {\n\t\tvar line = readline().split(' '),\n\t\t\top = +line[0],\n\t\t\tx1 = +line[1],\n\t\t\ty1 = +line[2],\n\t\t\tx2 = +line[3],\n\t\t\ty2 = +line[4],\n\t\t\tid = hash(x1, y1, x2, y2);\n\t\tif (op == 1) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else if (op == 2) {\n\t\t\tupdate(x1, y1, x2, y2, -id);\n\t\t} else {\n\t\t\tprint(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');\n\t\t\t// print(ask(x1, y1))\n\t\t\t// print(ask(x2, y2))\n\t\t}\n\t}\n})();"}, {"source_code": ";(function () {\n\tvar f = new Array();\n\tfor (var i = 1; i <= 2520; i++)\n\t\tf[i] = new Array(2521).join(0).split('')\n\tvar str = readline().split(' '),\n\t\tn = +str[0],\n\t\tm = +str[1],\n\t\tk = +str[2],\n\t\tcnt = 0;\n\tvar add = function (a, b, v) {\n\t\tfor (var i = a; i <= n; i += i & -i)\n\t\t\tfor (var j = b; j <= n; j += j & -j)\n\t\t\t\tf[i][j] = +f[i][j] + v\n\t}\n\tvar ask = function (a, b) {\n\t\tvar ans = 0\n\t\tfor (var i = a; i; i ^= i & -i)\n\t\t\tfor (var j = b; j; j ^= j & -j)\n\t\t\t\tans += +f[i][j]\n\t\treturn ans\n\t}\n\tvar update = function (a, b, c, d, e) {\n\t\tadd(a, b, e);\n\t\tadd(a, d+1, -e);\n\t\tadd(c+1, b, -e);\n\t\tadd(c+1, d+1, e);\n\t}\n\tvar hash = function (a, b, c, d) {\n\t\treturn a * b * c * d;\n\t}\n\twhile (k --) {\n\t\tvar line = readline().split(' '),\n\t\t\top = +line[0],\n\t\t\tx1 = +line[1],\n\t\t\ty1 = +line[2],\n\t\t\tx2 = +line[3],\n\t\t\ty2 = +line[4],\n\t\t\tid = hash(x1, y1, x2, y2);\n\t\tif (op == 1) {\n\t\t\tupdate(x1, y1, x2, y2, id);\n\t\t} else if (op == 2) {\n\t\t\tupdate(x1, y1, x2, y2, -id);\n\t\t} else {\n\t\t\tprint(ask(x1, y1) === ask(x2, y2) ? 'YES' : 'NO');\n\t\t\t// print(ask(x1, y1))\n\t\t\t// print(ask(x2, y2))\n\t\t}\n\t}\n})();"}], "src_uid": "263e0f82e7c8c749f5699d19b99ef418"} {"nl": {"description": "In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.A string is a bHTML table, if it satisfies the grammar: TABLE ::= <table>ROWS</table>ROWS ::= ROW | ROW ROWSROW ::= <tr>CELLS</tr>CELLS ::= CELL | CELL CELLSCELL ::= <td></td> | <td>TABLE</td>Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : \"table\", \"tr\", \"td\", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.", "input_spec": "For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.", "output_spec": "Print the sizes of all the tables in the non-decreasing order.", "sample_inputs": ["<table><tr><td></td></tr></table>", "<table>\n<tr>\n<td>\n<table><tr><td></td></tr><tr><td></\ntd\n></tr><tr\n><td></td></tr><tr><td></td></tr></table>\n</td>\n</tr>\n</table>", "<table><tr><td>\n<table><tr><td>\n<table><tr><td>\n<table><tr><td></td><td></td>\n</tr><tr><td></td></tr></table>\n</td></tr></table>\n</td></tr></table>\n</td></tr></table>"], "sample_outputs": ["1", "1 4", "1 1 1 3"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nlet ht = ''\nlet j = 10\n\nwhile (j--) {\n ht += readline() || ''\n}\n\nlet tst = []\nlet ts = []\n\nfor (let i = 0; i < ht.length; i++) {\n if (ht.slice(i, i + 7) == '') {\n tst.push(0)\n } else if (ht.slice(i, i + 8) == '
') {\n ts.push(tst.pop())\n } else if (ht.slice(i, i + 4) == '') {\n tst[tst.length - 1]++\n }\n}\n\nprint(ts.sort((a, b) => a - b).join(' '))"}], "negative_code": [], "src_uid": "eb5a5adffedacadad1df27a1ddc7f8ff"} {"nl": {"description": "We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.", "input_spec": "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 contains a single integer $$$n$$$ $$$(1\\le n\\le 2 \\cdot 10^5)$$$  — the size of array $$$a$$$. 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$$$) — 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": "For each test case, print \"Yes\" (without quotes) if it's possible to obtain $$$a$$$ after some 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": ["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"], "sample_outputs": ["No\nYes\nNo\nNo\nYes\nYes\nYes"], "notes": "NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\\langle \\underline{0}, 0, 0, 0\\rangle \\to \\langle 1, \\underline{0}, 0, 0 \\rangle \\to \\langle \\underline{1}, -1, 0, 0\\rangle \\to \\langle 2, \\underline{-1}, 0, 0\\rangle \\to \\langle 2, 0, \\underline{0}, 0\\rangle \\to \\langle 2, \\underline{0}, -1, 0\\rangle \\to \\langle \\underline{2}, -1, -1, 0\\rangle$$$"}, "positive_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n if(sum!==0) return 'NO'\r\n while(a.length && !a[a.length-1])a.pop()\r\n if(a[0]){\r\n while(a.length>1){\r\n const last=a.length-1\r\n if(a[last]>=0)return 'NO'\r\n a[last-1]+=a.pop()\r\n }\r\n }else if(a.length){\r\n return 'NO'\r\n }\r\n return 'YES'\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n {\r\n let sum = 0,\r\n flag = false;\r\n for (let i = 0; i < n ; i++) {\r\n sum += a[i];\r\n if (sum < 0) return 'NO';\r\n if (flag && sum !== 0) return 'NO';\r\n if (sum === 0) flag = true;\r\n }\r\n if(sum!==0)return 'NO'\r\n }\r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n if (sum !== 0) return 'NO';\r\n //if (n <= 2) return 'YES';\r\n {\r\n let sum = 0,\r\n flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n sum += a[i];\r\n if (sum < 0) return 'NO';\r\n if (flag && sum !== 0) return 'NO';\r\n if (sum === 0) flag = true;\r\n }\r\n }\r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = Number(lines[i]);\n }else{\n var a = lines[i].split(' ').map(Number);\n var flag = false;\n var x = 0;\n for(j = 0; j < n; j++){\n if(a[j] + x < 0){\n flag = true;\n }\n if(j && a[j] > 0 && x === 0){\n flag = true;\n }\n x = a[j] + x;\n }\n if(x !== 0){\n flag = true;\n }\n if(flag){\n console.log('NO');\n }else{\n console.log('YES');\n }\n }\n }\n});\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\nfunction output(x) {\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n \r\nfunction main() {\r\n let N = readline();\r\n \r\n for (let i = 0; i < N; i++) {\r\n let size = Number(readline());\r\n let arr = readline().split(' ').map(Number);\r\n let jumpsToTheRight = new Array(size).fill(0);\r\n jumpsToTheRight[0] = arr[0];\r\n let sum = arr[0];\r\n for (let index = 1; index < jumpsToTheRight.length; index++) {\r\n jumpsToTheRight[index] = arr[index] + jumpsToTheRight[index - 1];\r\n sum += arr[index];\r\n }\r\n\r\n let result = 'yes';\r\n let zero = false;\r\n for (let jumps of jumpsToTheRight) {\r\n if (jumps < 0) {\r\n result = 'no';\r\n break;\r\n } else if (jumps === 0) {\r\n zero = true;\r\n } else if (zero) {\r\n result = 'no';\r\n break;\r\n }\r\n }\r\n\r\n if (sum !== 0) {\r\n result = 'no';\r\n }\r\n\r\n output(result);\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n if(sum!==0) return 'NO'\r\n while(a.length && !a[a.length-1])a.pop()\r\n if(a[0]){\r\n while(a.length>1){\r\n const last=a.length-1\r\n if(a[last]>0)return 'NO'\r\n a[last-1]+=a.pop()\r\n }\r\n }else if(a.length){\r\n return 'NO'\r\n }\r\n return 'YES'\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n if(sum!==0) return 'NO'\r\n while(a.length && !a[a.length-1])a.pop()\r\n if(a[0]){\r\n while(a.length>1){\r\n console.log(a)\r\n const last=a.length-1\r\n if(a[last]>0)return 'NO'\r\n a[last-1]+=a.pop()\r\n }\r\n }else if(a.length){\r\n return 'NO'\r\n }\r\n return 'YES'\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n if(sum!==0) return 'NO'\r\n a.reverse()\r\n while(a.length>1){\r\n const last=a.length-1\r\n if(a[last]<0 || a[last] str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n if(sum!==0)return 'NO'\r\n {\r\n let sum = 0\r\n for (let i = 0; i < n ; i++) {\r\n sum += a[i];\r\n if (sum < 0) return 'NO';\r\n }\r\n }\r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n {\r\n let sum = 0,\r\n flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n sum += a[i];\r\n if (sum < 0) return 'NO';\r\n if (flag && sum !== 0) return 'NO';\r\n if (sum === 0) flag = true;\r\n }\r\n if(sum!==0)return 'NO'\r\n }\r\n \r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n {\r\n let sum = 0,\r\n flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n sum += a[i];\r\n if (sum < 0) return 'NO';\r\n if (flag && sum !== 0) return 'NO';\r\n if (sum === 0) flag = true;\r\n }\r\n }\r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b);\r\n if (sum !== 0) return 'NO';\r\n if (n <= 2) return 'YES';\r\n {\r\n let sum = 0,\r\n flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n sum += a[i];\r\n if (sum < 0) return 'NO';\r\n if (flag && sum !== 0) return 'NO';\r\n if (sum === 0) flag = true;\r\n }\r\n }\r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "src_uid": "9f0ffcbd0ce62a365a1ecbb4a2c1de3e"} {"nl": {"description": "There are $$$n$$$ heaps of stone. The $$$i$$$-th heap has $$$h_i$$$ stones. You want to change the number of stones in the heap by performing the following process once: You go through the heaps from the $$$3$$$-rd heap to the $$$n$$$-th heap, in this order. Let $$$i$$$ be the number of the current heap. You can choose a number $$$d$$$ ($$$0 \\le 3 \\cdot d \\le h_i$$$), move $$$d$$$ stones from the $$$i$$$-th heap to the $$$(i - 1)$$$-th heap, and $$$2 \\cdot d$$$ stones from the $$$i$$$-th heap to the $$$(i - 2)$$$-th heap. So after that $$$h_i$$$ is decreased by $$$3 \\cdot d$$$, $$$h_{i - 1}$$$ is increased by $$$d$$$, and $$$h_{i - 2}$$$ is increased by $$$2 \\cdot d$$$. You can choose different or same $$$d$$$ for different operations. Some heaps may become empty, but they still count as heaps. What is the maximum number of stones in the smallest heap after the process?", "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^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$). The second lines of each test case contains $$$n$$$ integers $$$h_1, h_2, h_3, \\ldots, h_n$$$ ($$$1 \\le h_i \\le 10^9$$$). 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 maximum number of stones that the smallest heap can contain.", "sample_inputs": ["4\n4\n1 2 10 100\n4\n100 100 100 1\n5\n5 1 1 1 8\n6\n1 2 3 4 5 6"], "sample_outputs": ["7\n1\n1\n3"], "notes": "NoteIn the first test case, the initial heap sizes are $$$[1, 2, 10, 100]$$$. We can move the stones as follows. move $$$3$$$ stones and $$$6$$$ from the $$$3$$$-rd heap to the $$$2$$$-nd and $$$1$$$ heap respectively. The heap sizes will be $$$[7, 5, 1, 100]$$$; move $$$6$$$ stones and $$$12$$$ stones from the last heap to the $$$3$$$-rd and $$$2$$$-nd heap respectively. The heap sizes will be $$$[7, 17, 7, 82]$$$. In the second test case, the last heap is $$$1$$$, and we can not increase its size.In the third test case, it is better not to move any stones.In the last test case, the final achievable configuration of the heaps can be $$$[3, 5, 3, 4, 3, 3]$$$."}, "positive_code": [{"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nlet solve = async () => {\r\n const nsc = parseInt(await getLine());\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = parseInt(await getLine());\r\n const h = (await getLine()).split(' ').map(num => parseInt(num));\r\n let l = 0, r = 0;\r\n let best = 0;\r\n for(let i = 0; i < n; i++)\r\n r = Math.max(r, h[i]);\r\n const workh = new Array(n);\r\n\r\n const resolve = function(th) {\r\n for(let i = 0; i < n; i++)\r\n workh[i] = 0;\r\n\r\n for(let i = n - 1; i >=0; i--) {\r\n if (h[i] + workh[i] < th)\r\n return false;\r\n const rem = h[i] + workh[i] - th;\r\n if (i>=2) {\r\n workh[i - 1] += Math.floor(Math.min(h[i], rem) / 3);\r\n workh[i - 2] += Math.floor(Math.min(h[i], rem) / 3) * 2;\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n while (l <= r) {\r\n const mid = Math.floor((l+r) / 2);\r\n if (resolve(mid)) {\r\n best = mid;\r\n l = mid + 1;\r\n } else {\r\n r = mid - 1;\r\n }\r\n }\r\n\r\n console.log(best);\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst h = rna();\r\n\r\n\t\tfunction check (x) {\r\n\t\t\tconst hh = h.slice();\r\n\t\t\tfor (let i = n-1; i >= 2; i--) {\r\n\t\t\t\tif (hh[i] < x) \r\n\t\t\t\t\treturn false;\r\n\t\t\t\tlet d = Math.floor((hh[i]-x)/3);\r\n\t\t\t\td = Math.min(Math.floor(h[i]/3), d);\r\n\t\t\t\thh[i] -= 3*d;\r\n\t\t\t\thh[i-1] += d;\r\n\t\t\t\thh[i-2] += 2*d;\r\n\t\t\t}\r\n\t\t\treturn hh[0] >= x && hh[1] >= x;\r\n\t\t}\r\n\r\n\t\tlet l = 1, r = 1e9;\r\n\t\twhile (r-l > 1) {\r\n\t\t\tlet m = l + r >> 1;\r\n\t\t\tif (check(m)) {\r\n\t\t\t\tl = m;\r\n\t\t\t} else {\r\n\t\t\t\tr = m-1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst ans = check(r) ? r : l;\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction solve_one_test() {\n let n = parseInt(readline());\n let array = readline().split(\" \").map(x => parseInt(x));\n // console.log(array);\n\n let low = 0;\n let high = 1e9 + 1;\n\n while (low + 1 != high) {\n let mid = Math.floor((low + high) / 2);\n\n function can_do(min_element) {\n carry = 0;\n carry_next = 0;\n\n for (let i = n - 1; i >= 0; --i) {\n let need_move = Math.floor((array[i] + carry - min_element) / 3);\n need_move = Math.min(need_move, Math.floor(array[i] / 3));\n\n if (i <= 1) {\n need_move = 0;\n }\n\n if (need_move < 0) {\n need_move = 0;\n }\n\n if (array[i] + carry - need_move * 3 < min_element) {\n return false;\n }\n\n carry = carry_next;\n carry_next = 0;\n\n carry += need_move;\n carry_next += need_move * 2;\n }\n\n if (carry > 0 || carry_next > 0) {\n return false;\n }\n\n return true;\n };\n\n if (can_do(mid)) {\n low = mid;\n } else {\n high = mid;\n }\n }\n\n console.log(low)\n}\n\nfunction main() {\n let num_tests = parseInt(readline());\n\n for (let i = 0; i < num_tests; ++i) {\n solve_one_test();\n }\n}\n"}], "negative_code": [{"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nlet solve = async () => {\r\n const nsc = parseInt(await getLine());\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = parseInt(await getLine());\r\n const h = (await getLine()).split(' ').map(num => parseInt(num));\r\n let l = 0, r = 0;\r\n let best = 0;\r\n for(let i = 0; i < n; i++)\r\n r = Math.max(r, h[i]);\r\n const workh = new Array(n);\r\n\r\n const resolve = function(th) {\r\n for(let i = 0; i < n; i++)\r\n workh[i] = 0;\r\n\r\n for(let i = n - 1; i >=0; i--) {\r\n if (h[i] + workh[i] < th)\r\n return false;\r\n const rem = h[i] + workh[i] - th;\r\n if (i > 0) {\r\n workh[i-1] += Math.floor(Math.min(h[i], rem)/3);\r\n }\r\n if (i > 1)\r\n workh[i-2] += Math.floor(Math.min(h[i], rem)/3) * 2;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n while (l <= r) {\r\n const mid = Math.floor((l+r) / 2);\r\n if (resolve(mid)) {\r\n best = mid;\r\n l = mid + 1;\r\n } else {\r\n r = mid - 1;\r\n }\r\n }\r\n\r\n console.log(best);\r\n }\r\n}\r\n\r\nsolve();\r\n"}], "src_uid": "895d5850e420a36ae3b5f0a50e359423"} {"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$$$)  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer  — $$$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": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var n = +readline();\n if (n === 1) {\n print(\"FastestFinger\");\n continue;\n }\n if (n % 2 || n === 2) {\n print(\"Ashishgup\");\n continue;\n }\n check(n);\n }\n}\n\nfunction check(n) {\n var m = n;\n while (m > 1 && m % 2 === 0) {\n m = m / 2;\n }\n if (m === 1 || (n / m === 2 && isSimple(m))) {\n print(\"FastestFinger\");\n return;\n }\n print(\"Ashishgup\");\n}\n\nfunction isSimple(n) {\n var sq = Math.floor(Math.sqrt(n)) + 1;\n for (var k = 3; k < sq; k += 2) {\n if (n % k === 0) {\n return false;\n }\n }\n return true;\n}\nmain();\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nvar input = '';\nprocess.stdin.on('data', function (line) {\n input += line;\n});\nprocess.stdin.on('end', function () {\n var lines = input.split('\\n');\n var tests = parseInt(lines.shift(), 10);\n while (tests--) {\n var n = parseInt(lines.shift(), 10);\n var ans = (function (n) {\n if (n == 1) {\n return 1;\n }\n if (n === 2) {\n return 0;\n }\n if (n % 2 === 1) {\n return 0;\n }\n if ((n & (n - 1)) === 0) {\n return 1;\n }\n var twoCount = 0;\n while (n % 2 === 0) {\n n /= 2;\n twoCount++;\n }\n if (twoCount > 1) {\n return 0;\n }\n return isPrime(n) ? 1 : 0;\n })(n);\n console.log(['Ashishgup', 'FastestFinger'][ans]);\n }\n});\nfunction isPrime(n) {\n for (var i = 3; i * i <= n; i += 2) {\n if (n % i === 0) {\n return false;\n }\n }\n return true;\n}\n// input helper\nfunction lineToNumArray(line) {\n return line.split(' ').map(function (element) { return parseInt(element, 10); });\n}\n"}, {"source_code": "function findPrimeFactors (num) {\n\n var primeFactors = [];\n while (num % 2 === 0) {\n primeFactors.push(2);\n num = num / 2;\n }\n\n var sqrtNum = Math.sqrt(num);\n for (var i = 3; i <= sqrtNum; i++) {\n while (num % i === 0) {\n primeFactors.push(i);\n num = num / i;\n }\n }\n\n if (num > 2) {\n primeFactors.push(num);\n }\n return primeFactors;\n}\n\nconst processData = (lines) => {\n let acc = 0\n const n = +lines[acc]\n acc++\n for (let i=0; i 1) {\n console.log('Ashishgup')\n } else {\n if (nonTwos > 1) {\n console.log('Ashishgup')\n } else {\n console.log('FastestFinger')\n }\n }\n }\n }\n }\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n C();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nlet checkOddFactor = (n) => {\n let i = 2;\n let oddNum = 1;\n while(i*i <= n){\n if(n%i === 0){\n if(i%2 !== 0){\n oddNum *= i;\n }else if((n/i)%2 !== 0){\n oddNum *= (n/i);\n }\n }\n i++;\n }\n return oddNum;\n}\n\nlet checkPrime = (n) => {\n let i = 2;\n while(i*i <= n){\n if(n%i === 0)\n return false;\n i++;\n }\n\n return true;\n}\n\nfunction C(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let winner = '';\n\n if(n === 1){\n winner = 1;\n }else if(n === 2){\n winner = 0;\n }\n else if(n%2 !== 0){\n winner = 0;\n }else{\n let x = (n & (n-1));\n if(n % 4 === 0 && x !== 0){\n winner = 0;\n }else if(x === 0){\n winner = 1;\n }else{\n if(checkPrime(n/2)){\n winner = 1;\n }else{\n winner = 0;\n }\n }\n }\n\n console.log(winner === 0 ? 'Ashishgup' : 'FastestFinger');\n }\n}"}], "negative_code": [{"source_code": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var n = +readline();\n if (n === 1) {\n print(\"FastestFinger\");\n continue;\n }\n if (n % 2 || n === 2) {\n print(\"Ashishgup\");\n continue;\n }\n check(n);\n }\n}\n\nfunction check(n) {\n var m = n;\n while (m > 1 && m % 2 === 0) {\n m = m / 2;\n }\n if (m === 1 || n / m === 2) {\n print(\"FastestFinger\");\n return;\n }\n print(\"Ashishgup\");\n}\nmain();"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n C();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nlet checkOddFactor = (n) => {\n let i = 2;\n while(i*i <= n){\n if(n%i === 0 && (i%2 !== 0 || (n/i)%2 !== 0)){\n return i%2 !== 0 ? i : n/(n/i);\n }\n i++;\n }\n return n;\n}\n\nfunction C(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let turn = 0;\n let winner = '';\n while(n > 1){\n if(n%2 !== 0){\n winner = turn === 0 ? 'Ashishgup' : 'FastestFinger';\n break;\n }else{\n let x = checkOddFactor(n);\n if(x === n){\n if(n === 2){\n winner = turn === 0 ? 'Ashishgup' : 'FastestFinger'; \n }else{\n winner = turn === 0 ? 'FastestFinger' : 'Ashishgup';\n }\n break;\n }\n n = x;\n }\n turn = turn === 0 ? 1 : 0;\n }\n\n if(winner === ''){\n console.log(turn === 0 ? 'FastestFinger' : 'Ashishgup');\n }else{\n console.log(winner);\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n C();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nlet checkOddFactor = (n) => {\n let i = 2;\n while(i*i <= n){\n if(n%i === 0 && i%2 !== 0)\n return n/i;\n i++;\n }\n return n;\n}\n\nfunction C(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let turn = 0;\n let winner = '';\n while(n > 1){\n if(n%2 !== 0){\n winner = turn === 0 ? 'Ashishgup' : 'FastestFinger';\n break;\n }else{\n let x = checkOddFactor(n);\n if(x === n){\n if(n === 2){\n winner = turn === 0 ? 'Ashishgup' : 'FastestFinger'; \n }else{\n winner = turn === 0 ? 'FastestFinger' : 'Ashishgup';\n }\n break;\n }\n n = x;\n }\n turn = turn === 0 ? 1 : 0;\n }\n\n if(winner === ''){\n console.log(turn === 0 ? 'FastestFinger' : 'Ashishgup');\n }else{\n console.log(winner);\n }\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n C();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nlet checkOddFactor = (n) => {\n let i = 2;\n while(i*i <= n){\n if(n%i === 0 && (i%2 !== 0 || (n/i)%2 !== 0)){\n return i%2 !== 0 ? n/i : n/(n/i);\n }\n i++;\n }\n return n;\n}\n\nfunction C(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let turn = 0;\n let winner = '';\n while(n > 1){\n if(n%2 !== 0){\n winner = turn === 0 ? 'Ashishgup' : 'FastestFinger';\n break;\n }else{\n let x = checkOddFactor(n);\n if(x === n){\n if(n === 2){\n winner = turn === 0 ? 'Ashishgup' : 'FastestFinger'; \n }else{\n winner = turn === 0 ? 'FastestFinger' : 'Ashishgup';\n }\n break;\n }\n n = x;\n }\n turn = turn === 0 ? 1 : 0;\n }\n\n if(winner === ''){\n console.log(turn === 0 ? 'FastestFinger' : 'Ashishgup');\n }else{\n console.log(winner);\n }\n }\n}"}], "src_uid": "b533572dd6d5fe7350589c7f4d5e1c8c"} {"nl": {"description": "We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings \"ab\" in the string and replace it with the string \"bba\". If we have no \"ab\" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.The string \"ab\" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.", "input_spec": "The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.", "output_spec": "Print the minimum number of steps modulo 109 + 7.", "sample_inputs": ["ab", "aab"], "sample_outputs": ["1", "3"], "notes": "NoteThe first example: \"ab\"  →  \"bba\".The second example: \"aab\"  →  \"abba\"  →  \"bbaba\"  →  \"bbbbaa\"."}, "positive_code": [{"source_code": "var line = readline();\nvar total = 0;\nvar increment = 0;\nvar n = 1000000007;\nfor (var i = 0; i < line.length; i++){\n if (line[i] == \"a\")\n increment = (2 * increment + 1) % n;\n else\n total = (total + increment) % n;\n}\n\n/*\nvar newStr = ['b','b','a'];\nvar str = [];\nfor (var i = 0; i < line.length; i++)\n str[i] = line[i];\n\nif (str.length > 1){\n for (var i = 1; i < str.length; i++){\n if (str[i] == 'b' && str[i - 1] == 'a'){\n //str = str.slice(0, i - 1).concat(newStr).concat(str.slice(i + 1));\n str = str.\n total++;\n i-=2;\n }\n }\n}\n*/\nprint(total);"}, {"source_code": "var s = readline();\nvar count = 0;\nvar countb = 0;\nfor (var i=s.length-1; i>=0; i--){\n\tif (s[i] == 'b') countb++;\n\telse {\n\t\tcount += countb; \n\t\tcountb *= 2; \n\t\tcount %= 1000000007;\n\t\tcountb %= 1000000007;\n\t}\n}\nprint (count);"}, {"source_code": "var s = readline();\nvar count = 0;\nvar countb = 0;\nvar counta = 0;\nfor (var i=s.length-1; i>=1; i--){\n\tif (s[i] == 'b' && s[i-1] == 'b') countb++;\n\tif (s[i] == 'b' && s[i-1] == 'a') {\n\t\tcountb++;\n\t\tcount += countb;\n\t\tcount %= 1000000007;\n\t\tcountb %= 1000000007;\n\t}\n\tif (s[i] == 'a' && s[i-1] == 'a') {\n\t\tcountb *= 2;\n\t\tcount += countb;\n\t\tcount %= 1000000007;\n\t\tcountb %= 1000000007;\n\t}\n\tif (s[i] == 'a' && s[i-1] == 'b') {\n\t\tcountb *= 2;\n\t}\n}\nprint (count%1000000007);"}], "negative_code": [{"source_code": "var line = readline();\nvar total = 0;\nvar increment = 0;\nfor (var i = 0; i < line.length; i++){\n if (line[i] == \"a\")\n increment = 2 * increment + 1;\n else\n total += increment;\n}\n\n/*\nvar newStr = ['b','b','a'];\nvar str = [];\nfor (var i = 0; i < line.length; i++)\n str[i] = line[i];\n\nif (str.length > 1){\n for (var i = 1; i < str.length; i++){\n if (str[i] == 'b' && str[i - 1] == 'a'){\n //str = str.slice(0, i - 1).concat(newStr).concat(str.slice(i + 1));\n str = str.\n total++;\n i-=2;\n }\n }\n}\n*/\nprint(total);"}, {"source_code": "var s = readline();\nvar count = 0;\nvar countb = 0;\nvar counta = 0;\nfor (var i=s.length-1; i>=1; i--){\n\tif (s[i] == 'b' && s[i-1] == 'b') countb++;\n\tif (s[i] == 'b' && s[i-1] == 'a') {\n\t\tcountb++;\n\t\tcount += countb;\n\t}\n\tif (s[i] == 'a' && s[i-1] == 'a') {\n\t\tcountb *= 2;\n\t\tcount += countb;\n\t}\n}\nprint (count%(1000000000 + 7));"}, {"source_code": "var s = readline();\nvar count = 0;\nvar countb = 0;\nvar counta = 0;\nfor (var i=s.length-1; i>=1; i--){\n\tif (s[i] == 'b' && s[i-1] == 'b') countb++;\n\tif (s[i] == 'b' && s[i-1] == 'a') {\n\t\tcountb++;\n\t\tcount += countb;\n\t}\n\tif (s[i] == 'a' && s[i-1] == 'a') {\n\t\tcountb *= 2;\n\t\tcount += countb;\n\t}\n\tif (s[i] == 'a' && s[i-1] == 'b') {\n\t\tcountb *= 2;\n\t}\n}\nprint (count%(1000000000 + 7));"}], "src_uid": "8f52241c690ec4f9af71a52904fb19a0"} {"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$$$) — 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$$$) — 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 — 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": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet ans = a[0];\r\n\t\tfor (const elm of a) ans &= elm;\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tfor(var i = 0; i < N - 1; i++){\r\n\t\t\tfor(var j = i + 1; j < N; j++){\r\n\t\t\t\tvar L = i;\r\n\t\t\t\tvar R = j;\r\n\t\t\t\tfor(var k = L; k <= R; k++){\r\n\t\t\t\t\tvar tmp = list[k] & list[R - k];\r\n\t\t\t\t\tlist[k] = tmp;\r\n\t\t\t\t\tlist[R - k] = tmp;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor(var i = 0; i < N - 1; i++){\r\n\t\t\tfor(var j = i + 1; j < N; j++){\r\n\t\t\t\tvar L = i;\r\n\t\t\t\tvar R = j;\r\n\t\t\t\tfor(var k = L; k <= R; k++){\r\n\t\t\t\t\tvar tmp = list[k] & list[R - k];\r\n\t\t\t\t\tlist[k] = tmp;\r\n\t\t\t\t\tlist[R - k] = tmp;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar max = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tmax = Math.max(max, list[i]);\r\n\t\t}\r\n\t\tmyout(max);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(e)\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(n => {\r\n stdin.on('data', n => e.push(n)),\r\n stdin.on('end', function () {\r\n const t = e.join('').split(os.EOL)\r\n n(t)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const n = new InputAndOutput()\r\n await n.init(), e(n)\r\n}\r\nfunction solve(e, n) {\r\n let t = n[0]\r\n for (let s = 1; s < e; ++s) t &= n[s]\r\n return t\r\n}\r\n__main__(function (e) {\r\n const n = Number(e.readLine())\r\n for (let t = 1; t <= n; ++t) {\r\n const n = solve(Number(e.readLine()), e.readIntegersOfLine())\r\n e.print(n + '\\n')\r\n }\r\n})\r\n"}, {"source_code": "let inputBuffer = ''\r\nprocess.stdin.on('data', data => {\r\n\tinputBuffer += data\r\n})\r\nprocess.stdin.on('end', _ => {\r\n\tinputBuffer = inputBuffer.trim().split('\\n')\r\n\r\n\tmain()\r\n})\r\n\r\nlet currentLine = 0\r\nfunction readline() {\r\n\treturn inputBuffer[currentLine++]\r\n}\r\nfunction readint() {\r\n\treturn parseInt(readline(), 10)\r\n}\r\nfunction readints() {\r\n\treturn readline().split(' ').map(s => parseInt(s, 10))\r\n}\r\nfunction print(s) {\r\n\tprocess.stdout.write(s + '\\n')\r\n}\r\nfunction write(s) {\r\n\tprocess.stdout.write(s)\r\n}\r\n\r\nfunction range(lowerBound, upperBound = undefined, step = 1) {\r\n\tif (upperBound === undefined) {\r\n\t\tupperBound = lowerBound\r\n\t\tlowerBound = 0\r\n\t}\r\n\tlet ret = []\r\n\tfor (let i = lowerBound; i < upperBound; i += step) ret.push(i)\r\n\treturn ret\r\n}\r\nfunction loop(lowerBound, upperBound = undefined, step = 1) {\r\n\treturn (func) => {\r\n\t\trange(lowerBound, upperBound, step).forEach(i => func(i))\r\n\t}\r\n}\r\n\r\nfunction main() {\r\n\tlet t = readint()\r\n\tloop(t)(_ => {\r\n\t\treadint()\r\n\t\tprint(readints().reduce((prev, x) => prev & x))\r\n\t})\r\n}\r\n"}, {"source_code": "var t = parseInt(readline())\nwhile(t--){\n var n=parseInt(readline())\n var v=readline().split(' ')\n var res=v[0]\n while(--n)\n res &= v[n]\n print(res)\n}"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst readLine = () => dataitr.next().value.trim();\r\nfunction rl () {\r\n\tlet ans = readLine().split(' ');\r\n\tif (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));\r\n\treturn ans.length == 1 ? ans[0] : ans;\r\n}\r\n\r\nfunction main () {\r\n\tlet t = rl();\r\n\twhile(t--){\r\n\t\tlet n = rl();\r\n\t\tlet a = rl();\r\n\r\n\t\tlet ans = a[0];\r\n\t\tfor (let i = 1 ; i < n; i++)\r\n\t\t\tans &= a[i];\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst readLine = () => dataitr.next().value.trim();\r\nfunction rl () {\r\n\tlet ans = readLine().split(' ');\r\n\tif (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));\r\n\treturn ans.length == 1 ? ans[0] : ans;\r\n}\r\n\r\nfunction main () {\r\n\tlet t = rl();\r\n\twhile(t--) {\r\n\t\tlet n = rl();\r\n\t\tlet a = rl();\r\n\t\tconsole.log(a[n - 1]);\r\n\t}\r\n\r\n}\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tfor(var i = 0; i < N - 1; i++){\r\n\t\t\tfor(var j = i + 1; j < N; j++){\r\n\t\t\t\tvar L = i;\r\n\t\t\t\tvar R = j;\r\n\t\t\t\tfor(var k = L; k <= R; k++){\r\n\t\t\t\t\tvar tmp = list[k] & list[R - k];\r\n\t\t\t\t\tlist[k] = tmp;\r\n\t\t\t\t\tlist[R - k] = tmp;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar max = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tmax = Math.max(max, list[i]);\r\n\t\t}\r\n\t\tmyout(max);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(e)\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(n => {\r\n stdin.on('data', n => e.push(n)),\r\n stdin.on('end', function () {\r\n const t = e.join('').split(os.EOL)\r\n n(t)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const n = new InputAndOutput()\r\n await n.init(), e(n)\r\n}\r\nfunction solve() {\r\n return -1\r\n}\r\n__main__(function (e) {\r\n const n = Number(e.readLine())\r\n for (let t = 1; t <= n; ++t) {\r\n const n = solve()\r\n e.print(n + '\\n')\r\n }\r\n})\r\n"}], "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$$$) — 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": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a)return u=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),void(o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{i+=t})),process.stdin.on(\"end\",(e=>{u=i.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return u[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r=0)e-=n[t],n[t]=0;else if(e-n[t]<=0){n[t]-=e;break}o.default.debug(n);let i=\"\";for(let t of r.split(\"\").reverse())n[t]>0&&(n[t]--,i=t+i);o.default.put(i)}))},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a)return u=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),void(o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{i+=t})),process.stdin.on(\"end\",(e=>{u=i.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return u[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r=0)e-=n[t],n[t]=0;else if(e-n[t]<=0){n[t]-=e;break}o.default.debug(n);let i=\"\";for(let t of r.split(\"\").reverse())n[t]>0&&(n[t]--,i=t+i);o.default.put(i)}))},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below: \n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, k] = io.nextNumbers()\n// let s = io.readline()\n// \n// let cnt: any = {}\n// \n// for (let c of s.split(\"\").sort()) {\n// cnt[c] = cnt[c] || 0\n// cnt[c] += 1\n// }\n// \n// for (let x in cnt) {\n// if (k - cnt[x] >= 0) {\n// k -= cnt[x]\n// \n// cnt[x] = 0\n// \n// continue\n// }\n// \n// if (k - cnt[x] <= 0) {\n// cnt[x] -= k\n// break\n// }\n// }\n// \n// io.debug(cnt)\n// \n// let o = \"\"\n// \n// for (let x of s.split(\"\").reverse()) {\n// if (cnt[x] > 0) {\n// cnt[x]--\n// o = x + o\n// }\n// }\n// \n// io.put(o)\n// }\n// \n// // io.runEachTest(main)\n// io.runMain(main)"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar n = nk[0];\nvar k = nk[1];\nvar s = readline().split('');\nvar count = 0;\nfor (var i=97; i<=122; i++){\n\tif (count == k) break;\n\tfor (var j=0; j a != '0').join('');\nprint(s);"}], "negative_code": [{"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a)return u=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),void(o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{i+=t})),process.stdin.on(\"end\",(e=>{u=i.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return u[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r=0)e-=n[t],n[t]=0;else if(e-n[t]<=0){n[t]-=e;break}o.default.debug(n);for(let t of r.split(\"\").reverse())n[t]>0&&(n[t]--,o.default.put(t))}))},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}], "src_uid": "9f095a5f5b39d8c2f99c4162f2d7c5ff"} {"nl": {"description": "Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.", "input_spec": "The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: ", "output_spec": "Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).", "sample_inputs": ["AHA", "Z", "XO"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "positive_code": [{"source_code": "(function main() {\n var line = readline();\n\n var sym = \"AHIMOTUVWXY\";\n\n for (var i = 0; i < line.length; i++){\n \n if (sym.indexOf(line[i]) == -1){\n print(\"NO\");\n return 0;\n }\n\n if (line[i] !== line[line.length - i - 1]){\n print(\"NO\");\n return 0;\n }\n }\n\n print(\"YES\");\n \n return 0;\n})();"}], "negative_code": [], "src_uid": "8135173b23c6b48df11b1d2609b08080"} {"nl": {"description": "The police department of your city has just started its journey. Initially, they don’t 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 (1 ≤ n ≤ 105), 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": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const events = parseInt(readline());\n const values = readline().split(' ').map(x => parseInt(x));\n let availableOfficer = 0 ;\n let crimes = 0 ;\n for (let i = 0 ; i < events ; i++){\n if (values[i] > 0){\n availableOfficer += values[i];\n }else {\n let crime = Math.abs(values[i]);\n let isCrime = availableOfficer - crime\n availableOfficer = (isCrime < 0 ) ? 0 : isCrime\n if (isCrime < 0) crimes += crime;\n }\n }\n console.log(crimes);\n}\n\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet numOfEvents;\nlet events;\nlet crimeCounter = 0;\nlet recruitersCounter = 0;\nrl.on(\"line\", (input) => {\n if (!numOfEvents) {\n numOfEvents = parseInt(input.split(\" \"))\n } else {\n events = input.split(\" \").map(Number)\n events.forEach(element => {\n if (element === -1) {\n if (recruitersCounter > 0) {\n recruitersCounter = recruitersCounter - 1\n }\n else{\n crimeCounter++\n }\n } else {\n recruitersCounter += element\n }\n\n });\n console.log(crimeCounter)\n rl.close()\n }\n})"}, {"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n const x = readline();\n const x2 = readline()\n .split(\" \")\n .map((x) => +x);\n \n policeRecruits(x2);\n}\n\n\nfunction policeRecruits(array) {\n let crimeCount = 0;\n let availableCops = 0;\n\n for (let i = 0; i < array.length; i++) {\n const element = array[i];\n if (element < 0) {\n if (availableCops > 0) {\n availableCops--;\n crimeCount = Math.max(crimeCount, crimeCount - 1);\n } else {\n crimeCount++;\n }\n } else {\n availableCops += element;\n }\n }\n console.log(crimeCount);\n}\n"}, {"source_code": "(function() {\n var n = parseInt(readline());\n var hired = 0, untreated = 0;\n readline().split(' ').forEach(function (v){\n if ( v[0] !== \"-\" ){\n hired += parseInt(v);\n }else{\n if ( hired > 0 ){\n --hired;\n }else{\n ++untreated;\n }\n }\n });\n print(untreated);\n})();"}, {"source_code": "var events = parseInt(readline());\n\nvar order = readline().split(\" \").map(x => parseInt(x));\n\nvar buffer = 0;\nvar crimes = 0;\n\nfor (var i = 0; i < events; i++ ) {\n if (order[i] === -1) {\n if (!buffer) {\n crimes++;\n } else {\n buffer--;\n }\n } else {\n buffer += order[i];\n }\n}\n\nprint(crimes);"}, {"source_code": "if (!this.readline) print = console.log, readline = require('./readline');\n\nfunction readNums() {\n\treturn readline().split(' ').map(Number);\n}\nprint(function(n) {\n\tvar a = readNums();\n\tvar ans = 0;\n\tvar p = 0;\n\tfor (var i = 0; i < n; i++) {\n\t\tif (a[i] === -1) {\n\t\t\tif (p > 0) {\n\t\t\t\tp--;\n\t\t\t} else {\n\t\t\t\tans++;\n\t\t\t}\n\t\t} else {\n\t\t\tp += a[i];\n\t\t}\n\t}\n\treturn ans;\n}(+readline()));"}, {"source_code": "var n = +readline(), events = readline().split(\" \"), sum = 0, police = 0;\n\nevents.forEach(function(a){\n\tif(a == \"-1\" && police == 0){\n\t\tsum++;\n\t}\n\telse if(a == \"-1\" && police > 0){\n\t\tpolice--;\n\t}\n\telse{\n\t\tpolice += +a;\n\t}\n});\n\nwrite(sum);"}, {"source_code": "var n = parseInt(readline());\nvar input = readline().split(' ').map(x=>parseInt(x));\n\nvar crime=0;\nvar officer=0;\nvar temp;\nfor(var i=0 ; i0){\n officer+=input[i];\n }\n else{\n temp = input[i]+ officer;\n if(temp>0){\n officer=temp;\n }\n else{\n crime += temp;\n officer=0;\n } \n }\n}\n\nprint(Math.abs(crime));"}, {"source_code": "var n = parseInt(readline());\nvar input = readline().split(' ').map(x=>parseInt(x));\n\nvar crime=0;\nvar officer=0;\n\nfor(var i=0 ; i0){\n officer+=input[i];\n }\n else{\n officer--;\n if(officer<0){\n officer=0;\n crime++;\n \n }\n }\n}\n\nprint(crime);"}, {"source_code": " var numberOfEvents = readline()\n var events = readline().split(' ').map(Number)\n\n var policeAvailable = 0\n var untreatedEvents = 0\n\n for (var i = 0; i < numberOfEvents; i++) {\n if (events[i] > 0) {\n policeAvailable += events[i]\n } else if (events[i] < 0 && policeAvailable === 0) {\n untreatedEvents += 1\n } else {\n policeAvailable -= 1\n }\n }\n\n print(untreatedEvents)"}, {"source_code": ";(function () {\n\n\tvar n = +readline();\n\tvar s = readline().split(' ').map(Number);\n\tvar x = 0;\n\tvar y = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\n\t\tif (s[i] == -1) {\n\t\t\tif (!x) y++;\n\t\t\telse x--;\n\t\t} else x += s[i];\n\n\t}\n\n\tprint(y);\n\n}).call(this);"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline());\n\tvar data = tokenizeIntegers(readline());\n\tvar police = 0, crimes = 0;\n\tfor (var i = 0; i < n; ++i) {\n\t\tif (data[i] == -1) {\n\t\t\tif (police == 0) {\n\t\t\t\t++crimes;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t--police;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tpolice += data[i];\n\t\t}\n\t}\n\tprint(crimes);\n}\n\nmain();\n"}, {"source_code": "var line = readline();\nvar n = line.split(' ')[0];\nline = readline();\nvar array=line.split(' ');\nvar sum =0;\nvar temp;\nvar solution = 0;\n\nfor(var i = 0 ; i < array.length;i++){\n temp = parseInt(array[i]);\n if(temp < 0){\n if(sum === 0){\n solution++\n }\n else{\n sum--;\n }\n }\n else{\n sum += temp;\n }\n}\n\nprint(solution);"}, {"source_code": "'use strict'\nString.prototype.getNumArray = function () {\n return String(this).split(' ').map(function (value) {\n return parseInt(value);\n });\n}\n\nreadline();\nlet events = readline().getNumArray(),\n crimeCounter = 0,\n availablePolice = 0;\n\nevents.map((event) => {\n if (event === -1) {\n if (availablePolice === 0) {\n crimeCounter++;\n } else {\n availablePolice--;\n }\n } else {\n availablePolice += event;\n }\n});\n\nwrite(crimeCounter);"}, {"source_code": "var totalEvents=readline();\nvar events = readline().split(' ').map(Number);\nvar availablePolice=0;\nvar crimes = 0;\n\nfor(var i=0;i0){\n availablePolice += events[i];\n }else if (events[i]<0 && availablePolice ===0){\n crimes +=1;\n }else{\n availablePolice -=1;\n }\n}\nprint(crimes);"}, {"source_code": "var n = readline(),\n\tnum = readline().split(\" \").map(function(x) {\n return parseInt(x)\n }),\n\tp = 0, c = 0;\nfor (var i = 0; i < n; i++) {\n\tif (num[i] >= 0) {\n\t\tp += num[i];\n } else {\n\t\t(p > 0) ? p-- : c++;\n }\n}\nprint(c);\n"}, {"source_code": "var n = readline();\nvar str = readline().split(\" \");\nvar temp = 0;\nvar res = 0\n\tfor (var i=0; i<+n; i++){\n\t\ttemp+= Number(str[i]);\n\t\tif (temp<0){\n\t\t\tres++;\n\t\t\ttemp=0;\n\t\t\t}\n\t}\nprint(res);"}, {"source_code": "var n = readline();\nvar c = readline().split(' ').map(Number);\nvar person = 0;\nvar crimes = 0;\n\nfor(var i = 0; i < n; i++){\n if(c[i] > 0){\n person += c[i];\n }\n else if(person !== 0){\n person += c[i];\n }\n else {\n crimes ++;\n }\n}\n\nprint(crimes);"}, {"source_code": "var n = parseInt(readline());\nvar answ = 0;\nvar items = readline().split(' ');\nvar police = 0;\nfor( var i = 0; i < items.length; ++i) {\n if (items[i] == '-1' && police == 0) {\n answ++;\n } else {\n police += parseInt(items[i]);\n }\n}\n\nprint(answ);\n\n"}, {"source_code": "var hired = 0, arr, events, numOfCrims = 0;\n \nevents = readline('Enter Num of Events');\narr = readline().split(' ').map(Number);\n \nfor (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n if (hired === 0)\n numOfCrims++;\n else\n hired--;\n }\n else\n hired = hired +arr[i];\n \n}\n \nprint(numOfCrims);"}, {"source_code": "readline();\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = 0, police = 0;\nfor (var i = 0; i < a.length; i++) {\n if (a[i] >= 0) {\n police+= a[i];\n } else {\n if (police > 0) {\n police--;\n } else {\n n++;\n }\n }\n}\nprint(n);"}, {"source_code": "var n=parseInt(readline());\nvar array=readline().split(' ').map(Number);\n\nun=0\nper=0;\n\nfor(var i=0;i0){\n per=per+array[i]\n }else{\n un=un+1;\n }\n }else{\n per=per+array[i]\n }\n}\nprint(un);"}, {"source_code": "readline();\nvar recruits = readline().split(' ').map(Number);\nvar sum=0;\nvar index=0\nfor (i = recruits.length-1; i>=0; i--) {\n if (recruits[i]<0)\n sum+=recruits[i];\n else{\n sum=recruits[i]+sum;\n if(sum>=1)\n sum=0;\n\n }\n\n \n \n}\nprint(Math.abs(sum))"}, {"source_code": "var n = readline();\nvar p = readline().split(\" \");\nvar stack = [];\nvar u = 0;\nvar min = 0;\nvar push = function(n,stack){\n\tif(stack.length != 0)\n\t\tn+=stack.pop();\n\tstack.push(n);\n\tmin = (n < min) ? n : min;\n}\n\nfor (var i = 0; i < p.length; i++)\n\tpush(parseInt(p[i]),stack);\nprint(min*-1);"}, {"source_code": "n=+readline()\nx=0\nprint(readline().split(' ').map(Number).reduce((s,a)=>s+((x=a>0?Math.max(a,x+a):x-1)<0?1:0),0))\n"}, {"source_code": "var n = readline();\n\nvar line = readline().split(' ');\n\nvar police = 0;\nvar crimes = 0;\nvar unsolved = 0;\n\nfor(i=0;i0){\n\tpolice+=parseInt(line[i]);\n } else{\n\tcrimes+=1;\n\tif(crimes>police){\n\t unsolved+=1;\n\t crimes=0;\n\t continue;\n\t}else{\n\t police-=1;\n\t crimes-=1;\n\t}\n }\n}\n\nprint(unsolved);"}, {"source_code": "\"use strict\";\n\nvar main = function() {\n var n = +rd();\n var A = rdAr();\n \n wr(A.reduce((a, v) => [Math.max(0, a[0] + v), a[1] + (v === -1 && a[0] <= 0)], [0, 0])[1]);\n};\n\nvar rd = readline;\nvar wr = write;\nvar pr = print;\nvar rdAr = () => rd().split(' ').map(v => +v);\nvar cmpLt = (a, b) => a - b;\nvar cmpGt = (a, b) => b - a;\n\nmain();"}, {"source_code": "readline()\nT=readline().split(' ').map(Number)\nprint(T.reduce((a,c) => {\n if (c > 0) {\n a.p += c;\n } else {\n if (a.p) {\n a.p--;\n } else {\n a.a++;\n }\n }\n return a;\n}, { a: 0, p: 0 }).a)\n"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction main() {\n const events_count = parseInt(readline(), 10);\n const events = readline().trim().split(' ').map(string => parseInt(string, 10));\n var crimes_untreated = 0;\n var free_police_forces = 0;\n\n events.forEach(event => {\n if (event === -1) {\n if (free_police_forces > 0) {\n free_police_forces--;\n } else {\n crimes_untreated++;\n }\n } else {\n free_police_forces += event;\n }\n });\n\n print(crimes_untreated);\n}\n\nmain();"}, {"source_code": "(function (){\n var Ret = 0;\n var K = 0;\n var C = readline();\n var Arr = readline().split(\" \");\n for (var i in Arr) {\n var N = parseInt(Arr[i]);\n //console.log(i,N);\n if (N > 0) {\n K += N;\n } else {\n if (K > 0) {\n K--;\n } else {\n Ret++;\n }\n }\n }\n print(Ret);\n})();"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var list = nextIntArray();\n var ok = 0;\n var ng = 0;\n for(var i = 0; i < N; i++){\n if(list[i] > 0){\n ok += list[i];\n }else{\n if(ok > 0){\n ok--;\n }else{\n ng++;\n }\n }\n }\n myout(ng);\n}\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet counter = 0;\n\nrl.on('line', (input) => {\n if (counter++ === 0) return;\n let line = input.split(' ');\n let inputs = [];\n line.forEach(element => {\n inputs.push(parseInt(element));\n });\n rl.close();\n console.log(solve(inputs));\n});\n\n\nconst solve = (inputs) => {\n let currentHired = 0,\n unsolved = 0;\n inputs.forEach(element => {\n if (element === -1 && currentHired === 0) unsolved++;\n else if (element === -1 && currentHired !== 0) currentHired--;\n else currentHired += element;\n });\n return unsolved;\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n const n = readline();\n let l = readline().split(' ').map(x => parseInt(x));\n let result = 0;\n let sum = 0;\n for (let i = 0; i < n; i++) {\n sum += l[i];\n if (sum < 0) {\n result++;\n sum = 0;\n }\n }\n // output\n print(result);\n}\n\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let ans = 0;\n let cops = 0;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n cops += arr[i];\n }\n else {\n if (cops === 0) {\n ans++;\n }\n else {\n cops = Math.max(0, --cops);\n }\n }\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "const input = [];\n \nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n \nRL.on('line', (line) => {\n input.push(line);\n});\n\nRL.on('close', () => {\n const nums = input[1].split(' ').map(x => parseInt(x));\n let answ = 0; let cops = 0;\n\n nums.forEach(x => {\n if (x >= 0) cops += x;\n else {\n if (cops + x < 0) answ += 1;\n else cops += x;\n }\n });\n\n console.log(answ);\n});"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet hired=0\n\tlet untreated=0\n\tlet x=+readLine()\n\tlet order=readLine().split(\" \").map(n=>+n)/* +ve int*/\n\tfor(let i=0;i Number(num));\n\n for (i = 0; i < test; i++) {\n\n if (cases[i] > 0) {\n positive += cases[i];\n }\n else if (positive > 0) {\n positive--;\n }\n else {\n untreatedCrime++;\n }\n\n }\n return untreatedCrime.toString();\n\n}\n\n\n\n\n\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let arr = readLine().split(' ').map(v => parseInt(v));\n let current = 0;\n let ans = 0;\n for (var i = 0; i < n; i++) {\n current += arr[i];\n if (current < 0) {\n ans++;\n current = 0;\n }\n }\n console.log(ans);\n}"}], "negative_code": [{"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet numOfEvents;\nlet events;\nlet crimeCounter = 0;\nlet recruitersCounter = 0;\nrl.on(\"line\", (input) => {\n if (!numOfEvents) {\n numOfEvents = parseInt(input.split(\" \"))\n } else {\n events = input.split(\" \").map(Number)\n events.forEach(element => {\n if (element === -1) {\n crimeCounter++\n } else {\n recruitersCounter += element\n }\n if (crimeCounter <= recruitersCounter) {\n recruitersCounter = recruitersCounter - crimeCounter \n crimeCounter = 0\n }\n });\n console.log(crimeCounter)\n rl.close()\n }\n})"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet numOfEvents;\nlet events;\nlet crimeCounter = 0;\nlet recruitersCounter = 0;\nrl.on(\"line\", (input) => {\n if (!numOfEvents) {\n numOfEvents = parseInt(input.split(\" \"))\n } else {\n events = input.split(\" \").map(Number)\n events.forEach(element => {\n if (crimeCounter <= recruitersCounter) {\n recruitersCounter = recruitersCounter - crimeCounter \n crimeCounter = 0\n }\n if (element === -1) {\n crimeCounter++\n } else {\n recruitersCounter += element\n }\n \n });\n console.log(crimeCounter)\n rl.close()\n }\n})"}, {"source_code": "(function() {\n var n = parseInt(readline());\n var hired = 0, untreated = 0;\n readline().split(' ').forEach(function (v){\n if ( v[0] === \"1\" ){\n ++hired;\n }else{\n if ( hired > 0 ){\n --hired;\n }else{\n ++untreated;\n }\n }\n });\n print(untreated);\n})();"}, {"source_code": "var hired = 0, arr, events, numOfCrims = 0;\n\nevents = readline('Enter Num of Events');\narr = readline().split(' ').map(Number);\n\nfor (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n if (hired === 0)\n numOfCrims++;\n else\n hired--;\n }\n else\n hired = arr[i];\n\n}\n\nprint(numOfCrims);"}, {"source_code": "readline();\nvar recruits = readline().split(' ').map(Number);\nvar sum=0;\nvar index=0\nfor (i = recruits.length-1; i>=0; i--) {\n if (recruits[i]<0)\n sum+=recruits[i];\n else{\n sum=recruits[i]+sum;\n if(sum>=1)\n sum=0;\n\n }\n print(Math.abs(sum))\n \n \n}\nprint(Math.abs(sum))\n"}, {"source_code": "n=+readline()\nx=0\nprint(readline().split(' ').map(Number).reduce((s,a)=>s+((x=a>0?a:x-1)<0?1:0),0))\n"}, {"source_code": "var n = readline();\n\nvar line = readline().split(' ');\n\nvar police = 0;\nvar crimes = 0;\nvar unsolved = 0;\n\nfor(i=0;i0){\n\tpolice+=1;\n } else{\n\tcrimes+=1;\n\tif(crimes>police){\n\t unsolved+=1;\n\t crimes=0;\n\t continue;\n\t}else{\n\t police-=1;\n\t crimes-=1;\n\t}\n }\n}\n\nprint(unsolved);"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction main() {\n const events_count = parseInt(readline(), 10);\n const events = readline().trim().split(' ').map(string => {\n return parseInt(string, 10);\n });\n var crimes_untreated = 0;\n var free_police_forces = 0;\n\n events.forEach(event => {\n if (event === -1) {\n if (free_police_forces > 0) {\n free_police_forces--;\n } else {\n crimes_untreated++;\n }\n } else {\n free_police_forces += event;\n }\n });\n\n print(crimes_untreated);\n}"}, {"source_code": "(function() {\n var n = parseInt(readline());\n var hired = 0, untreated = 0;\n readline().split(' ').forEach(function (v){\n if ( v[0] == '1' ){\n ++hired;\n }else{\n if ( hired > 0 ){\n --hired;\n }else{\n ++untreated;\n }\n } \n });\n print(untreated);\n})();"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let ans = 0;\n let cops = 0;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === 1) {\n cops++;\n }\n else {\n if (cops === 0) {\n ans++;\n }\n else {\n cops = Math.max(0, --cops);\n }\n }\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "// Sample code to perform I/O:\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n main(stdin_input);\n});\n\nfunction main(input) {\n let output = nameLookUp(input);\n process.stdout.write(output); // Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\n// Write your code here\nfunction nameLookUp(str) {\n\n let inputs = str.trim().split('\\n');\n let untreatedCrime = 0;\n let cases = inputs[1].split(' ');\n for (let index = 0; index < cases.length - 1; index++) {\n const element = cases[index];\n if (cases[index] < 0) {\n untreatedCrime++;\n if ((index - 1) >= 0 && cases[index - 1] > 0) {\n untreatedCrime -= 1;\n }\n\n }\n\n }\n return untreatedCrime.toString();\n\n}\n\n\n\n\n\n"}, {"source_code": "// Sample code to perform I/O:\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n main(stdin_input);\n});\n\nfunction main(input) {\n let output = nameLookUp(input);\n process.stdout.write(output); // Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\n// Write your code here\nfunction nameLookUp(str) {\n\n let inputs = str.trim().split('\\n');\n let positive = 0;\n let untreatedCrime = 0;\n let cases = inputs[1].split(' ');\n for (let index = 0; index < cases.length; index++) {\n const element = cases[index];\n if (cases[index] < 0) {\n untreatedCrime++;\n if (positive > 0) {\n untreatedCrime -= positive;\n positive = 0;\n }\n }\n else {\n positive += +cases[index];\n }\n\n }\n return untreatedCrime.toString();\n\n}\n\n\n\n\n\n"}], "src_uid": "af47635f631381b4578ba599a4f8b317"} {"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 > 1. 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 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), 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": "(function () {\n\tvar n = parseInt(readline());\n\tvar line = readline().split(' ');\n\tvar m = {};\n\tvar prefix = 0;\n\tvar ans = n - 1;\n\t//print(n);\n\tfor(var idx in line){\n\t\tprefix += parseInt(line[idx]);\n\t\t//print(prefix);\n\t\tif(!m[''+prefix]) {\n\t\t\tm[''+prefix] = 1;\n\t\t} else {\n\t\t\t++m[''+prefix];\n\t\t}\n\t\tans = n - m[''+prefix] > ans? ans: n - m[''+prefix];\n\t}\n\tprint(ans);\n})();"}, {"source_code": "(function () {\n\tvar n = parseInt(readline());\n\tvar line = readline().split(' ');\n\tvar m = {};\n\tvar prefix = 0;\n\tvar ans = n - 1;\n\t//print(n);\n\tfor(var idx in line){\n\t\tprefix += parseInt(line[idx]);\n\t\t//print(prefix);\n\t\tif(!m[prefix]) {\n\t\t\tm[prefix] = 1;\n\t\t} else {\n\t\t\t++m[prefix];\n\t\t}\n\t\tans = n - m[prefix] > ans? ans: n - m[prefix];\n\t}\n\tprint(ans);\n})();"}], "negative_code": [], "src_uid": "be12bb8148708f9ad3dc33b83b55eb1e"} {"nl": {"description": "Gianni, SWERC's chief judge, received a huge amount of high quality problems from the judges and now he has to choose a problem set for SWERC.He received $$$n$$$ problems and he assigned a beauty score and a difficulty to each of them. The $$$i$$$-th problem has beauty score equal to $$$b_i$$$ and difficulty equal to $$$d_i$$$. The beauty and the difficulty are integers between $$$1$$$ and $$$10$$$. If there are no problems with a certain difficulty (the possible difficulties are $$$1,2,\\dots,10$$$) then Gianni will ask for more problems to the judges.Otherwise, for each difficulty between $$$1$$$ and $$$10$$$, he will put in the problem set one of the most beautiful problems with such difficulty (so the problem set will contain exactly $$$10$$$ problems with distinct difficulties). You shall compute the total beauty of the problem set, that is the sum of the beauty scores of the problems chosen by Gianni.", "input_spec": "Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\le t\\le 100$$$) — the number of test cases. The descriptions of the $$$t$$$ test cases follow. The first line of each test case contains the integer $$$n$$$ ($$$1\\le n\\le 100$$$) — how many problems Gianni received from the judges. The next $$$n$$$ lines contain two integers each. The $$$i$$$-th of such lines contains $$$b_i$$$ and $$$d_i$$$ ($$$1\\le b_i, d_i\\le 10$$$) — the beauty score and the difficulty of the $$$i$$$-th problem.", "output_spec": "For each test case, print the total beauty of the problem set chosen by Gianni. If Gianni cannot create a problem set (because there are no problems with a certain difficulty) print the string MOREPROBLEMS (all letters are uppercase, there are no spaces).", "sample_inputs": ["2\n\n3\n\n8 4\n\n9 3\n\n6 7\n\n12\n\n3 10\n\n10 1\n\n10 2\n\n10 3\n\n10 4\n\n3 10\n\n10 5\n\n10 6\n\n10 7\n\n10 8\n\n10 9\n\n1 10"], "sample_outputs": ["MOREPROBLEMS\n93"], "notes": "NoteIn the first test case, Gianni has received only $$$3$$$ problems, with difficulties $$$3, 4, 7$$$ which are not sufficient to create a problem set (for example because there is not a problem with difficulty $$$1$$$).In the second test case, Gianni will create a problem set by taking the problems $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$9$$$, $$$10$$$, $$$11$$$ (which have beauty equal to $$$10$$$ and all difficulties from $$$1$$$ to $$$9$$$) and one of the problems $$$1$$$ and $$$6$$$ (which have both beauty $$$3$$$ and difficulty $$$10$$$). The total beauty of the resulting problem set is $$$10\\cdot 9 + 3 = 93$$$."}, "positive_code": [{"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n let cnt=0;\r\n for(let _=1;_<=t;_++)\r\n {\r\n let n=parseInt(line[++cnt]);\r\n let a=new Array(11);\r\n for(let i=0;i<=10;i++) a[i]=0;\r\n for(let i=1;i<=n;i++)\r\n {\r\n let [x,y]=line[++cnt].split(' ').map(x=>{return parseInt(x)});\r\n a[y]=Math.max(a[y],x);\r\n }\r\n let ans=0;\r\n flag=false;\r\n for(let i=1;i<=10;i++)\r\n {\r\n if(!a[i]) flag=true;\r\n ans+=a[i];\r\n }\r\n if(flag) console.log('MOREPROBLEMS');\r\n else console.log(ans);\r\n }\r\n})"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n let cnt=0;\r\n for(let _=1;_<=t;_++)\r\n {\r\n let n=parseInt(line[++cnt]);\r\n let a=new Array(11);\r\n for(let i=0;i<=10;i++) a[i]=0;\r\n for(let i=1;i<=n;i++)\r\n {\r\n let [x,y]=line[++cnt].split(' ').map(x=>{return parseInt(x)});\r\n // console.log('z->',x,y);\r\n a[y]=Math.max(a[y],x);\r\n }\r\n // for(let i=1;i<=n;i++) console.log(a[i]);\r\n let ans=0;\r\n flag=false;\r\n for(let i=1;i<=10;i++)\r\n {\r\n if(!a[i]) flag=true;\r\n ans+=a[i];\r\n }\r\n if(flag) console.log('MOREPROBLEMS');\r\n else console.log(ans);\r\n }\r\n})"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n const res = new Array(11).fill(-1);\r\n for (let [b, d] of a) {\r\n res[d] = Math.max(res[d], b);\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < 11; i++) {\r\n if (res[i] === -1) {\r\n console.log('MOREPROBLEMS');\r\n return;\r\n }\r\n sum += res[i];\r\n }\r\n console.log(sum);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = [];\r\n let tmp = n;\r\n while (tmp--) {\r\n a.push((await read()).split(' ').map(Number));\r\n }\r\n solve(n, a);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "negative_code": [], "src_uid": "98beefa4cb73ccbf9575a6cfe73f4fff"} {"nl": {"description": "$$$n$$$ people gathered to hold a jury meeting of the upcoming competition, the $$$i$$$-th member of the jury came up with $$$a_i$$$ tasks, which they want to share with each other.First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$ (an array of size $$$n$$$ where each integer from $$$1$$$ to $$$n$$$ occurs exactly once).Then the discussion goes as follows: If a jury member $$$p_1$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If a jury member $$$p_2$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. ... If a jury member $$$p_n$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation $$$p$$$ is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo $$$998\\,244\\,353$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) — number of jury members. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) — the number of problems that the $$$i$$$-th member of the jury came up with. The sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print one integer — the number of nice permutations, taken modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["4\n2\n1 2\n3\n5 5 5\n4\n1 3 3 7\n6\n3 4 2 1 3 3"], "sample_outputs": ["1\n6\n0\n540"], "notes": "NoteExplanation of the first test case from the example:There are two possible permutations, $$$p = [1, 2]$$$ and $$$p = [2, 1]$$$. For $$$p = [1, 2]$$$, the process is the following: the first jury member tells a task; the second jury member tells a task; the first jury member doesn't have any tasks left to tell, so they are skipped; the second jury member tells a task. So, the second jury member has told two tasks in a row (in succession), so the permutation is not nice.For $$$p = [2, 1]$$$, the process is the following: the second jury member tells a task; the first jury member tells a task; the second jury member tells a task. So, this permutation is nice."}, "positive_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst MOD = 998244353;\r\n\r\nconst B = n => BigInt(n);\r\nconst N = n => Number(n);\r\n\r\nfunction fact (n) {\r\n\tlet res = 1;\r\n\tfor (let i = 1; i <= n; i++) res = res * i % MOD;\r\n\treturn res;\r\n}\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\ta.sort((x, y) => x - y);\r\n\r\n\t\tlet ans = 0;\r\n\t\tif (a[n-1] - a[n-2] == 0) { \r\n\t\t\tans = fact(n);\r\n\t\t}\r\n\t\tif (a[n-1] - a[n-2] == 1) {\r\n\t\t\tlet cnt = 0;\r\n\t\t\tfor (let i = 0; i < n; i++) cnt += a[i] == a[n-2];\r\n\t\t\tlet ways = 1;\r\n\t\t\tlet juries = n - (cnt + 1);\r\n\t\t\tlet spots = 1 + (cnt + 1);\r\n\t\t\twhile (juries--) {\r\n\t\t\t\tways = ways * spots % MOD, spots++;\r\n\t\t\t}\r\n\t\t\tans = fact(n) - N(B(fact(cnt)) * B(ways) % B(MOD));\r\n\t\t\tans = (MOD + ans) % MOD;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n console.log(solve(n, arr))\n }\n// })()\n})\n\nfunction solve(n, arr) {\n const gs = arr.reduce((o, x) => {\n o[x] = (o[x] || 0) + 1\n return o\n }, {})\n const sorted = Object.keys(gs).map(Number)\n .sort((a, b) => b - a)\n// console.log(gs, sorted)\n const all = fac(n)\n if (sorted.length < 2) return all\n\n const a = sorted[0]\n const b = sorted[1]\n if (gs[a] > 1) return all\n if (a > b + 1) return 0\n\n let ca = gs[a]\n let cb = gs[b]\n let cc = n - ca - cb\n\n let invalid = mul(fac(ca), fac(cb))\n for (let i = 1; i <= cc; i++) {\n invalid = mul(invalid, ca + cb + i)\n }\n let ans = add(all, -invalid)\n return add(ans, 998244353)\n}\n\nfunction add(a, b) {\n return (a + b) % 998244353\n}\nfunction mul(a, b) {\n const str = b.toString(2)\n let r = 0\n let base = a\n for (let i = str.length - 1; i >= 0; i--) {\n if (str[i] === '1') {\n r = add(r, base)\n }\n base = add(base, base)\n }\n return r\n}\nfunction fac(n) {\n let ans = 1\n for (let i = 2; i <= n; i++) {\n ans = mul(ans, i)\n }\n return ans\n}\n"}], "negative_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst MOD = 998244353;\r\n\r\nconst B = n => BigInt(n);\r\nconst N = n => Number(n);\r\n\r\nfunction fact (n) {\r\n\tlet res = 1;\r\n\tfor (let i = 1; i <= n; i++) res = res * i % MOD;\r\n\treturn res;\r\n}\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\ta.sort((x, y) => x - y);\r\n\r\n\t\tlet ans = 0;\r\n\t\tif (a[n-1] - a[n-2] == 0) { \r\n\t\t\tans = fact(n);\r\n\t\t}\r\n\t\tif (a[n-1] - a[n-2] == 1) {\r\n\t\t\tlet cnt = 0;\r\n\t\t\tfor (let i = 0; i < n; i++) cnt += a[i] == a[n-2];\r\n\t\t\tlet ways = 1;\r\n\t\t\tlet juries = n - (cnt + 1);\r\n\t\t\tlet spots = 1 + (cnt + 1);\r\n\t\t\twhile (juries--) {\r\n\t\t\t\tways = ways * spots % MOD, spots++;\r\n\t\t\t}\r\n\t\t\tans = fact(n) - N(B(fact(cnt)) * B(ways) % B(MOD));\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst MOD = 998244353;\r\n\r\nfunction fact (n) {\r\n\tlet ans = 1;\r\n\tfor (let i = 1; i <= n; i++) \r\n\t\tans = ans * i % MOD;\r\n\treturn ans;\r\n}\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rn();\r\n\t\tlet a = rna();\r\n\r\n\t\ta.sort((x, y) => y - x);\r\n\r\n\t\tlet ans = 2;\r\n\t\tif (a[0] - a[1] == 0) ans = fact(n);\r\n\t\tif (a[0] - a[1] == 1) {\r\n\r\n\t\t\tlet k = 0;\r\n\t\t\tfor (const vl of a) {\r\n\t\t\t\tk += vl == a[1];\r\n\t\t\t}\r\n\r\n\t\t\tfor (let x = n - 1; x >= k; x--) {\r\n\t\t\t\tlet prd = 1;\r\n\t\t\t\tfor (let i = 0; i < k; i++) {\r\n\t\t\t\t\tprd = prd * (x - i) % MOD;\r\n\t\t\t\t}\r\n\t\t\t\tans += prd * fact(n-k-1);\r\n\t\t\t\tans %= MOD;\r\n\t\t\t}\r\n\t\t\tans = (fact(n) - ans + MOD) % MOD;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n \r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst MOD = 998244353;\r\n\r\nfunction fact (n) {\r\n\tlet ans = 1;\r\n\twhile (n) ans = (ans * n--) % MOD;\r\n\treturn ans;\r\n}\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rn();\r\n\t\tlet a = rna();\r\n\r\n\t\ta.sort((x, y) => x - y);\r\n\r\n\t\tlet k = 0;\r\n\t\tfor (const x of a) k += x == a[n-2];\r\n\r\n\t\tlet ans = 0;\r\n\t\tif (a[n-1] == a[n-2]) ans = fact(n);\r\n\t\tif (a[n-1] == a[n-2] + 1) {\r\n\t\t\tlet x = n - 1;\r\n\t\t\twhile (x >= k) {\r\n\t\t\t\tlet prd = 1;\r\n\t\t\t\tfor (let j = 0; j < k; j++) {\r\n\t\t\t\t\tprd = prd * (x - j) % MOD;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tans = (ans + prd * fact(n-k-1)) % MOD;\r\n\t\t\t\tx--;\r\n\t\t\t}\r\n\t\t\tans = (fact(n) - ans) % MOD;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n \r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst MOD = 998244353;\r\n\r\nfunction fact (n) {\r\n\tlet ans = 1;\r\n\twhile (n) ans = (ans * n--) % MOD;\r\n\treturn ans;\r\n}\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rn();\r\n\t\tlet a = rna();\r\n\r\n\t\ta.sort((x, y) => x - y);\r\n\r\n\t\tlet k = 0;\r\n\t\tfor (const x of a) k += x == a[n-2];\r\n\r\n\t\tlet ans = 0;\r\n\t\tif (a[n-1] == a[n-2]) ans = fact(n);\r\n\t\tif (a[n-1] == a[n-2] + 1) {\r\n\t\t\tlet x = n - 1;\r\n\t\t\twhile (x >= k) {\r\n\t\t\t\tans = (ans + fact(x)/fact(x-k) * fact(n-k-1)) % MOD;\r\n\t\t\t\tx--;\r\n\t\t\t}\r\n\t\t\tans = (fact(n) - ans) % MOD;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n \r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst MOD = 998244353;\r\n\r\nfunction fact (n) {\r\n\tlet ans = 1;\r\n\twhile (n) ans = (ans * n--) % MOD;\r\n\treturn ans;\r\n}\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rn();\r\n\t\tlet a = rna();\r\n\r\n\t\ta.sort((x, y) => x - y);\r\n\r\n\t\tlet cnt = 0;\r\n\t\tfor (const x of a) cnt += x == a[n-2];\r\n\r\n\t\tlet ans = 0;\r\n\t\tif (a[n-1] == a[n-2]) ans = fact(n);\r\n\t\tif (a[n-1] == a[n-2] + 1) ans = fact(n) * cnt / (cnt + 1) % MOD;\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n console.log(solve(n, arr))\n }\n// })()\n})\n\nfunction solve(n, arr) {\n const gs = arr.reduce((o, x) => {\n o[x] = (o[x] || 0) + 1\n return o\n }, {})\n const sorted = Object.keys(gs).map(Number)\n .sort((a, b) => b - a)\n\n const all = fac(n)\n if (sorted.length < 2) return all\n\n const a = sorted[0]\n const b = sorted[1]\n if (a > b + 1) return 0\n\n let ca = gs[a]\n let cb = gs[b]\n let cc = n - ca - cb\n\n let invalid = mul(fac(ca), fac(cb))\n for (let i = 1; i <= cc; i++) {\n invalid = mul(invalid, ca + cb + i)\n }\n let ans = add(all, -invalid)\n return add(ans, 998244353)\n}\n\nfunction add(a, b) {\n return (a + b) % 998244353\n}\nfunction mul(a, b) {\n const str = b.toString(2)\n let r = 0\n let base = a\n for (let i = str.length - 1; i >= 0; i--) {\n if (str[i] === '1') {\n r = add(r, base)\n }\n base = add(base, base)\n }\n return r\n}\nfunction fac(n) {\n let ans = 1\n for (let i = 2; i <= n; i++) {\n ans = mul(ans, i)\n }\n return ans\n}\n"}], "src_uid": "81d4867a7e5128baf316193e9cc3dfce"} {"nl": {"description": "Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a \"+=\" operation that adds the right-hand side value to the left-hand side variable. For example, performing \"a += b\" when a = $$$2$$$, b = $$$3$$$ changes the value of a to $$$5$$$ (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations \"a += b\" or \"b += a\". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $$$n$$$. What is the smallest number of operations he has to perform?", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\leq T \\leq 100$$$) — the number of test cases. Each of the following $$$T$$$ lines describes a single test case, and contains three integers $$$a, b, n$$$ ($$$1 \\leq a, b \\leq n \\leq 10^9$$$) — initial values of a and b, and the value one of the variables has to exceed, respectively.", "output_spec": "For each test case print a single integer — the smallest number of operations needed. Separate answers with line breaks.", "sample_inputs": ["2\n1 2 3\n5 4 100"], "sample_outputs": ["2\n7"], "notes": "NoteIn the first case we cannot make a variable exceed $$$3$$$ in one operation. One way of achieving this in two operations is to perform \"b += a\" twice."}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let [a, b, target] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n let count = 0;\n let i = 0;\n while (a <= target || b <= target) {\n if (a > b) {\n b += a;\n } else {\n a += b;\n }\n count++;\n i++;\n }\n console.log(count - 1);\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n \tvar input = nextIntArray();\n \tvar N = input[2];\n \tvar min = Math.min(input[0], input[1]);\n \tvar max = Math.max(input[0], input[1]);\n \tvar count = 0;\n \twhile(N >= max){\n \t\tmin += max;\n \t\tvar tmp = max;\n \t\tmax = min;\n \t\tmin = tmp;\n \t\tcount++;\n \t}\n \toutput[i] = count;\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n})\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n})\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 1;\n let i = 1;\n while (i <= testCases) {\n const int = data[i].split(' ');\n let a = int[0] * 1;\n let b = int[1] * 1;\n const n = int[2] * 1;\n let count = 0;\n while (true) {\n if (a > n || b > n) {\n console.log(count);\n break;\n }\n a > b ? b += a : a += b;\n count += 1;\n }\n i += 1;\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nvar input = '';\nprocess.stdin.on('data', function (line) {\n input += line;\n});\nprocess.stdin.on('end', function () {\n var _a, _b;\n var lines = input.split('\\n');\n var tests = parseInt(lines.shift(), 10);\n while (tests--) {\n var a = void 0, b = void 0, n = void 0;\n _a = lineToNumArray(lines.shift()), a = _a[0], b = _a[1], n = _a[2];\n var steps = 0;\n while (Math.max(a, b) <= n) {\n _b = [a + b, Math.max(a, b)], a = _b[0], b = _b[1];\n steps++;\n }\n console.log(steps);\n }\n});\n// input helper\nfunction lineToNumArray(line) {\n return line.split(' ').map(function (element) { return parseInt(element, 10); });\n}\n"}, {"source_code": "const process = require('process')\nlet input = ''\nprocess.stdin.on('data', data => input += data)\nprocess.stdin.on('end', () => main(input))\n\nfunction main(input) {\n let lines = input.trim().split('\\n')\n let n = +lines[0]\n for(let i = 0; i < n; i++) {\n let [a, b, n] = lines[1 + i].split(' ')\n console.log(solution(+a, +b, +n))\n }\n}\n\nfunction solution(a, b, n) {\n if (a < b) return solution(b, a, n)\n // a >= b\n let i = 0\n for (; a <= n; i++) {\n let c = a + b\n b = a\n a = c\n }\n return i\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => string.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nconst s2i = s => parseInt(s, 10);\n\nfunction main() {\n const T = s2i(readLine());\n for(let i = 0; i < T; i++) {\n let [a, b, n] = readLine().split(' ').map(s2i);\n\n if (a > b) [a, b] = [b, a];\n\n let ops = 0;\n\n while (b <= n) {\n [a, b] = [b, a + b];\n ops++;\n }\n\n console.log(ops);\n }\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n3 4\n##..\n##..\n...#\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n // let n = Number(readline());\n\n // let string = 'codeforces';\n\n // let s = 's'.repeat(BigInt.asIntN(n-1));\n\n // console.log(string + s);\n \n let n = parseInt(readline());\n\n for(let i=0;i parseInt(val));\n var a = inp[0],\n b = inp[1],\n n = inp[2];\n var count = 0;\n while (Math.max(a, b) <= n) {\n if (a < b) {\n var temp = a;\n a = b;\n b = temp;\n }\n b += a;\n count++;\n }\n print(count);\n}\n"}, {"source_code": "\"use strict\";\n\n//readline().split(' ').map(Number);\n\nfunction sec(){\n var arr = readline().split(' ').map(Number);\n var a = Math.min(arr[0],arr[1]);\n var b = Math.max(arr[0],arr[1]);\n var aa = 1, bb = 1;\n var c = 1;\n while(aa * a + bb * b <= arr[2]){\n c++;\n bb = aa+bb;\n aa = bb-aa;\n }\n print(c);\n}\n\n\n\nfunction main(){\n var t = readline();\n while(t--){\n sec();\n }\n}\n\nmain();"}, {"source_code": "function solve() {\n var T = Number(read());\n for (var t = 0; t < T; ++t) {\n var abn = read().split(' ').map(Number);\n var a = abn[0], b = abn[1], n = abn[2];\n var count = 0;\n while (a <= n && b <= n) {\n if (a < b) {\n a += b;\n } else {\n b += a;\n }\n count++;\n }\n write(count);\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n \n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n \n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n solve();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', solve);\n }\n} else {\n solve();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}, {"source_code": "var count = +readline();\n \nfor(var index = 0; index < count; ++index) {\n var content = readline()\n var content = content.split(' ');\n var a = +content[0];\n var b = +content[1];\n var n = +content[2];\n \n var rounds = 0;\n \n if(a > n || b > n) {\n print(\"0\");\n } else {\n while(a <= n && b <= n) {\n ++rounds;\n \n if(a + b > n) {\n a += b; \n } else {\n if(a < b) {\n a += b;\n } else {\n b += a;\n }\n }\n }\n }\n \n print('' + rounds + '\\n');\n}"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nconst s2i = s => parseInt(s, 10);\n\nfunction main() {\n const T = s2i(readLine());\n for(let i = 0; i < T; i++) {\n let [a, b, n] = readLine().split(' ').map(s2i);\n\n if (a < b) {\n const temp = a;\n a = b;\n b = temp;\n }\n\n let ops = 0;\n\n while (b <= n) {\n ops++;\n const sum = a + b;\n a = b;\n b = sum;\n }\n\n console.log(ops);\n }\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n3 4\n##..\n##..\n...#\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n // let n = Number(readline());\n\n // let string = 'codeforces';\n\n // let s = 's'.repeat(BigInt.asIntN(n-1));\n\n // console.log(string + s);\n \n let n = parseInt(readline());\n\n for(let i=0;i {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n // let n = Number(readline());\n\n // let string = 'codeforces';\n\n // let s = 's'.repeat(BigInt.asIntN(n-1));\n\n // console.log(string + s);\n \n let n = parseInt(readline());\n\n for(let i=0;i b) {\n b = sum;\n } else {\n a = sum;\n }\n\n count++;\n }\n\n console.log(count - 1);\n}\n\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n // let n = Number(readline());\n\n // let string = 'codeforces';\n\n // let s = 's'.repeat(BigInt.asIntN(n-1));\n\n // console.log(string + s);\n \n let n = parseInt(readline());\n\n for(let i=0;i b) {\n b = sum;\n } else {\n a = sum;\n }\n\n count++;\n }\n\n console.log(count);\n}\n\n"}, {"source_code": "var count = +readline();\n \nfor(var index = 0; index < count; ++index) {\nvar content = readline()\nvar content = content.split(' ');\nvar a = +content[0];\nvar b = +content[1];\nvar n = +content[2];\n \nvar rounds = 0;\n \nif(a > n || b > n) {\n print(\"0\");\n} else {\n while(a < n && b < n) {\n ++rounds;\n \n if(a + b > n) {\n a += b; \n } else {\n if(a < b) {\n a += b;\n } else {\n b += a;\n }\n }\n }\n}\n \nprint('' + rounds + '\\n');\n}"}, {"source_code": "var content = readline()\nvar content = content.split(' ');\nvar a = +content[0];\nvar b = +content[1];\nvar n = +content[2];\n\nvar rounds = 0;\n\nif(a > n || b > n) {\n print(\"0\");\n} else {\n while(a < n && b < n) {\n ++round;\n \n if(a + b > n) {\n a += b; \n } else {\n if(a < b) {\n a += b;\n } else {\n b += a;\n }\n }\n }\n}\n\nprint('' + rounds);"}], "src_uid": "5999a4e2fac29b5f4804639f6e949279"} {"nl": {"description": "You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones. You can do the following operation: choose two indices $$$1 \\le i , j \\le n$$$, $$$i \\ne j$$$, add $$$a_{i}$$$ to $$$a_{j}$$$, remove $$$a_{i}$$$ from $$$a$$$. Note that elements of $$$a$$$ can become bigger than $$$1$$$ after performing some operations. Also note that $$$n$$$ becomes $$$1$$$ less after the operation.What is the minimum number of operations needed to make $$$a$$$ non-decreasing, i. e. that each element is not less than the previous element?", "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 description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), the size of array $$$a$$$. Next line contains $$$n$$$ integers $$$a_{1}, a_{2}, \\ldots a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$. It's guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print a single integer, minimum number of operations needed to make $$$a$$$ non-decreasing.", "sample_inputs": ["4\n\n8\n\n0 0 1 1 1 1 1 1\n\n5\n\n1 0 0 1 1\n\n2\n\n1 0\n\n11\n\n1 1 0 0 1 0 0 1 1 1 0"], "sample_outputs": ["0\n1\n1\n3"], "notes": "NoteIn the first test case, $$$a$$$ is already non-decreasing, so you don't need to do any operations and the answer is $$$0$$$.In the second test case, you can perform an operation for $$$i = 1$$$ and $$$j = 5$$$, so $$$a$$$ will be equal to $$$[0, 0, 1, 2]$$$ and it becomes non-decreasing.In the third test case, you can perform an operation for $$$i = 2$$$ and $$$j = 1$$$, so $$$a$$$ will be equal to $$$[1]$$$ and it becomes non-decreasing."}, "positive_code": [{"source_code": "var n = parseInt(readline());\r\n\r\nfor (var i = 0; i < n; i++){\r\n var counter = 0;\r\n\r\n var k = parseInt(readline());\r\n var arr = readline().split(\" \");\r\n\r\n var bolo = k - 1;\r\n var starti = 0;\r\n \r\n for(var j = 1; j < k; j++){\r\n if(arr[j - 1] > arr[j]){\r\n while (arr[bolo] == 1){\r\n bolo--;\r\n }\r\n while(arr[starti] == 0){\r\n starti++;\r\n }\r\n arr[starti] = 0;\r\n arr[bolo] = 1\r\n j = starti + 1;\r\n k = bolo;\r\n counter++;\r\n }\r\n }\r\n print(counter);\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => {\r\n return string.trim();\r\n });\r\n solve();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve() {\r\n var t = readline();\r\n for (var k = 0; k < t; k++) {\r\n var n = readline();\r\n var STR = readline();\r\n var List = STR.split(' ');\r\n var res = 0;\r\n if (STR.match(/0/g) == null) {\r\n process.stdout.write(res + '\\n');\r\n continue;\r\n }\r\n var z = STR.match(/0/g).length;\r\n for (var i = 0; i < n; i++) {\r\n if (List[i] == 0) {\r\n z--;\r\n } else {\r\n z--;\r\n res++;\r\n }\r\n if (z == 0) {\r\n process.stdout.write(res + '\\n');\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\n\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nlet t = +readline();\r\n\r\nwhile(t--){\r\n let n = +readline();\r\n let arr = readline().split(' ').map(x => +x);\r\n console.log(`${solve(arr, n)}`) \r\n}\r\n\r\nfunction solve(nums, n){\r\n let result = 0;\r\n let l = 0;\r\n let r = n-1;\r\n while(l < r){\r\n while(nums[r]) r--;\r\n while(nums[l] === 0) l++;\r\n if(l < r){\r\n result++;\r\n l++;\r\n r--;\r\n }\r\n }\r\n return result;\r\n}\r\n"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\n\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nlet t = +readline();\r\n\r\nwhile(t--){\r\n let n = +readline();\r\n let arr = readline().split(' ').map(x => +x);\r\n console.log(`${solve(arr, n)}`) \r\n}\r\n\r\nfunction solve(nums, n){\r\n let result = 0;\r\n let l = 0;\r\n let r = n-1;\r\n while(l < r){\r\n while(nums[r]) r--;\r\n while(nums[l] === 0) l++;\r\n if(l < r){\r\n result++;\r\n nums[l] = 0;\r\n nums[r] = 1;\r\n l++;\r\n r--;\r\n }\r\n }\r\n return result;\r\n}\r\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var oneLeft = [];\r\n var zeroRight = [];\r\n zeroRight[n] = 0;\r\n for (var i = 0; i < n; i++) {\r\n oneLeft[i] = (oneLeft[i - 1] || 0) + a[i];\r\n zeroRight[n - i - 1] = zeroRight[n - i] + 1 - a[n - i - 1];\r\n }\r\n\r\n for (i = 0; i < n; i++) {\r\n if (oneLeft[i] === zeroRight[i + 1]) {\r\n write(oneLeft[i]);\r\n return;\r\n }\r\n }\r\n write(0);\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX = 0;\r\nvar ANS = '';\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\nfunction sortNumbers(a, b) {\r\n return a - b;\r\n}\r\nfunction sortNumbersDec(a, b) {\r\n return b - a;\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar index = [];\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tif(list[i] == 0){\r\n\t\t\t\tindex.push(i);\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar output = 0;\r\n\t\tfor(var i = 0; i < N && index.length > 0; i++){\r\n\t\t\tif(list[i] == 1 && i < index[index.length - 1]){\r\n\t\t\t\toutput++;\r\n\t\t\t\tindex.pop();\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n for(let _=1;_<=t;_++)\r\n {\r\n let n=parseInt(line[2*_-1]);\r\n let a=line[2*_].split(' ').map(x=>{return parseInt(x)});\r\n let cnt=0;\r\n for(let i=0;i= l && a[r]) r--;\r\n while (r >= l && !a[l]) l++;\r\n if (l < r) {\r\n res++;\r\n }\r\n }\r\n return res;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst sqrt = (n) => {\r\n let low = 1n,\r\n high = n,\r\n ans;\r\n while (low <= high) {\r\n let mid = (low + high) / 2n;\r\n if (mid * mid <= n) {\r\n ans = mid;\r\n low = mid + 1n;\r\n } else high = mid - 1n;\r\n }\r\n return ans;\r\n};\r\n\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n let zero = [];\r\n for (let i = 0; i < n; i++) if (arr[i] === 0) zero.push(i);\r\n if (zero.length === 0) console.log(0);\r\n else {\r\n let ans = 0;\r\n let left = 0,\r\n right = zero.length - 1;\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] === 1) {\r\n if (right >= 0 && i < zero[right]) {\r\n ans++;\r\n right--;\r\n }\r\n } else left++;\r\n }\r\n console.log(ans);\r\n }\r\n }\r\n};\r\nsolve();\r\n"}], "negative_code": [{"source_code": "var n = parseInt(readline());\r\n\r\nfor (var i = 0; i < n; i++){\r\n var counter = 0;\r\n\r\n var k = parseInt(readline());\r\n var arr = readline().split(\" \");\r\n\r\n var bolo;\r\n for(var j = 1; j < k; j++){\r\n if(arr[j - 1] > arr[j]){\r\n bolo = k - 1; \r\n while (arr[bolo] == 1){\r\n bolo--;\r\n }\r\n arr[j - 1] = 0;\r\n arr[bolo] = 1\r\n j = 0\r\n counter++;\r\n }\r\n }\r\n print(counter);\r\n}"}, {"source_code": "var n = parseInt(readline());\r\n\r\nfor (var i = 0; i < n; i++){\r\n var counter = 0;\r\n\r\n var k = parseInt(readline());\r\n var arr = readline().split(\" \");\r\n\r\n for(var j = 1; j < k; j++){\r\n if(arr[j - 1] > arr[j]){\r\n j++;\r\n counter++;\r\n }\r\n }\r\n print(counter);\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => {\r\n return string.trim();\r\n });\r\n solve();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve() {\r\n var t = readline();\r\n for (var k = 0; k < t; k++) {\r\n var n = readline();\r\n var STR = readline();\r\n var List = STR.split(' ');\r\n var res = 0;\r\n var z = STR.match(/0/g).length;\r\n for (var i = 0; i < n; i++) {\r\n if (List[i] == 0) {\r\n z--;\r\n } else {\r\n z--;\r\n res++;\r\n }\r\n if (z == 0) {\r\n return process.stdout.write(res + '\\n');\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => {\r\n return string.trim();\r\n });\r\n solve();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve() {\r\n var t = readline();\r\n for (var k = 0; k < t; k++) {\r\n var n = readline();\r\n var List = readline().split(' ');\r\n var res = 0;\r\n for (var i = 1; i <= n; i++) {\r\n if (List[i] >= List[i - 1]) {\r\n if (n - i == 1) {\r\n console.log(res + '\\n');\r\n }\r\n } else {\r\n res++;\r\n if (n - i == 1) {\r\n console.log(res + '\\n');\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => {\r\n return string.trim();\r\n });\r\n solve();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve() {\r\n var t = readline();\r\n for (var k = 0; k < t; k++) {\r\n var n = readline();\r\n var List = readline().split(' ');\r\n var res = 0;\r\n for (var i = 1; i <= n; i++) {\r\n if (List[i] >= List[i - 1]) {\r\n if (n - i == 1) {\r\n console.log(res);\r\n }\r\n } else {\r\n res++;\r\n if (n - i == 1) {\r\n console.log(res);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => {\r\n return string.trim();\r\n });\r\n solve();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve() {\r\n var t = readline();\r\n for (var k = 0; k < t; k++) {\r\n var n = readline();\r\n var List = readline().split(' ');\r\n var res = 0;\r\n for (var i = 0; i < n; i++) {\r\n if (List[i] <= List[i + 1]) {\r\n if (n - i == 1) {\r\n console.log(res);\r\n }\r\n } else {\r\n res++;\r\n if (n - i == 1) {\r\n res = res - 1;\r\n console.log(res);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => {\r\n return string.trim();\r\n });\r\n solve();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve() {\r\n var t = readline();\r\n for (var k = 0; k < t; k++) {\r\n var n = readline();\r\n var List = readline().split(' ');\r\n var res = 0;\r\n for (var i = 0; i < n; i++) {\r\n if (List[i] <= List[i + 1]) {\r\n if (n - i == 1) {\r\n process.stdout.write(res + '\\n');\r\n }\r\n } else {\r\n res++;\r\n if (n - i == 1) {\r\n res = res - 1;\r\n process.stdout.write(res + '\\n');\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\n\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nlet t = +readline();\r\n\r\nwhile(t--){\r\n let n = +readline();\r\n let arr = readline().split(' ').map(x => +x);\r\n console.log(`${solve(arr, n)}`) \r\n}\r\n\r\nfunction solve(nums, n){\r\n let result = 0;\r\n while(--n){\r\n if(nums[n] < nums[n-1]) result++;\r\n }\r\n return result;\r\n}\r\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var oneLeft = [];\r\n var zeroRight = [];\r\n for (var i = 0; i < n; i++) {\r\n oneLeft[i] = (oneLeft[i - 1] || 0) + a[i];\r\n zeroRight[n - i - 1] = (zeroRight[n - i] || 0) + (1 - a[n - i - 1]);\r\n }\r\n\r\n for (i = 0; i < n - 1; i++) {\r\n if (oneLeft[i] === zeroRight[i + 1]) {\r\n write(oneLeft[i]);\r\n return;\r\n }\r\n }\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX = 0;\r\nvar ANS = '';\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\nfunction sortNumbers(a, b) {\r\n return a - b;\r\n}\r\nfunction sortNumbersDec(a, b) {\r\n return b - a;\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}], "src_uid": "c247c7c382c243ab6b991c4a11bfc421"} {"nl": {"description": "There are $$$n$$$ chests. The $$$i$$$-th chest contains $$$a_i$$$ coins. You need to open all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.There are two types of keys you can use to open a chest: a good key, which costs $$$k$$$ coins to use; a bad key, which does not cost any coins, but will halve all the coins in each unopened chest, including the chest it is about to open. The halving operation will round down to the nearest integer for each chest halved. In other words using a bad key to open chest $$$i$$$ will do $$$a_i = \\lfloor{\\frac{a_i}{2}\\rfloor}$$$, $$$a_{i+1} = \\lfloor\\frac{a_{i+1}}{2}\\rfloor, \\dots, a_n = \\lfloor \\frac{a_n}{2}\\rfloor$$$; any key (both good and bad) breaks after a usage, that is, it is a one-time use. You need to use in total $$$n$$$ keys, one for each chest. Initially, you have no coins and no keys. If you want to use a good key, then you need to buy it.During the process, you are allowed to go into debt; for example, if you have $$$1$$$ coin, you are allowed to buy a good key worth $$$k=3$$$ coins, and your balance will become $$$-2$$$ coins.Find the maximum number of coins you can have after opening all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 10^5$$$; $$$0 \\leq k \\leq 10^9$$$) — the number of chests and the cost of a good key respectively. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \\leq a_i \\leq 10^9$$$)  — the amount of coins in each chest. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case output a single integer  — the maximum number of coins you can obtain after opening the chests in order from chest $$$1$$$ to chest $$$n$$$. Please note, that the answer 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 (like long long for C++).", "sample_inputs": ["5\n\n4 5\n\n10 10 3 1\n\n1 2\n\n1\n\n3 12\n\n10 10 29\n\n12 51\n\n5 74 89 45 18 69 67 67 11 96 23 59\n\n2 57\n\n85 60"], "sample_outputs": ["11\n0\n13\n60\n58"], "notes": "NoteIn the first test case, one possible strategy is as follows: Buy a good key for $$$5$$$ coins, and open chest $$$1$$$, receiving $$$10$$$ coins. Your current balance is $$$0 + 10 - 5 = 5$$$ coins. Buy a good key for $$$5$$$ coins, and open chest $$$2$$$, receiving $$$10$$$ coins. Your current balance is $$$5 + 10 - 5 = 10$$$ coins. Use a bad key and open chest $$$3$$$. As a result of using a bad key, the number of coins in chest $$$3$$$ becomes $$$\\left\\lfloor \\frac{3}{2} \\right\\rfloor = 1$$$, and the number of coins in chest $$$4$$$ becomes $$$\\left\\lfloor \\frac{1}{2} \\right\\rfloor = 0$$$. Your current balance is $$$10 + 1 = 11$$$. Use a bad key and open chest $$$4$$$. As a result of using a bad key, the number of coins in chest $$$4$$$ becomes $$$\\left\\lfloor \\frac{0}{2} \\right\\rfloor = 0$$$. Your current balance is $$$11 + 0 = 11$$$. At the end of the process, you have $$$11$$$ coins, which can be proven to be maximal."}, "positive_code": [{"source_code": "var t = readline();\r\n\r\nfor (var i = 0; i < t; i++) {\r\n var inp = readline().split(' ');\r\n var n = inp[0];\r\n var k = inp[1];\r\n var chests = readline().split(' ');\r\n var ans = 0;\r\n var good30 = 0;\r\n\r\n for (var j = 0; j < n; j++) {\r\n var bad30 = 0;\r\n var div = 1;\r\n\r\n for (var p = j; p < n && p < j + 31; p++) {\r\n div *= 2;\r\n bad30 += Math.floor(parseInt(chests[p]) / div);\r\n }\r\n ans = Math.max(ans, good30 + bad30);\r\n good30 += parseInt(chests[j]) - k;\r\n }\r\n\r\n ans = Math.max(ans, good30);\r\n\r\n print(ans);\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, k, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, arr) {\n // return check(n, k, arr)\n //\n // const dp = []\n // const save = arr.slice()\n // for (let i = 0; i <= 30; i++) {\n const sum = []\n for (let j = 0; j < arr.length; j++) {\n sum[j] = arr[j]\n if (j) sum[j] += sum[j - 1]\n // arr[j] = Math.floor(arr[j] / 2)\n }\n // dp[i] = sum\n // }\n // console.log(dp)\n let ans = sum[n - 1] - n * k\n for (let i = 0; i < arr.length; i++) {\n let now = (sum[i - 1] || 0) - k * i\n for (let j = 0; j <= 30; j++) {\n if (i + j >= n) break\n now += Math.floor(arr[i + j] / (2 ** (j + 1)))\n }\n // console.log(i, now)\n ans = Math.max(ans, now)\n }\n return ans\n}\nfunction check(n, k, arr) {\n const limit = 2 ** n\n let max = -Infinity\n for (let i = 0; i < limit; i++) {\n let bad = 0\n let ans = 0\n for (let j = 0; j < n; j++) {\n if (i & (1 << j)) {\n // bad\n bad++\n } else {\n ans -= k\n }\n ans += Math.floor(arr[j] / (2 ** bad))\n }\n if (ans > max) {\n console.log(i.toString(2), ans)\n max = ans\n }\n }\n return max\n}\n"}], "negative_code": [{"source_code": "var t = parseInt(readline());\r\n \r\nfor (var i = 0; i < t; i++) {\r\n var inp = readline().split(' ');\r\n var n = inp[0];\r\n var k = inp[1];\r\n var chests = readline().split(' ');\r\n \r\n var ans = 0;\r\n \r\n var rest = 0;\r\n var div = 0;\r\n \r\n for (var j = 0; j < chests.length; j++) {\r\n rest += chests[j];\r\n }\r\n \r\n for (var j = 0; j < chests.length; j++) {\r\n var curr = chests[j];\r\n for (var l = 0; l < div; l++) {\r\n curr = Math.floor(curr / 2);\r\n }\r\n \r\n if (Math.floor(rest / 2) < rest - k) {\r\n ans -= k;\r\n ans += curr;\r\n rest -= curr;\r\n } else {\r\n ans += Math.floor(curr / 2);\r\n rest -= curr;\r\n rest = Math.floor(rest / 2);\r\n div++;\r\n }\r\n }\r\n \r\n print(ans);\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, k, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, arr) {\n const dp = []\n const save = arr.slice()\n for (let i = 0; i <= 30; i++) {\n const sum = []\n for (let j = 0; j < arr.length; j++) {\n sum[j] = arr[j]\n if (j) sum[j] += sum[j - 1]\n arr[j] = Math.floor(arr[j] / 2)\n }\n dp[i] = sum\n }\n // console.log(dp)\n let ans = 0\n let bad = 0\n for (let i = 0; i < arr.length; i++) {\n const cur = dp[bad][n - 1] - (dp[bad][i - 1] || 0)\n const next = dp[bad + 1][n - 1] - (dp[bad + 1][i - 1] || 0)\n if (cur - next < k) {\n bad++\n } else {\n ans -= k\n }\n ans += bad ? Math.floor(save[i] / (2 ** bad)) : save[i]\n }\n return ans\n}\n"}], "src_uid": "9fcc55a137b5ff021fdc8e1e867ce856"} {"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)$$$ — 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)$$$ — 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$$$) — 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$$$) — 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 — 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": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nconst log = console.log\r\n\r\n\r\n/********** MAIN *****************/\r\nfunction main() {\r\n let t = parseInt(readline());\r\n let cols,line1,line2,g =[],a\r\n while(t-->0){\r\n cols = parseInt(readline());\r\n line1 = readline().split(\"\")\r\n line2 = readline().split(\"\")\r\n g.push(line1)\r\n g.push(line2)\r\n a=dfs(g,0,0,cols)\r\n a?log('YES'):log('NO')\r\n g =[]\r\n }\r\n}\r\n\r\nconst dfs = (g,r,c,cols)=>{\r\n if(c===cols){\r\n return true\r\n }\r\n if(g[r][c]==='0' || g[r+1][c]==='0'){\r\n return dfs(g,r,c+1,cols)\r\n }\r\n else{\r\n return false\r\n }\r\n}\r\n"}, {"source_code": "\r\n\r\n// /****************************************************************\\\r\n// BISMILLAHIR RAHMANIR RAHIM\r\n// ****************************************************************\r\n// AUTHOR NAME: MD. TAHURUZZOHA TUHIN\r\n// \\****************************************************************/\r\n\r\n\r\n\r\n// 'use strict';\r\n// process.stdin.resume();\r\n// process.stdin.setEncoding('utf-8');\r\n\r\n// let inputString = '';\r\n// let currentLine = 0;\r\n\r\n// process.stdin.on('data', inputStdin => {\r\n// inputString += inputStdin;\r\n// });\r\n\r\n// process.stdin.on('end', _ => {\r\n// inputString = inputString.trim().split('\\n').map(string => {\r\n// return string.trim();\r\n// });\r\n\r\n// main();\r\n// });\r\n\r\n// function input() {\r\n// return inputString[currentLine++];\r\n// }\r\n\r\n// function main() {\r\n\r\n// let n, m, p, mx = [], mn = [], mp = [], mk = [], mh = [], t;\r\n// t = input();\r\n// let a = 0;\r\n// while (a < t) {\r\n// a++;\r\n// n = input();\r\n// n = parseInt(n);\r\n// m = input();\r\n// p = input();\r\n\r\n// for (const x of m) {\r\n// mx.push(x.toString());\r\n// }\r\n\r\n// for (const x of p) {\r\n// mn.push(x.toString());\r\n// }\r\n// mp = [mx, mn];\r\n// for (let i = 0; i < 2; i++) {\r\n// for (let j = 0; j < n; j++) {\r\n// if (mp[i][j] === '0' && i == 0) {\r\n// mk.push(i + 1, j + 1);\r\n// }\r\n// if (mp[i][j] === '0' && i == 1) {\r\n// mh.push(i + 1, j + 1);\r\n// }\r\n// }\r\n// }\r\n// let mg = [...mk, ...mh];\r\n// let cnt = 0, pnt = 1;\r\n// for (let i = 0; i < mg.length / 2; i += 1) {\r\n// let v1 = Math.abs(mg[i] - mg[i + 2]);\r\n// if (v1 >= 2) pnt = 0;\r\n// }\r\n\r\n// if (pnt === 0) {\r\n// for (let i = 0; i < mk.length; i += 2) {\r\n// let v3 = Math.abs(mk[i] - mh[i]);\r\n// let v4 = Math.abs(mk[i + 1] - mh[i + 1]);\r\n// if (((v3 >= 2 || v4 >= 2))) {\r\n// cnt = 0;\r\n// } else {\r\n// cnt = 1;\r\n// }\r\n// }\r\n// }\r\n// console.log((pnt || cnt ? \"YES\" : \"NO\"));\r\n// mk.length = 0;\r\n// mh.length = 0;\r\n// mg.length = 0;\r\n// mp.length = 0;\r\n// mx.length = 0;\r\n// mn.length = 0;\r\n// }\r\n\r\n// }\r\n\r\n\r\n\r\n\r\n\r\n/****************************************************************\\\r\n BISMILLAHIR RAHMANIR RAHIM\r\n****************************************************************\r\n AUTHOR NAME: MD. TAHURUZZOHA TUHIN\r\n\\****************************************************************/\r\n\r\n\r\n\r\n'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n\r\n let n, m, p, mx = [], mn = [], t;\r\n t = input();\r\n let a = 0;\r\n while (a < t) {\r\n a++;\r\n n = input();\r\n n = parseInt(n);\r\n m = input();\r\n p = input();\r\n\r\n for (const x of m) {\r\n mx.push(x.toString());\r\n }\r\n\r\n for (const x of p) {\r\n mn.push(x.toString());\r\n }\r\n let out = \"YES\"\r\n for (let i = 0; i < n; i++) {\r\n if (mx[i] === '1' && mn[i] === '1') {\r\n out = \"NO\";\r\n break;\r\n }\r\n }\r\n console.log(out);\r\n mx.length = 0;\r\n mn.length = 0;\r\n p = 0;\r\n n = 0;\r\n m = 0;\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n \nfunction Queue() {\n this.length = 0;\n}\n \nQueue.prototype.push = function (item) {\n var node = {item: item};\n if (this.last) {\n this.last = this.last.next = node;\n } else {\n this.last = this.first = node;\n }\n this.length++;\n};\n\nQueue.prototype.shift = function () {\n var node = this.first;\n if (node) {\n this.first = node.next;\n if (!(--this.length)) {\n this.last = undefined;\n }\n return node.item;\n }\n};\n\nQueue.prototype.slice = function (start, end) {\n start = typeof start === 'undefined' ? 0 : start;\n end = typeof end === 'undefined' ? Infinity : end;\n\n var output = [];\n\n var i = 0;\n for (var node = this.first; node; node = node.next) {\n if (--end < 0) {\n break;\n } else if (++i > start) {\n output.push(node.item);\n }\n }\n return output;\n}\n\nclass Logger {\n\n constructor() {\n this.enabled = false;\n }\n\n enable() {\n this.enabled = true;\n }\n\n disable() {\n this.enabled = false;\n }\n\n log(...str) {\n if (this.enabled) {\n console.error(...str);\n }\n }\n}\n\nlet logger = new Logger();\n// logger.enable();\n \nfunction main() {\n\n let t = +readline();\n\n for (let i = 0; i < t; ++i) {\n let n = +readline();\n let a = readline();\n let b = readline();\n\n let canReachEnd = true;\n\n for (let j = 0; j < n; ++j) {\n if (a[j] == '1' && b[j] == '1') {\n canReachEnd = false;\n break;\n }\n }\n\n console.log(canReachEnd?'YES':'NO')\n\n }\n\n}"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, s) {\r\n const dp = Array.from({\r\n length: n\r\n }, () => [0, 0]);\r\n for (let j = 0; j < 2; j++) if (s[j][0] === '0') dp[0][j] = 1;\r\n for (let i = 1; i < n; i++) {\r\n for (let j = 0; j < 2; j++) if (s[j][i] === '0' && (dp[i - 1][0] || dp[i - 1][1])) dp[i][j] = 1;\r\n }\r\n return dp[n - 1][0] || dp[n - 1][1] ? 'YES' : 'NO';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = [];\r\n let tmp = 2;\r\n while (tmp--) {\r\n a.push(await read());\r\n }\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "var readline = require('readline');\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nlet ls = [];\r\n\r\nfunction solve(){\r\n let l = 0;\r\n const t = parseInt(ls[l++]);\r\n for (let q = 0; q < t; q++){\r\n const n = parseInt(ls[l++]);\r\n const s1 = ls[l++];\r\n const s2 = ls[l++];\r\n let res = 'YES';\r\n for (let i = 0; i < n; i++){\r\n if (s1[i] == '1' && s2[i] == '1'){\r\n res = 'NO';\r\n break;\r\n }\r\n }\r\n console.log(res);\r\n }\r\n}\r\n\r\nrl.on('line', (l) => ls.push(l));\r\nrl.on('close', () => solve());"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet n = nl.num();\n\t\tlet a = nl.line().split('');\n\t\tlet b = nl.line().split('');\n\t\tlet flag = true;\n\t\tfor(let j = 0; j < n && flag; j++){\n\t\t\tif (a[j] === '1' && a[j] === b[j]) {\n\t\t\t\tflag = false;\n\t\t\t}\n\t\t}\n\t\tans.push(flag);\n\t}\n\tconsole.log(ans.map(e => e?\"YES\":\"NO\").join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "let inputText = ''\r\nprocess.stdin.on('data', c => inputText += c)\r\n\r\nprocess.stdin.on('end', () => {\r\n\r\n const {EOL} = require('os')\r\n const lines = inputText.split(EOL) /*your input text, split by lines*/\r\n\r\n // console.log(lines);\r\n\r\n let pointer = 0;\r\n let k = parseInt(lines[pointer++]);\r\n outer : while (k -- > 0) {\r\n\r\n let len = parseInt(lines[pointer++]);\r\n let line1 = lines[pointer++];\r\n let line2 = lines[pointer++];\r\n\r\n // console.log(\"NO\");\r\n for(let i = 0 ; i < len ; i++) {\r\n if(line1[i] === '1' && line2[i] === '1') {\r\n console.log(\"NO\");\r\n continue outer;\r\n }\r\n }\r\n\r\n console.log(\"YES\");\r\n }\r\n\r\n // [n, m, a] = inputText.split(' ');\r\n // let k1 = n / a;\r\n // let k2 = m / a;\r\n // console.log(Math.ceil(k1) * Math.ceil(k2))\r\n})\r\n\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar dy = [-1,-1,-1,0,1,1,1,0];\r\n\tvar dx = [-1,0,1,1,1,0,-1,-1];\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar s = [next(), next()];\r\n\t\tvar list = new Array(2);\r\n\t\tfor(var i = 0; i < 2; i++){\r\n\t\t\tlist[i] = new Array(N).fill(false);\r\n\t\t}\r\n\r\n\t\tvar queue = [];\r\n\t\tif(s[0][0] == \"0\"){\r\n\t\t\tqueue.push([0,0]);\r\n\t\t\tlist[0][0] = true;\r\n\t\t}\r\n\t\twhile(queue.length > 0){\r\n\t\t\tvar now = queue.shift();\r\n\t\t\tvar y = now[0];\r\n\t\t\tvar x = now[1];\r\n\t\t\tfor(var i = 0; i < dy.length; i++){\r\n\t\t\t\tvar nextY = y + dy[i];\r\n\t\t\t\tvar nextX = x + dx[i];\r\n\t\t\t\tif(nextY < 2 && nextY >= 0 && nextX < N && nextX >= 0){\r\n\t\t\t\t\tif(s[nextY][nextX] == \"0\" && !list[nextY][nextX]){\r\n\t\t\t\t\t\tlist[nextY][nextX] = true;\r\n\t\t\t\t\t\tqueue.push([nextY, nextX]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout((list[1][N - 1]) ? \"YES\" : \"NO\");\r\n\t}\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const grid = lines.slice(l, l + 2).map(str => str.trim())\n l += 2\n output[i] = solve(n, grid)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, grid) {\n const q = [[0, 0]]\n const visited = {}\n while (q.length) {\n // console.log(q)\n const [x, y] = q.shift()\n if (x === 1 && y === n - 1) return 'YES'\n const k = x + ',' + y\n if (visited[k]) continue\n visited[k] = 1\n\n add(n, grid, q, x, y + 1)\n add(n, grid, q, x + 1, y)\n add(n, grid, q, x + 1, y + 1)\n add(n, grid, q, x - 1, y)\n add(n, grid, q, x - 1, y + 1)\n }\n return 'NO'\n}\nfunction add(n, grid, q, x, y) {\n if (x >= 0 && x < 2 && y >= 0 && y < n && grid[x][y] === '0') {\n q.push([x, y])\n }\n}\n"}, {"source_code": "var t = parseInt(readline());\nfor (var i=0; i 0) {\r\n var n, c1, c2;\r\n n = readline();\r\n c1 = readline();\r\n c2 = readline();\r\n for (var i = 0; i < n; i++)\r\n if (c1[i] == '1' && c2[i] == '1')\r\n n = -1;\r\n write(n == -1 ? \"NO\\n\" : \"YES\\n\");\r\n}"}, {"source_code": "var testcase=parseInt(readline())\r\nwhile(testcase--)\r\n{\r\n var n=parseInt(readline())\r\n var s1=readline()\r\n var s2=readline()\r\n \r\n var ans=true\r\n var ind=0;\r\n while(ind {\r\n input+=line\r\n });\r\n\r\n\r\n readline.on('end',()=>{\r\n console.log(input)\r\n })"}, {"source_code": "\r\n/****************************************************************\\\r\n BISMILLAHIR RAHMANIR RAHIM\r\n****************************************************************\r\n AUTHOR NAME: MD. TAHURUZZOHA TUHIN\r\n\\****************************************************************/\r\n\r\n\r\n\r\n'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n\r\n let n, m, p, mx = [], mn = [], mp = [], mk = [], mh = [], t;\r\n t = input();\r\n let a = 0;\r\n while (a < t) {\r\n a++;\r\n n = input();\r\n n = parseInt(n);\r\n m = input();\r\n p = input();\r\n\r\n for (const x of m) {\r\n mx.push(x.toString());\r\n }\r\n\r\n for (const x of p) {\r\n mn.push(x.toString());\r\n }\r\n mp = [mx, mn];\r\n for (let i = 0; i < 2; i++) {\r\n for (let j = 0; j < n; j++) {\r\n if (mp[i][j] === '0' && i == 0) {\r\n mk.push(i + 1, j + 1);\r\n }\r\n if (mp[i][j] === '0' && i == 1) {\r\n mh.push(i + 1, j + 1);\r\n }\r\n }\r\n }\r\n let mg = [...mk, ...mh];\r\n let cnt = 0, pnt = 1;\r\n for (let i = 0; i < mg.length / 2; i += 1) {\r\n let v1 = Math.abs(mg[i] - mg[i + 2]);\r\n if (v1 >= 2) pnt = 0;\r\n }\r\n\r\n if (pnt === 0) {\r\n for (let i = 0; i < mk.length; i += 2) {\r\n let v3 = Math.abs(mk[i] - mh[i]);\r\n let v4 = Math.abs(mk[i + 1] - mh[i + 1]);\r\n if (((v3 >= 2 || v4 >= 2))) {\r\n cnt = 0;\r\n } else {\r\n cnt = 1;\r\n }\r\n }\r\n }\r\n console.log((pnt || cnt ? \"YES\" : \"NO\"));\r\n mk.length = 0;\r\n mh.length = 0;\r\n mg.length = 0;\r\n mp.length = 0;\r\n mx.length = 0;\r\n mn.length = 0;\r\n }\r\n\r\n}"}, {"source_code": "\r\n/****************************************************************\\\r\n BISMILLAHIR RAHMANIR RAHIM\r\n****************************************************************\r\n AUTHOR NAME: MD. TAHURUZZOHA TUHIN\r\n\\****************************************************************/\r\n\r\n\r\n\r\n'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction input() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n\r\n let n, m, p, mx = [], mn = [], mp = [], mk = [], mh = [], t;\r\n t = input();\r\n let a = 0;\r\n while (a < t) {\r\n a++;\r\n n = input();\r\n n = parseInt(n);\r\n m = input();\r\n p = input();\r\n\r\n for (const x of m) {\r\n mx.push(x.toString());\r\n }\r\n\r\n for (const x of p) {\r\n mn.push(x.toString());\r\n }\r\n mp = [mx, mn];\r\n for (let i = 0; i < 2; i++) {\r\n for (let j = 0; j < n; j++) {\r\n if (mp[i][j] === '0' && i == 0) {\r\n mk.push(i + 1, j + 1);\r\n }\r\n if (mp[i][j] === '0' && i == 1) {\r\n mh.push(i + 1, j + 1);\r\n }\r\n }\r\n }\r\n let mg = [...mk, ...mh];\r\n let cnt = 0, pnt = 1;\r\n for (let i = 0; i < mg.length / 2; i += 1) {\r\n let v1 = Math.abs(mg[i] - mg[i + 2]);\r\n if (v1 >= 2) pnt = 0;\r\n }\r\n\r\n if (pnt === 0) {\r\n for (let i = 0; i < mk.length; i += 2) {\r\n let v3 = Math.abs(mk[i] - mh[i]);\r\n let v4 = Math.abs(mk[i + 1] - mh[i + 1]);\r\n if (((v3 >= 2 || v4 >= 2))) {\r\n cnt = 0;\r\n } else {\r\n cnt = 1;\r\n }\r\n }\r\n }\r\n console.log((pnt || cnt ? \"YES\" : \"NO\"));\r\n mk = mk.splice(0, mk.lenth);\r\n mh = mh.splice(0, mh.lenth);\r\n mg = mg.splice(0, mg.lenth);\r\n mp = mp.splice(0, mp.lenth);\r\n mx = mx.splice(0, mx.lenth);\r\n mn = mn.splice(0, mn.lenth);\r\n }\r\n\r\n}"}], "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 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type. ", "output_spec": "The only line of output contains one integer — 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 — on the second day, and of third type — 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": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\nvar numbers = ints(),\n\tn = numbers[0],\n\tk = numbers[1],\n\ts = ints().reduce(function(s, x) {\n\t\treturn s + Math.floor(x / k) + (x % k == 0 ? 0 : 1)\n\t}, 0)\n\nprint(Math.floor(s / 2) + (s % 2))"}, {"source_code": "\nvar params = readline().split(\" \").map(function convert(value) {return +value; });\n\nvar n = params[0];\nvar k = params[1];\n\nvar counter = readline().split(\" \").map(function convert(value) {return +value; })\n\t\t\t\t\t\t\t\t\t.reduce(function (total, current) {\n\t\t\t\t\t\t\t\t\t\treturn total + (current - current % k) / k + (current % k !== 0);}, 0);\n\nprint((counter - counter % 2) / 2 + (counter % 2 !== 0));\n"}, {"source_code": "\"use strict\";\nif (typeof print == 'undefined') var print = console.log;\nif (typeof readline == 'undefined') {\n let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\\n');\n var readline = () => lines[id ++];\n}\n\nlet nums = () => readline().split(' ').map(x => +x);\nlet t = nums(), n = t[0], k = t[1];\n\nlet a = nums().map(x => Math.floor((x + k -1) / k)).reduce((m, n) => m + n, 0);\nprint(Math.floor((a + 1) / 2));\n\n"}, {"source_code": "var g = readline().split(\" \");\nvar n = +g[0];\nvar k = +g[1];\nvar y = readline().split(\" \");\nvar sum = 0;\nfor(i=0;i lines[id ++];\n}\n\nlet nums = () => readline().split(' ').map(x => +x);\nlet t = nums(), n = t[0], k = t[1];\n\nlet ans = 0, c = 0;\nlet a = nums().map(x => (ans += Math.floor(x / (2 * k)), x % (2 * k)));\nfor (let i of a) {\n if (i > k) ans ++;\n else ++c;\n}\nans += c >>> 1; if (c & 1) ans++;\nprint(ans);\n\n"}], "src_uid": "3992602be20a386f0ec57c51e14b39c5"} {"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$$$) — 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$$$ — the type of the favorite drink of the $$$i$$$-th student.", "output_spec": "Print exactly one integer — 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": "function main() {\n // write code here:\n const nk = stdin[0].split(' ').map(Number)\n var arr = new Array(nk[1]).fill(0),\n result = 0,\n t = 0;\n for (let i = 1; i <= nk[0]; i++) {\n var a = Number(stdin[i]) - 1;\n arr[a]++;\n }\n for (let j = 0; j < nk[1]; j++) {\n result += Math.floor(arr[j] / 2) * 2;\n //如果arr[j]为奇数,则先记录下来为奇数的个数\n if (arr[j] % 2 === 1) t++;\n }\n //在最后的 result 加上 (奇数个数+1)/ 2 的结果\n result += Math.floor((t + 1) / 2);\n console.log(result);\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({input: process.stdin});\nvar stdin = [];\nrl.on('line', function (line) {\n stdin.push(line);\n});\nrl.on('close', main);"}, {"source_code": "var r = readline().split(' ').map(Number);\nvar n = r[0], k = r[1], d = {};\nfor (var i = 0; i < n; i++) {\n var j = readline();\n d[j] = d[j] ? 0 : 1;\n}\nvar x = Object.keys(d).reduce((r, i) => r + d[i], 0);\nprint(n - x + Math.ceil(x/2));\n"}, {"source_code": "var n = Number(readline().split(' ')[0]), d = {};\nfor (var i = 0; i < n; i++) {var j = readline(); d[j] = d[j] ? 0 : 1;}\nvar x = Object.keys(d).reduce((r, i) => r + d[i], 0);\nwrite(n - x + Math.ceil(x/2));\n"}, {"source_code": "var arr = readline().split(' ').map(item => +item);\nvar n = arr[0], k = arr[1];\n\narr = new Array(k).fill(0);\n\nfor(var i = 0; i < n; i++) {\n var j = +readline() - 1;\n arr[j]++;\n}\n\ncount = 0;\nmod = 0;\n\nfor(var i = 0; i < arr.length; i++) {\n var j = arr[i] % 2;\n count += arr[i] - j;\n mod += j;\n}\n\ncount += parseInt(mod / 2) + mod % 2;\n\nprint(count);\n"}, {"source_code": "\"use strict\";\n\nvar main = function() {\n var input = rdAr();\n var n = input[0];\n var k = input[1];\n var C = crAr(2000, 0);\n for (var i = 0; i < n; ++i) {\n var a = +rd();\n C[a] = (++C[a]) % 2;\n }\n var r = C.reduce((v, a) => v + a);\n var bad = r >> 1;\n wr(n - bad);\n};\n \nconst rd = readline;\nconst wr = write;\nconst pr = print;\nconst rdAr = () => rd().split(' ').map(v => +v);\nconst prAr = (a) => pr(a.join(' '));\nconst cmpLt = (a, b) => a - b;\nconst cmpGt = (a, b) => b - a;\nArray.prototype.sortLt = function() { return this.sort(cmpLt); };\nArray.prototype.sortGt = function() { return this.sort(cmpGt); };\nconst crAr = function(length, ...fillArgs) { return new Array(length).fill(...fillArgs); };\n \nmain();"}, {"source_code": "var v = readline().split(' ');\nv.map(x => Number(x));\nvar cnt = new Array;\ncnt.length = v[1];\ncnt.fill(0,0, v[1]);\nfor(var i = 0;i < v[0];i++){\n var x = Number(readline());\n cnt[x - 1]++;\n}\n\nvar ans = 0;\nvar have = Math.floor((v[0] + 1)/2);\nvar t = 0;\nfor(i = 0;i < v[1];i++){\n ans += Math.floor( (cnt[i] / 2)) * 2;\n if(cnt[i] % 2 == 1) t++;\n}\nans += Math.floor((t + 1)/2);\nprint(ans);"}], "negative_code": [], "src_uid": "dceeb739a56bb799550138aa8c127996"} {"nl": {"description": "A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print \"NO\" (without quotes).A substring of a string is a contiguous subsequence of letters in the string. For example, \"ab\", \"c\", \"abc\" are substrings of string \"abc\", while \"ac\" is not a substring of that string.The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.", "input_spec": "The first line contains integer n (1 ≤ n ≤ 105) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105.", "output_spec": "Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print \"NO\" (without quotes) if there are no good strings.", "sample_inputs": ["4\nmail\nai\nlru\ncf", "3\nkek\npreceq\ncheburek"], "sample_outputs": ["cfmailru", "NO"], "notes": "NoteOne can show that in the first sample only two good strings with minimum length exist: \"cfmailru\" and \"mailrucf\". The first string is lexicographically minimum."}, "positive_code": [{"source_code": "var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');\nvar map = {};\n\nalphabet.forEach(function(char) {\n map[char] = {\n used: false,\n to: undefined,\n from: undefined\n };\n});\n\nvar n = Number(readline());\nvar hasResult = true;\n\ncycle:\n for(var i = 0; i result.length) {\n print('NO');\n } else {\n print(result);\n }\n}"}, {"source_code": "var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');\nvar map = {};\n\nalphabet.forEach(function(char) {\n map[char] = {\n used: false,\n to: undefined,\n from: undefined\n };\n});\n\nvar n = Number(readline());\nvar hasResult = true;\n\ncycle:\n for(var i = 0; i result.length) {\n print('NO');\n } else {\n print(result);\n }\n}"}, {"source_code": "var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');\nvar map = {};\n\nalphabet.forEach(function(char) {\n map[char] = {\n used: false,\n to: undefined,\n from: undefined\n };\n});\n\nvar n = Number(readline());\nvar hasResult = true;\n\ncycle:\n for(var i = 0; i result.length) {\n print('NO');\n } else {\n print(result);\n }\n}"}], "negative_code": [{"source_code": "\nvar alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');\nvar map = {};\n\nalphabet.forEach(function(char) {\n\tmap[char] = {\n\t\tisFirstChar: false,\n\t\tused: false,\n\t\tdirection: undefined\n\t};\n});\n\nvar n = Number(readline());\nvar hasResult = true;\n\ncycle:\nfor(var i = 0; i= 0; i--) {\r\n var _mnr;\r\n while (mxr.length && a[mxr[mxr.length - 1]] < a[i]) mxr.pop();\r\n while (mnr.length && a[mnr[mnr.length - 1]] > a[i]) mnr.pop();\r\n if (mxr.length && mxr[mxr.length - 1] < ((_mnr = mnr[mnr.length - 1]) !== null && _mnr !== void 0 ? _mnr : Infinity)) {\r\n var _mnr2;\r\n let t = (_mnr2 = mnr[mnr.length - 1]) !== null && _mnr2 !== void 0 ? _mnr2 : Infinity;\r\n let j = binarySearch(mxr, 0, mxr.length - 1, j => mxr[j] > t);\r\n next[i] = mxr[j];\r\n } else if (mnr.length) {\r\n var _mxr;\r\n let t = (_mxr = mxr[mxr.length - 1]) !== null && _mxr !== void 0 ? _mxr : Infinity;\r\n let j = binarySearch(mnr, 0, mnr.length - 1, j => mnr[j] > t);\r\n next[i] = mnr[j];\r\n }\r\n mxr.push(i);\r\n mnr.push(i);\r\n }\r\n let res = 0;\r\n for (let i = 0; i < n - 1; i = next[i]) res++;\r\n return res;\r\n}\r\nfunction binarySearch(arr, l, r, comp) {\r\n while (l < r) {\r\n const m = l + r >> 1;\r\n if (comp(m)) l = m + 1;else r = m;\r\n }\r\n return l;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n if (n === 1) return 0;\r\n const mnl = new Array(n).fill(-1),\r\n mnr = new Array(n).fill(n);\r\n let st = [];\r\n for (let i = 0; i < n; i++) {\r\n while (st.length && a[st[st.length - 1]] > a[i]) st.pop();\r\n if (st.length) mnl[i] = st[st.length - 1];\r\n st.push(i);\r\n }\r\n st = [];\r\n for (let i = n - 1; i >= 0; i--) {\r\n while (st.length && a[st[st.length - 1]] > a[i]) st.pop();\r\n if (st.length) mnr[i] = st[st.length - 1];\r\n st.push(i);\r\n }\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [];\r\n let idx = 0;\r\n const add = (i, j) => {\r\n e[idx] = j, ne[idx] = h[i], h[i] = idx++;\r\n };\r\n st = [];\r\n for (let i = 0; i < n; i++) {\r\n while (st.length && a[st[st.length - 1]] < a[i]) st.pop();\r\n for (let j = st.length - 1; j >= 0; j--) {\r\n if (st[j] < mnl[i]) break;\r\n add(i, st[j]);\r\n add(st[j], i);\r\n }\r\n st.push(i);\r\n }\r\n st = [];\r\n for (let i = n - 1; i >= 0; i--) {\r\n while (st.length && a[st[st.length - 1]] < a[i]) st.pop();\r\n for (let j = st.length - 1; j >= 0; j--) {\r\n if (st[j] > mnr[i]) break;\r\n add(i, st[j]);\r\n add(st[j], i);\r\n }\r\n st.push(i);\r\n }\r\n let query = [0],\r\n vis = new Array(n),\r\n dis = 0;\r\n while (1) {\r\n dis++;\r\n const tmp = [];\r\n for (let u of query) {\r\n vis[u] = 1;\r\n for (let k = h[u]; k !== -1; k = ne[k]) {\r\n const v = e[k];\r\n if (vis[v]) continue;\r\n if (v === n - 1) {\r\n process.stdout.write(dis + '\\n');\r\n return;\r\n }\r\n tmp.push(v);\r\n }\r\n }\r\n query = tmp;\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "src_uid": "2592836c1457efda9ad333524abfdf56"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$, consisting of $$$n$$$ integers each.Let's define a function $$$f(a, b)$$$ as follows: let's define an array $$$c$$$ of size $$$n$$$, where $$$c_i = a_i \\oplus b_i$$$ ($$$\\oplus$$$ denotes bitwise XOR); the value of the function is $$$c_1 \\mathbin{\\&} c_2 \\mathbin{\\&} \\cdots \\mathbin{\\&} c_n$$$ (i.e. bitwise AND of the entire array $$$c$$$). Find the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way (leaving the initial order is also an option).", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) — the size of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i < 2^{30}$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$0 \\le b_i < 2^{30}$$$). The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer — the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way.", "sample_inputs": ["3\n\n5\n\n1 0 0 3 3\n\n2 3 2 1 0\n\n3\n\n1 1 1\n\n0 0 3\n\n8\n\n0 1 2 3 4 5 6 7\n\n7 6 5 4 3 2 1 0"], "sample_outputs": ["2\n0\n7"], "notes": null}, "positive_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const sa = lines[l++].trim().split(' ').map(Number)\n const sb = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, sa, sb)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, sa, sb) {\n let r = 0\n for (let k = 29; k >= 0; k--) {\n const mask = r | (1 << k)\n const m1 = {}\n const m2 = {}\n for (let i = 0; i < n; i++) {\n const k1 = sa[i] & mask\n const k2 = sb[i] & mask\n m1[k1] = (m1[k1] || 0) + 1\n m2[k2] = (m2[k2] || 0) + 1\n }\n // console.log(k, m1, m2)\n let ok = 1\n for (let h1 in m1) {\n const h2 = (~h1) & mask\n if (m1[h1] !== m2[h2]) {\n ok = 0\n break\n }\n }\n if (ok) r |= (1 << k)\n }\n return r\n}\n"}], "negative_code": [], "src_uid": "bed2d2e4a33bf133f7e9d5ebc1557c3e"} {"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$$$) — 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$$$) — the number of rows and columns of the table $$$a$$$ respectively.", "output_spec": "For each test case output a single integer — 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": "const readline = require('readline').createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\n\r\nlet lineCounter = 0\r\n// multi line input\r\nreadline.on('line', (line) => {\r\n if (lineCounter > 0) {\r\n let [n, m] = line.split(' ').map(Number)\r\n console.log(optimalPath(n, m))\r\n }\r\n lineCounter++\r\n})\r\n\r\nlet optimalPath = (n, m) => {\r\n let minimalCost = (m * (m - 1)) / 2\r\n\r\n minimalCost += (m * (n * (n + 1))) / 2\r\n\r\n return minimalCost\r\n}"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0, m = 0;\n for(i = 1; i <= t; i++){\n var a = lines[i].split(' ').map(Number);\n n = a[0], m = a[1];\n var ans = m * (m - 1) / 2 + m * n * (n + 1) / 2;\n console.log(ans);\n }\n});\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar M = nextInt();\r\n\t\tvar output = M * (M + 1) / 2;\r\n\t\toutput += ((N * (N + 1) / 2)) * M;\r\n\t\toutput -= M;\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var t = parseInt(readline());\r\n\r\n for (let i = 0; i < t; i++) {\r\n var x = readline().split(' ');\r\n var n = parseInt(x[0]);\r\n var m = parseInt(x[1]);\r\n\r\n var sum = 0;\r\n sum += (m*(m+1))/2;\r\n sum += m*(n*(n+1))/2;\r\n sum -= m;\r\n\r\n console.log(sum); \r\n\r\n }\r\n}"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\n\r\nconst solve = () => {\r\n const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n,m] = readline().trim().split(\" \").map(cur=>parseInt(cur));\r\n let cnt = Math.floor((m * (m + 1))/2);\r\n for(let i=1;i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction print(val) {\r\n console.log(val);\r\n}\r\n\r\nfunction readInt() {\r\n return parseInt(readline());\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n//#endregion\r\nfunction readInts() {\r\n return readline().split(' ').map(x=>parseInt(x));\r\n}\r\n\r\nfunction autoSum(a1,an,n) {\r\n return (a1+an) * n / 2;\r\n}\r\n\r\nfunction main() {\r\n let t = readInt();\r\n while(t-- > 0) {\r\n let [n,m] = readInts();\r\n print(autoSum(1,m,m) + autoSum(m,n*m,n) - m);\r\n }\r\n}\r\n"}, {"source_code": "/**\n * Format:\n * {type: 'number', namedVariable?: string }\n * {type: 'repeat', instructionCount: number, count: number, namedVariable?: string }\n * {type: 'array', namedVariable?: string }\n * {type: 'string', namedVariable?: string }\n */\n const readline = require('readline');\n\n function createCLIReader(instructions) {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const mappedVariables = {};\n\n let resolvePromise = null;\n const donePromise = new Promise((res, rej) => {\n resolvePromise = res;\n });\n\n function waitUntilDone() {\n return donePromise;\n }\n\n /**\n * {type: 'repeat', count: number, iteration: number, basePointer: number, pointer: number, instructionCount: number, context: array }\n */\n const stack = [];\n let pc = -1;\n\n function finished() {\n if (pc >= instructions.length) {\n return true;\n }\n return false;\n }\n\n function checkFinished() {\n // console.log(`Finish check ${pc}, ${JSON.stringify(stack)}, ${pc >= instructions.length}, ${stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1}`);\n if (pc >= instructions.length) {\n return true;\n }\n if (stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1) {\n return true;\n }\n return false;\n }\n\n function getNextInstructionContext() {\n if (!stack.length) {\n return {\n index: ++pc,\n }\n }\n const lastStack = stack[stack.length - 1];\n if (lastStack.pointer === lastStack.instructionCount) {\n lastStack.pointer = 0;\n lastStack.iteration = lastStack.iteration + 1;\n }\n if (lastStack.count === lastStack.iteration) {\n stack.pop();\n pc = lastStack.basePointer + lastStack.instructionCount + 1;\n return {\n index: pc,\n }\n }\n\n lastStack.pointer = lastStack.pointer + 1;\n return {\n index: lastStack.basePointer + lastStack.pointer,\n context: {\n namedPath: [...lastStack.context.namedPath, lastStack.iteration]\n }\n }\n }\n\n function pushRepeatToStack(instruction, index, context) {\n stack.push({\n type: 'repeat',\n count: typeof instruction.count === 'number' ? instruction.count : context && context.namedPath ? getIn(mappedVariables, [...context.namedPath, instruction.count]) : mappedVariables[instruction.count],\n iteration: 0,\n basePointer: index,\n pointer: 0,\n instructionCount: instruction.instructionCount,\n context: {\n namedPath: context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable],\n }\n })\n setIn(mappedVariables, context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable], []);\n }\n\n function nextInstruction() {\n if (finished()) {\n // console.warn('Calling nextInstruction after finished, something is wrong');\n return;\n }\n while (true) {\n const { index, context } = getNextInstructionContext();\n const instruction = instructions[index];\n\n // console.log(`Debugging: ${index}, ${JSON.stringify(context)}, ${JSON.stringify(instruction)}`);\n switch (instruction.type) {\n case 'number':\n case 'array':\n case 'string':\n return {\n ...instruction,\n namedPath: instruction.namedVariable ? context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable] : undefined,\n }\n case 'repeat':\n pushRepeatToStack(instruction, index, context);\n break;\n default:\n // console.warn('Unclear instruction, abort');\n return;\n }\n }\n }\n\n function getIn(object, path) {\n for (let i = 0; i < path.length; ++i) {\n object = object[path[i]];\n }\n return object;\n }\n\n function setIn(object, path, value) {\n for (let i = 0; i < path.length - 1; ++i) {\n if (object[path[i]] == null) {\n object[path[i]] = {};\n }\n object = object[path[i]];\n }\n object[path[path.length - 1]] = value;\n }\n\n rl.on('line', line => {\n if (finished()) {\n return;\n }\n const { type, namedPath } = nextInstruction();\n switch (type) {\n case 'number':\n if (namedPath) {\n setIn(mappedVariables, namedPath, parseInt(line));\n }\n break;\n case 'string':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim());\n }\n break;\n case 'array':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim().split(' ').map(x => parseInt(x)));\n }\n break;\n default:\n // console.warn(`Value unread, received type ${type}.`);\n }\n\n if (checkFinished()) {\n resolvePromise(mappedVariables);\n rl.close();\n }\n });\n return {\n waitUntilDone,\n };\n }\n\n function solve(testCase) {\n const n = testCase.nAndM[0];\n const m = testCase.nAndM[1];\n return (m * (m - 1) / 2) + (n * (n + 1) / 2 * m);\n }\n\n (async function main() {\n const reader = createCLIReader([\n { type: 'number', namedVariable: 'numberOfTestCase' },\n { type: 'repeat', instructionCount: 1, count: 'numberOfTestCase', namedVariable: 'testCase' },\n { type: 'array', namedVariable: 'nAndM' },\n ]);\n const schema = await reader.waitUntilDone();\n\n for (let i = 0; i < schema.numberOfTestCase; ++i) {\n console.log(solve(schema.testCase[i]));\n }\n })();\n"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var t = parseInt(readline());\r\n\r\n for (let i = 0; i < t; i++) {\r\n var x = readline().split(' ');\r\n var n = parseInt(x[0]);\r\n var m = parseInt(x[1]);\r\n\r\n var sum = 0;\r\n for (let j = 0; j < m; j++) {\r\n sum += (j+1);\r\n }\r\n for (let j = 0; j < n; j++) {\r\n sum += m*(j+1);\r\n }\r\n sum -= m;\r\n\r\n console.log(sum); \r\n\r\n }\r\n}"}, {"source_code": "const process = require(\"process\");\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet line = \"\";\n\nprocess.stdin.on(\"data\", (data) => {\n line += data + \"\\n\";\n});\n\nprocess.stdin.on(\"end\", () => {\n line = line.trim().split(\"\\n\");\n main();\n});\n\nfunction main() {\n const t = Number(line[0]);\n // console.log(t);\n let j = 1;\n\n while (j < t + 1) {\n const [n, m] = line[j++].split(\" \");\n solve(Number(n), Number(m));\n }\n}\n\nfunction solve(m, n) {\n let val = n,\n sum = (n * (n + 1)) / 2;\n val = 2 * val;\n\n let i = 1;\n\n while (i < m) {\n sum += val;\n val = val + n;\n i++;\n }\n\n console.log(sum);\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction findKthLargest(nums, k) {\n k = nums.length - k;\n const quickSelect = (l, r) => {\n let pivot = nums[r];\n let p = l;\n for (let i = l; i < r; i++) {\n if (nums[i] <= pivot) {\n swapper(nums, p, i);\n p++;\n }\n }\n swapper(nums, p, r);\n\n if (p > k) return quickSelect(l, p - 1);\n else if (p < k) return quickSelect(p + 1, r);\n else return nums[p];\n };\n\n return quickSelect(0, nums.length - 1);\n};\n\nfunction swapper(array, a, b) {\n const temp = array[b];\n array[b] = array[a];\n array[a] = temp;\n};\n\nfunction main() {\n const t = readline() - 1;\n for (var l = 0; l <= t; l++) {\n const [n, m] = readline().split(' ').map(r => (r) - 0);\n if (m == 1) {\n const x = n * (n + 1) / 2;\n foo(String(x));\n }\n else {\n const x = m * (m + 1) / 2;\n const y = (2*m + (n-1)*m) * n/ 2;\n foo(String(x+y-m));\n }\n }\n}\nfunction foo(x) {\n process.stdout.write(x); // without auto '\\n' (newline)\n console.log(); // with auto '\\n' (newline)\n}\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n//\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n//\r\nprocess.stdin.on(\"data\", (rawData) => {\r\n standardInputString += rawData;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n standardInputString = standardInputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((line) => {\r\n return line.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\nfunction print(data) {\r\n console.log(data);\r\n}\r\n\r\n//line to array of integers\r\n//readline().split(' ').map(Number)\r\n// let iter=parseInt(readline())\r\n//multiple integer construction->const [a,b,c]=integer array\r\n\r\nfunction main() {\r\n let q = parseInt(readline());\r\n for (let i = 0; i < q; i++) {\r\n let nm = readline().split(\" \").map(Number);\r\n print(Easy(nm[0], nm[1]));\r\n }\r\n}\r\nfunction Easy(n, m) {\r\n let nth = n;\r\n let a = m;\r\n let d = m;\r\n let sum = (nth / 2) * (2 * a + (nth - 1) * d);\r\n let sum2 = (m * (m + 1)) / 2;\r\n return sum + sum2 - m;\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n const [rows, cols] = readline().split(' ').map(Number);\r\n let sum = 0;\r\n for (let m = 0; m < cols; m++) {\r\n sum += m + 1;\r\n }\r\n for (let n = 1; n < rows; n++) {\r\n sum += (n + 1) * cols;\r\n }\r\n\r\n output(sum);\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m) {\r\n return m * (m - 1) / 2 + m * n * (n + 1) / 2;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, m);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "var q = Number(readline());\r\nwhile(q--) {\r\n var s=readline().split(\" \");\r\n var n=Number(s[0]);\r\n var m=Number(s[1]);\r\n var tot=0;\r\n for(i=1;i<=m;++i)\r\n tot+=i;\r\n for(i=2;i<=n;++i)\r\n tot+=(i-1)*m+m;\r\n print(tot);\r\n}"}], "negative_code": [{"source_code": "const readline = require('readline').createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n})\r\n\r\n// multi line input\r\nreadline.on('line', (line) => {\r\n if (line.length > 1) {\r\n let [n, m] = line.split(' ').map(Number)\r\n console.log(optimalPath(n, m))\r\n }\r\n})\r\n\r\nlet optimalPath = (n, m) => {\r\n let minimalCost = (m * (m - 1)) / 2\r\n\r\n minimalCost += (m * (n * (n + 1))) / 2\r\n\r\n return minimalCost\r\n}"}], "src_uid": "7d774a003d2e3e8ae6fe1912b3998c96"} {"nl": {"description": "Suppose you have a special $$$x$$$-$$$y$$$-counter. This counter can store some value as a decimal number; at first, the counter has value $$$0$$$. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either $$$x$$$ or $$$y$$$ to its value. So all sequences this counter generates are starting from $$$0$$$. For example, a $$$4$$$-$$$2$$$-counter can act as follows: it prints $$$0$$$, and adds $$$4$$$ to its value, so the current value is $$$4$$$, and the output is $$$0$$$; it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$8$$$, and the output is $$$04$$$; it prints $$$8$$$, and adds $$$4$$$ to its value, so the current value is $$$12$$$, and the output is $$$048$$$; it prints $$$2$$$, and adds $$$2$$$ to its value, so the current value is $$$14$$$, and the output is $$$0482$$$; it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$18$$$, and the output is $$$04824$$$. This is only one of the possible outputs; for example, the same counter could generate $$$0246802468024$$$ as the output, if we chose to add $$$2$$$ during each step.You wrote down a printed sequence from one of such $$$x$$$-$$$y$$$-counters. But the sequence was corrupted and several elements from the sequence could be erased.Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string $$$s$$$ — the remaining data of the sequence. For all $$$0 \\le x, y < 10$$$, calculate the minimum number of digits you have to insert in the string $$$s$$$ to make it a possible output of the $$$x$$$-$$$y$$$-counter. Note that you can't change the order of digits in string $$$s$$$ or erase any of them; only insertions are allowed.", "input_spec": "The first line contains a single string $$$s$$$ ($$$1 \\le |s| \\le 2 \\cdot 10^6$$$, $$$s_i \\in \\{\\text{0} - \\text{9}\\}$$$) — the remaining data you have. It's guaranteed that $$$s_1 = 0$$$.", "output_spec": "Print a $$$10 \\times 10$$$ matrix, where the $$$j$$$-th integer ($$$0$$$-indexed) on the $$$i$$$-th line ($$$0$$$-indexed too) is equal to the minimum number of digits you have to insert in the string $$$s$$$ to make it a possible output of the $$$i$$$-$$$j$$$-counter, or $$$-1$$$ if there is no way to do so.", "sample_inputs": ["0840"], "sample_outputs": ["-1 17 7 7 7 -1 2 17 2 7 \n17 17 7 5 5 5 2 7 2 7 \n7 7 7 4 3 7 1 7 2 5 \n7 5 4 7 3 3 2 5 2 3 \n7 5 3 3 7 7 1 7 2 7 \n-1 5 7 3 7 -1 2 9 2 7 \n2 2 1 2 1 2 2 2 0 1 \n17 7 7 5 7 9 2 17 2 3 \n2 2 2 2 2 2 0 2 2 2 \n7 7 5 3 7 7 1 3 2 7"], "notes": "NoteLet's take, for example, $$$4$$$-$$$3$$$-counter. One of the possible outcomes the counter could print is $$$0(4)8(1)4(7)0$$$ (lost elements are in the brackets).One of the possible outcomes a $$$2$$$-$$$3$$$-counter could print is $$$0(35)8(1)4(7)0$$$.The $$$6$$$-$$$8$$$-counter could print exactly the string $$$0840$$$."}, "positive_code": [{"source_code": "(function() {\nvar INPUT = ``;\nvar OUTPUT = ``;\n\nvar main = function() {\"use strict\";\n // TODO\n var s = rdS().split('').map(v => +v);\n var R = crAr(10).map(v => crAr(10));\n \n var foo = function(x, y) {\n //pr('x,y: ', x,y);\n var G = crAr(10).map(v => []);\n var P = crAr(10).map(v => crAr(10, null));\n\n var path = function(v1, v2) {\n //pr('v1, v2:', v1, v2)\n if (P[v1][v2] !== null) {\n return P[v1][v2];\n }\n //pr('opop')\n var res = -1;\n var Q = [v1];\n var was = crAr(10, null);\n was[v1] = 0;\n var p = 0;\n //pr('was', was)\n while (p < Q.length) {\n //prAr(Q)\n var curV = Q[p];\n var curL = was[curV];\n for (var i = 0; i < G[curV].length; ++i) {\n var nextV = G[curV][i];\n //pr(nextV)\n if (nextV === v2) {\n //pr('opop2')\n return P[v1][v2] = curL + 1;;\n break;\n } else if (was[nextV] === null) {\n //pr('opop3')\n Q.push(nextV);\n was[nextV] = curL + 1;\n //prAr(Q);\n //pr('was', was)\n }\n }\n //pr(Q.length);\n \n ++p;\n }\n \n return P[v1][v2] = res;\n };\n \n for (var k = 0; k < 10; ++k) {\n G[k].push( (k+x)%10 );\n G[k].push( (k+y)%10 );\n }\n //prAr(G);\n \n var res = 0;\n //prAr(s)\n for (var k = 1; k < s.length; ++k) {\n var d1 = s[k-1];\n var d2 = s[k];\n //pr('d1,d2: ', d1,d2);\n \n var L = path(d1, d2);\n //pr('L: ', L)\n if (L === -1) {\n return -1;\n }\n res += L - 1;\n }\n \n return res;\n };\n \n //foo(0, 1);\n //return;\n \n for (var i = 0; i < 10; ++i) {\n for (var j = i; j < 10; ++j) {\n var res = foo(i, j);\n R[i][j] = R[j][i] = res;\n }\n }\n \n for (var i = 0; i < R.length; ++i) {\n prAr(R[i]);\n }\n};\n\nif(INPUT){INPUT=INPUT.split('\\n').reverse();\nreadline=()=>INPUT.pop();\nwrite=(...s)=>{OUTPUT+=[...s].join(' ')};\nprint=(...s)=>{write(...s);OUTPUT+='\\n'};}\nconst\nrdS=readline,\nrdN=()=>+rdS(),\nrdArS=()=>rdS().split(' '),\nrdArN=()=>rdArS().map(v=>+v),\nwr=write,\npr=print,\nprAr=(a)=>pr(...a),\nprOb=(o)=>pr(JSON.stringify(o,null,4)),\ncrAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},\ngetPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},\ndefineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});\ndefineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});\ndefineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});\n\nmain();\nreturn OUTPUT;\n})();"}], "negative_code": [], "src_uid": "2ebfcb54231d115a4aa9e5fc52b4ebe7"} {"nl": {"description": "Polycarp is sad — 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$$$) — 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$$$) — the number of red, green and blue lamps in the set, respectively.", "output_spec": "Print $$$t$$$ lines — 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": "function main() {\n var testCasesNum = +readline();\n var testCases = [];\n for (var i = 0; i < testCasesNum; i++) {\n (function (i) {\n testCases[i] = readline();\n canPay(testCases[i]);\n })(i)\n }\n}\n\nfunction canPay(testCase) {\n var caseArr = testCase.split(' ').map(Number);\n var r = +caseArr[0];\n var g = +caseArr[1];\n var b = +caseArr[2];\n if ((r >= g && r >= b && r <= g + b + 1) ||\n (g >= r && g >= b && g <= r + b + 1) ||\n (b >= g && b >= r && b <= g + r + 1)) {\n print(\"Yes\")\n } else {\n print(\"No\")\n }\n}\n\nmain()"}, {"source_code": "'use strict';\n\nlet col = +readline();\n\nlet strings = [];\nfor (let i = 0; i < col; i++){\n\tstrings[i] = readline();\n\tstrings[i] = strings[i].split(\" \").map(function(item) {\n\t\treturn +item;\n\t});\n}\n\nfunction yesNo(arr) {\n\tlet max = 0;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (max <= arr[i]) {\n\t\t\tmax = arr[i];\n\t\t}\n\t}\n\tlet sum = arr[0] + arr[1] + arr[2];\n\tif (max - 1 > (sum - max)) {\n\t\treturn 'No\\n';\n\t} else {\n\t\treturn 'Yes\\n';\n\t}\n}\n\nfor (let i = 0; i < col; i++) {\n\tlet res = yesNo(strings[i]);\n\tprint(res);\n}\n\n\n\n"}, {"source_code": "var t = parseInt(readline(), 10),\n inp = [];\n\nfor(var i=1; i<=t; i++) {\n inp = readline().split(' ').map(el => parseInt(el, 10));\n r = inp[0];\n g = inp[1];\n b = inp[2];\n \n if(r>=g && r>=b) {\n if(g+b >= r-1) print('YES');\n else print('NO');\n } else if(g>=r && g>=b) {\n if(r+b >= g-1) print('YES');\n else print('NO');\n } else if(b>=r && b>=g) {\n if(r+g >= b-1) print('YES');\n else print('NO');\n }\n}"}, {"source_code": "let input = \"\";\nconst { EOL } = require(\"os\");\nprocess.stdin.on(\"data\", i => (input += i));\n\nprocess.stdin.on(\"end\", func);\n\nasync function func() {\n const [t, ...queries] = input.split(EOL);\n for (let i = 0; i < t; i++) {\n const [r, g, b] = queries.shift().split(\" \").map(a => parseInt(a));\n if (r + g + 1 < b || r + b + 1 < g || g + b + 1 < r) {\n console.log('No')\n } else {\n console.log('Yes')\n }\n }\n}\n\nmodule.exports = func;\n"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let i = 0; i < t; i++) {\n const r = arr[i].split(' ').map(a => parseInt(a))\n sort(r)\n if(r[2] - r[1] - r[0] > 1) wr('No')\n else wr('Yes')\n }\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction max(...x) {\n return Math.max(...x)\n}\n\nfunction min(...x) {\n return Math.min(...x)\n}\n\nfunction mod(a, m) {\n let x = a % m\n if(x >= 0 ) return x\n else return m + x \n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n↑入力 ↓出力');\n Main();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var tmp = nextIntArray();\n tmp.sort(function(a,b){\n \treturn b - a;\n });\n var max = tmp[0];\n var mins = tmp[1] + tmp[2];\n \n if(max - mins < 2){\n output[i] = \"Yes\";\n }else{\n output[i] = \"No\";\n }\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n arr.sort((a, b) => a - b);\n const r = arr[2] - arr[1] - arr[0];\n\n if (r > 1) {\n console.log('NO');\n }\n else {\n console.log('YES');\n }\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = 3\n\t\ti++\n\t\treturn\n\t}\n\tlet inputarr = input.split(' ')\n\n\tlet r = parseInt(inputarr[0])\n\tlet g = parseInt(inputarr[1])\n\tlet b = parseInt(inputarr[2])\n\t\n\tlet arr = [r, g, b]\n\n\tarr.sort(function(a,b) {\n\t\treturn a-b\n\t\n\t})\n\tif(arr[1]+arr[0] < arr[2] - 1){\n\n\t\tconsole.log(\"No\")\n\t}\n\telse\n\t{\n\t\tconsole.log(\"Yes\")\n\t}\n\n}\n"}, {"source_code": "let finalInput = '';\n\nprocess.stdin.setEncoding('utf-8').on('data', input => {\n finalInput += input;\n});\n\nprocess.stdin.setEncoding('utf-8').on('end', () => {\n let lines = finalInput.split('\\r\\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);\n lines.forEach(line => {\n let values = line.split(' ').map(Number).sort((a, b) => a - b);\n let result = values[2] - values[0] - values[1] <= 1;\n console.log(result ? 'Yes' : 'No');\n });\n});"}, {"source_code": "let fs = require(\"fs\");\n\nlet txt = fs.readFileSync(0, \"utf-8\").split(\"\\r\\n\").filter(data => {\n return data.length > 0;\n});\ntxt.shift();\nfor (let i = 0; i < txt.length; i++) {\n doit(txt[i].split(\" \").filter(data=>data.length>0).map(data=>data*1));\n}\n\nfunction doit(tab) {\n let max=tab.indexOf(Math.max(...tab));\n let score=0;\n tab.forEach((data,index)=>{\n if(index!=max)score+=data;\n });\n if(score>=tab[max]-1){\n console.log(\"YES\");\n }else{\n console.log(\"NO\");\n \n }\n}"}], "negative_code": [{"source_code": "\"use strict\";\n\nlet col = +readline();\n\nlet strings = [];\nfor (let i = 0; i < col; i++){\n\tstrings[i] = readline();\n\tstrings[i] = strings[i].split(\" \").map(function(item) {\n\t\treturn +item;\n\t});\n}\n\nfunction yesNo(arr) {\n\tlet max = 0;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (max <= arr[i]) {\n\t\t\tmax = arr[i];\n\t\t}\n\t}\n\tlet sum = arr[0] + arr[1] + arr[2];\n\tif ((sum - max) < max) {\n\t\treturn 'No\\n';\n\t} else {\n\t\treturn 'Yes\\n';\n\t}\n}\n\nfor (let i = 0; i < col; i++) {\n\tlet res = yesNo(strings[i]);\n\tprint(res);\n}\n"}, {"source_code": "'use strict';\n\nlet col = +readline();\n\nlet strings = [];\nfor (let i = 0; i < col; i++){\n\tstrings[i] = readline();\n\tstrings[i] = strings[i].split(\" \").map(function(item) {\n\t\treturn +item;\n\t});\n}\n\nfunction yesNo(arr) {\n\tlet max = 0;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (max <= arr[i]) {\n\t\t\tmax = arr[i];\n\t\t}\n\t}\n\tlet sum = arr[0] + arr[1] + arr[2];\n\tif ((sum - max) <= max - 1) {\n\t\treturn 'No\\n';\n\t} else {\n\t\treturn 'Yes\\n';\n\t}\n}\n\nfor (let i = 0; i < col; i++) {\n\tlet res = yesNo(strings[i]);\n\tprint(res);\n}\n\n\n\n"}, {"source_code": "\"use strict\";\n\nvar col = +readline();\n\nvar strings = [];\nfor (var i = 0; i < col; i++){\n\tstrings[i] = readline();\n\tstrings[i] = strings[i].split(\" \").map(function(item) {\n\t\treturn +item;\n\t});\n}\n\nfunction yesNo(arr) {\n\tlet max = 0;\n\tfor (var i = 0; i < 3; i++) {\n\t\tif (max < arr[i]) {\n\t\t\tmax = arr[i];\n\t\t}\n\t}\n\tvar sum = arr[0] + arr[1] + arr[2];\n\tif ((sum - max) < max) {\n\t\treturn 'No';\n\t} else if ((sum - max) >= max) {\n\t\treturn 'Yes';\n\t}\n}\n\nfor (var i = 0; i < col; i++) {\n\tprint(yesNo(strings[i]));\n}"}, {"source_code": "\"use strict\";\n\nvar col = +readline();\n\nvar strings = [];\nfor (var i = 0; i < col; i++){\n\tstrings[i] = readline();\n\tstrings[i] = strings[i].split(\" \").map(function(item) {\n\t\treturn +item;\n\t});\n}\n\nfunction yesNo(arr) {\n\tlet max = 0;\n\tfor (var i = 0; i < 3; i++) {\n\t\tif (max < arr[i]) {\n\t\t\tmax = arr[i];\n\t\t}\n\t}\n\tvar sum = arr[0] + arr[1] + arr[2];\n\tif ((sum - max) < max) {\n\t\treturn 'No\\n';\n\t} else {\n\t\treturn 'Yes\\n';\n\t}\n}\n\nfor (var i = 0; i < col; i++) {\n\tprint(yesNo(strings[i]));\n}"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let i = 0; i < t; i++) {\n const [r, g, b] = arr[i].split(' ').map(a => parseInt(a))\n if(r >= g && r >= b && b + g >= r) {\n wr('Yes')\n }\n else if(g >= r && g >= b && b + r >= g) {\n wr('Yes')\n }\n else if(b >= r && b >= g && g + r >= b) {\n wr('Yes')\n }\n else wr('No')\n }\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction max(...x) {\n return Math.max(...x)\n}\n\nfunction min(...x) {\n return Math.min(...x)\n}\n\nfunction mod(a, m) {\n let x = a % m\n if(x >= 0 ) return x\n else return m + x \n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n const min = Math.min(...arr);\n const max = Math.max(...arr);\n\n if (max - min > 1) {\n console.log('NO');\n }\n else {\n console.log('YES');\n }\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = 3\n\t\ti++\n\t\treturn\n\t}\n\tarr = []\n\tlet inputarr = input.split(' ')\n\n\tlet r = inputarr[0]\n\tlet g = inputarr[1]\n\tlet b = inputarr[2]\n\t\n\tconst res = Math.abs((r-g-b))\n\t\n\tconsole.log(res > 3 ? \"NO\" : \"YES\")\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = 3\n\t\ti++\n\t\treturn\n\t}\n\tarr = []\n\tlet inputarr = input.split(' ')\n\n\tlet r = parseInt(inputarr[0])\n\tlet g = parseInt(inputarr[1])\n\tlet b = parseInt(inputarr[2])\n\n\t\n\tif(r === g){\n\t\tif(r > b){\n\t\t\tconsole.log(\"No\")\n\t\t\treturn\n\t\t}\n\t}\n\t\n\tif(g === b){\n\t\tif(g > r){\n\t\t\tconsole.log(\"No\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tif(r === b){\n\t\tif(r > b){\n\t\t\tconsole.log(\"No\")\n\t\t\treturn\n\t\t} \n\t}\n\n\tconst res = Math.abs((r-g-b))\n\t\t\t\n\tconsole.log(res > 3 ? \"No\" : \"Yes\")\n\n\n\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = 3\n\t\ti++\n\t\treturn\n\t}\n\tarr = []\n\tlet inputarr = input.split(' ')\n\n\tlet r = inputarr[0]\n\tlet g = inputarr[1]\n\tlet b = inputarr[2]\n\n\n\tif(r === g){\n\t\tif(r > b){\n\t\t\tconsole.log(\"NO\")\n\t\t\treturn\n\t\t}\n\t}\n\t\n\tif(g === b){\n\t\tif(g > r){\n\t\t\tconsole.log(\"NO\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tif(r === b){\n\t\tif(r > b){\n\t\t\tconsole.log(\"NO\")\n\t\t\treturn\n\t\t} \n\t}\n\n\tconst res = Math.abs((r-g-b))\n\t\t\t\n\tconsole.log(res > 3 ? \"NO\" : \"YES\")\n\n\n\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = 3\n\t\ti++\n\t\treturn\n\t}\n\tarr = []\n\tlet inputarr = input.split(' ')\n\n\tlet r = inputarr[0]\n\tlet g = inputarr[1]\n\tlet b = inputarr[2]\n\n\tif(r === b || r === g || g === b){\n\t\tconsole.log(\"NO\")\n\t}\n\n\tconsole.log(r-b-g)\n\tconst res = Math.abs((r-g-b))\n\t\t\t\n\tconsole.log(res > 3 ? \"NO\" : \"YES\")\n\n\n\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = 3\n\t\ti++\n\t\treturn\n\t}\n\tarr = []\n\tlet inputarr = input.split(' ')\n\n\tlet r = inputarr[0]\n\tlet g = inputarr[1]\n\tlet b = inputarr[2]\n\t\n\tconst res = Math.abs((r-g-b))\n\t\n\tconsole.log(res >= 3 ? \"NO\" : \"YES\")\n\n\n\n}\n"}], "src_uid": "34aa41871ee50f06e8acbd5eee94b493"} {"nl": {"description": "Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string $$$s$$$ he found is a binary string of length $$$n$$$ (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters $$$s_i$$$ and $$$s_{i+1}$$$, and if $$$s_i$$$ is 1 and $$$s_{i + 1}$$$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $$$s$$$ as clean as possible. He thinks for two different strings $$$x$$$ and $$$y$$$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer $$$t$$$ test cases: for the $$$i$$$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings $$$x$$$ and $$$y$$$ of the same length then $$$x$$$ is lexicographically smaller than $$$y$$$ if there is a position $$$i$$$ such that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$.", "input_spec": "The first line contains the integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. Next $$$2t$$$ lines contain test cases — one per two lines. The first line of each test case contains the integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) — the length of the string $$$s$$$. The second line contains the binary string $$$s$$$. The string $$$s$$$ is a string of length $$$n$$$ which consists only of zeroes and ones. It's guaranteed that sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$t$$$ answers — one per test case. The answer to the $$$i$$$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).", "sample_inputs": ["5\n10\n0001111111\n4\n0101\n8\n11001101\n10\n1110000000\n1\n1"], "sample_outputs": ["0001111111\n001\n01\n0\n1"], "notes": "NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase $$$s_2$$$.In the third test case, Lee can make moves, for example, in the following order: 11001101 $$$\\rightarrow$$$ 1100101 $$$\\rightarrow$$$ 110101 $$$\\rightarrow$$$ 10101 $$$\\rightarrow$$$ 1101 $$$\\rightarrow$$$ 101 $$$\\rightarrow$$$ 01."}, "positive_code": [{"source_code": "function solve() {\n var T = Number(read());\n for (var t = 0; t < T; t++) {\n var n = Number(read());\n var s = read();\n var firstOne = s.indexOf('1');\n var lastZero = s.lastIndexOf('0');\n if (firstOne < lastZero && firstOne !== -1) {\n s = s.substr(0, firstOne) + s.substr(lastZero);\n }\n write(s);\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n\n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n\n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n solve();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n\n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n\n RL.on('close', solve);\n }\n} else {\n solve();\n}\n\nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let _ = +readLine();\n let str = readLine();\n let countZero = 0;\n let countOne = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === \"0\") {\n countZero++;\n } else {\n break;\n }\n }\n for (let i = str.length - 1; i >= 0; i--) {\n if (str[i] === \"1\") {\n countOne++;\n } else {\n break;\n }\n }\n if (countOne + countZero === str.length) {\n console.log(str);\n } else {\n console.log(`${\"0\".repeat(countZero)}0${\"1\".repeat(countOne)}`);\n }\n }\n}\n"}, {"source_code": "var data = '';\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', (buffer) =>\n{\n data += buffer;\n});\n\nprocess.stdin.on('end', () =>\n{\n var x = data.split(/\\s+/);\n var i = 1;\n\n for (var cas = 0; cas < x[0]; cas++, i += 2)\n {\n var n = x[i];\n var res = '';\n var str = x[i + 1];\n var len = str.length;\n var left = 0, right = len - 1;\n for (; left < len && str[left] == '0'; left++);\n for (; right >= 0 && str[right] == '1'; right--);\n for (var j = 0; j < left; j++) res += '0';\n if (left < right) res += '0';\n for (var j = right + 1; j < len; j++) res += '1';\n console.log(res);\n }\n});"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet input = '';\nprocess.stdin.on('data', (line) => {\n input += line;\n});\nprocess.stdin.on('end', () => {\n const lines = input.split('\\n');\n let tests = parseInt(lines.shift(), 10);\n while (tests--) {\n lines.shift();\n const s = lines.shift();\n let zeroCount = 0;\n let ans = [...s]\n .reverse()\n .reduce((acc, char) => {\n if (char === '0') {\n zeroCount++;\n }\n else if (zeroCount) {\n zeroCount = 1;\n }\n else {\n acc += char;\n }\n return acc;\n }, '');\n ans += '0'.repeat(zeroCount);\n console.log([...ans].reverse().join(''));\n }\n});\n// input helper\nfunction lineToNumArray(line) {\n return line.split(' ').map(element => parseInt(element, 10));\n}\n"}, {"source_code": "const processData = (lines) => {\n let acc = 0\n const n = +lines[acc]\n acc++\n for (let i=0; i= right) {\n console.log(l)\n } else {\n // console.log('left', l.slice(0, left))\n // console.log('right', l.slice(right))\n console.log(l.slice(0, left) + '0' + l.slice(right))\n }\n\n //\n // const zeroPoint = l.indexOf('0')\n // const onePoint = l.indexOf('1')\n // const secondZeroPoint = l.indexOf('0', onePoint)\n //\n // if (zeroPoint === 0) {\n // if (secondZeroPoint > 0) {\n // console.log(l.slice(0, onePoint) + '0')\n // } else {\n // console.log(l)\n // }\n // } else {\n // if (zeroPoint > 0 ) {\n // console.log('0')\n // } else {\n // console.log(l)\n // }\n // }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "var t = parseInt(readline());\n\nwhile(t--){\n var n = parseInt(readline());\n var str = readline();\n \n var cur = 0;\n var isDesc = false;\n while(cur + 1 < n){\n if(str[cur] == '1' && str[cur + 1] == '0'){\n isDesc = true;\n break;\n }\n cur++;\n }\n \n\n if(isDesc) {\n var newstr = \"\";\n leadZ = 0;\n while(leadZ < n && str[leadZ] == '0')\n leadZ++;\n leadZ++;\n sufO = 0;\n while(sufO < n && str[n - 1 - sufO] == '1')\n sufO++;\n \n while(leadZ--)\n newstr += \"0\";\n\n while(sufO--)\n newstr += \"1\";\n\n print(newstr);\n } else {\n print(str);\n }\n \n}"}, {"source_code": "function solve() {\n var T = Number(read());\n for (var t = 0; t < T; t++) {\n read();\n var s = read();\n var firstOne = s.indexOf('1');\n var lastZero = s.lastIndexOf('0');\n if (firstOne < lastZero && firstOne !== -1) {\n s = s.substr(0, firstOne) + s.substr(lastZero);\n }\n write(s);\n }\n}\n \n \nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n \n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n \n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n solve();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', solve);\n }\n} else {\n solve();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}"}], "negative_code": [], "src_uid": "bb071f1f4fc1c129a32064c1301f4942"} {"nl": {"description": "Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.", "input_spec": "The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.", "output_spec": "In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them.", "sample_inputs": ["3 2", "5 3"], "sample_outputs": ["2\n1 2\n2 3", "3\n1 2\n2 3\n3 4\n3 5"], "notes": "NoteIn the first example the only network is shown on the left picture.In the second example one of optimal networks is shown on the right picture.Exit-nodes are highlighted. "}, "positive_code": [{"source_code": "var s=readline().split(' ')\nvar n=+s[0]\nvar k=+s[1]\nvar dist=[]\ndist.length=n+1\nvar q=[]\ndist[1]=0\nvar res=[]\nfor (var i=2;i<=k+1;i++)\n{\n dist[i]=1\n res.push(\"1 \"+i)\n}\nfor (var i=2;i<=n;i++)\n{\n if (i+k<=n)\n {\n res.push(i+' '+(i+k))\n dist[i+k]=1+dist[i]\n }\n else{q.push(dist[i]);}\n}\nprint(q[q.length-1]+q[q.length-2])\nfor (var i=0;i 1 && d === 0) return 'No solution';\n\tvar ans = [d];\n\tk--;\n\twhile (k--)\n\t\tans.push('0');\n\treturn ans.join('');\n} .apply(0, readline().split(' ').map(Number)));"}, {"source_code": ";(function () {\n\n\tprint((function (k, d) {\n\t\tk = +k;\n\t\tif (d === '0' && k > 1) return 'No solution';\n\t\tfor (var i = 1; i < k; i++) d += '0';\n\t\treturn d;\n\t}).apply(this, readline().split(' ')));\n\n}).call(this);"}, {"source_code": ";(function () {\n\n\tprint((function (k, d) {\n\t\tk = +k;\n\t\tif (d === '0' && k > 1) return 'No solution';\n\t\tfor (var i = 1; i < k; i++) d += '0';\n\t\treturn d;\n\t}).apply(this, readline().split(' ')));\n\n}).call(this);"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\n\tfunction solve(numDigits, digitalRoot) {\n\t\tif (digitalRoot == 0) {\n\t\t\tprint(numDigits == 1 ? 0 : \"No solution\");\n\t\t\treturn;\n\t\t}\n\t\tvar digits = [digitalRoot];\n\t\tfor (var digitIndex = 1; digitIndex < numDigits; ++digitIndex) {\n\t\t\tdigits.push(0);\n\t\t}\n\t\tprint(digits.join(\"\"));\n\t}\n\n\tvar data = tokenizeIntegers(readline());\n\tsolve(data[0], data[1]);\n}\n\nmain();\n"}], "negative_code": [{"source_code": "print(function(k, d) {\n\tif (k === 0 && d > 1) return 'No solution';\n\tvar ans = [d];\n\tk--;\n\twhile (k--)\n\t\tans.push('0');\n\treturn ans.join('');\n} .apply(0, readline().split(' ').map(Number)));\n"}, {"source_code": ";(function () {\n\n\tprint((function (k, d) {\n\t\tfor (var i = 1, k = +k; i < k; i++) d += '0';\n\t\treturn d;\n\t}).apply(this, readline().split(' ')));\n\n}).call(this);"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\n\tfunction solve(numDigits, digitalRoot) {\n\t\tif (digitalRoot == 0) {\n\t\t\tprint(numDigits == 1 ? 0 : \"Impossible\");\n\t\t\treturn;\n\t\t}\n\t\tvar digits = [digitalRoot];\n\t\tfor (var digitIndex = 1; digitIndex < numDigits; ++digitIndex) {\n\t\t\tdigits.push(0);\n\t\t}\n\t\tprint(digits.join(\"\"));\n\t}\n\n\tvar data = tokenizeIntegers(readline());\n\tsolve(data[0], data[1]);\n}\n\nmain();\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$$$) — 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": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n \n \nfunction main() {\n const line = readline();\n var cases = line.split(\" \");\n var n = parseInt(cases[0]);\n var m = parseInt(cases[1]);\n var x = parseInt(cases[2]);\n var y = parseInt(cases[3]);\n pathPrint(n,m,x,y);\n}\n\nfunction pathPrint(n,m,x,y){\n var currX = x;\n var currY = y;\n\n var reachedX = -1;\n var reachedY = -1;\n \n for(var i = currY; i >=1; i--){\n console.log(currX + \" \"+i);\n }\n for(var j = currY+1;j <=m;j++){\n console.log(currX+ \" \"+j);\n }\n\n reachedX = currX;\n reachedY = m;\n\n var rowAbove = currX-1;\n var rowBelow = currX+1;\n\n while(rowAbove>=1 && rowBelow<=n){\n reachedX = rowAbove;\n reachedY = m;\n for(var col1 = reachedY ; col1>=1;col1--){\n console.log(reachedX+ \" \"+col1);\n }\n reachedX = rowBelow;\n reachedY = 1;\n for(var col = 1 ; col<=m;col++){\n console.log(reachedX+ \" \"+col);\n }\n rowAbove--;\n rowBelow++;\n }\n\n if(rowBelow <=n){\n reachedX = rowBelow;\n reachedY = m;\n while(rowBelow <=n){\n reachedX = rowBelow;\n if(reachedY == m){\n for(var col2 = m ; col2>=1;col2--){\n console.log(reachedX+ \" \"+col2);\n }\n reachedY = 1;\n }else{\n for(var col3 = 1 ; col3<=m;col3++){\n console.log(reachedX+ \" \"+col3);\n }\n reachedY = m;\n }\n rowBelow++;\n }\n }\n\n if(rowAbove >=1){\n reachedX = rowAbove;\n reachedY = m;\n while(rowAbove >=1){\n reachedX = rowAbove;\n if(reachedY == m){\n for(var col4 = m ; col4>=1;col4--){\n console.log(reachedX+ \" \"+col4);\n }\n reachedY = 1;\n }else{\n for(var col5 = 1 ; col5<=m;col5++){\n console.log(reachedX+ \" \"+col5);\n }\n reachedY = m;\n }\n rowAbove--;\n }\n }\n}\n\n\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let [rowLen, colLen, x, y] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n for (let row = 0; row < rowLen; row++) {\n for (let col = 0; col < colLen; col++) {\n console.log(`${x} ${y}`);\n y++;\n if (y > colLen) y = 1;\n }\n y--;\n x++;\n if (y === 0) y = colLen;\n if (x > rowLen) x = 1;\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let [rowLen, colLen, x, y] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const visited = {};\n\n for (let i = y; i <= colLen; i++) {\n console.log(`${x} ${i}`);\n }\n for (let i = y - 1; i > 0; i--) {\n console.log(`${x} ${i}`);\n }\n\n let reverse = false;\n\n for (let row = 1; row <= rowLen; row++) {\n for (let col = 1; col <= colLen; col++) {\n if (x === row) {\n reverse = true;\n continue;\n }\n if (!reverse) {\n if (row % 2 !== 0) {\n console.log(`${row} ${col}`);\n } else {\n console.log(`${row} ${colLen + 1 - col}`);\n }\n } else {\n if (row % 2 === 0) {\n console.log(`${row} ${col}`);\n } else {\n console.log(`${row} ${colLen + 1 - col}`);\n }\n }\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n// \tdata = data.split('\\n');\n// \tconst testCases = data[0] * 1;\n// \tlet i = 1;\n// \twhile (i <= testCases) {\n let num = data.trim().split(' ').map(Number);\n let n = num[0];\n let m = num[1];\n let x = num[2];\n let y = num[3];\n console.log(x+' '+y);\n for (let c = m; c >= 1; c -= 1) {\n if (c !== y) console.log(x+' '+c);\n }\n let check = false;\n for (let i = 0; i < n; i++) { \n if (i+1 === x) {check=true; continue;}\n if (check) {\n if (i % 2 !== 0) { \n for (let j = 0; j < m; j++) console.log((i+1)+' '+(j+1)); \n \n // If current row is odd, print from \n // right to left \n } else { \n for (let j = m - 1; j >= 0; j--) \n console.log((i+1)+' '+(j+1));\n } \n }\n // If current row is even, print from \n // left to right \n else {\n if (i % 2 == 0) { \n for (let j = 0; j < m; j++) console.log((i+1)+' '+(j+1)); \n \n // If current row is odd, print from \n // right to left \n } else { \n for (let j = m - 1; j >= 0; j--) \n console.log((i+1)+' '+(j+1));\n }\n }\n \n // i += 1;\n\t}\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const [n, m, sx, sy] = readLine().split(/\\s/).map(Number)\n const visited = Array(n).fill().map(() => [])\n console.log(sx, sy)\n visited[sx - 1][sy - 1] = true\n console.log(1, sy)\n visited[0][sy - 1] = true\n console.log(1, 1)\n visited[0][0] = true\n for (let r = 0; r < n; r++) {\n for (let _c = 0; _c < m; _c++) {\n const c = r % 2 === 0 ? _c : m - 1 - _c\n if (!visited[r][c]) {\n console.log(r + 1, c + 1)\n visited[r][c] = true\n }\n }\n }\n}\n\n"}, {"source_code": "const main = () => {\n const input = readline()\n .split(\" \")\n .map((i) => Number(i));\n\n const N = input[0];\n const M = input[1];\n\n const pos = {\n x: input[2],\n y: input[3],\n };\n\n for (var i = pos.x; i <= N; i++) {\n print(i, pos.y);\n }\n\n for (var i = pos.x - 1; i >= 1; i--) {\n print(i, pos.y);\n }\n\n pos.x = 1;\n\n for (var i = 1; i < pos.y; i++) {\n if (pos.x === 1) {\n for (var j = 1; j <= N; j++) {\n print(j, i);\n }\n\n pos.x = N;\n } else {\n for (var j = N; j >= 1; j--) {\n print(j, i);\n }\n\n pos.x = 1;\n }\n }\n\n for (var i = pos.y + 1; i <= M; i++) {\n if (pos.x === 1) {\n for (var j = 1; j <= N; j++) {\n print(j, i);\n }\n\n pos.x = N;\n } else {\n for (var j = N; j >= 1; j--) {\n print(j, i);\n }\n\n pos.x = 1;\n }\n }\n};\n\nmain();"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let [rowLen, colLen, x, y] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const visited = {};\n\n for (let i = y; i <= colLen; i++) {\n console.log(`${x} ${i}`);\n visited[`${x}_${i}`] = true;\n }\n for (let i = y - 1; i > 0; i--) {\n console.log(`${x} ${i}`);\n visited[`${x}_${i}`] = true;\n }\n\n for (let row = 1; row <= rowLen; row++) {\n for (let col = 1; col <= colLen; col++) {\n if (row % 2 !== 0) {\n !visited[`${row}_${col}`] && console.log(`${row} ${col}`);\n } else {\n !visited[`${row}_${colLen + 1 - col}`] && console.log(`${row} ${colLen + 1 - col}`);\n }\n }\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n const [x, y, a, b] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n const visited = {};\n const arr = [...Array(x).fill(0)].map((_) => Array(y).fill(0));\n arr[a - 1][b - 1] = 1;\n traverse(a - 1, b - 1);\n\n function traverse(a, b) {\n if (a < 0 || a >= x || b < 0 || b >= y || visited[`${a}${b}`]) return;\n\n console.log(`${a + 1} ${b + 1}`);\n\n visited[`${a}${b}`] = 1;\n\n traverse(a, b + 1);\n traverse(a - 1, b);\n traverse(a, b - 1);\n traverse(a + 1, b);\n }\n}\n"}, {"source_code": "const main = () => {\n const input = readline()\n .split(\" \")\n .map((i) => Number(i));\n\n const N = input[0];\n const M = input[1];\n\n const pos = {\n x: input[2],\n y: input[3],\n };\n\n for (var i = pos.x; i <= N; i++) {\n print(i, pos.y);\n }\n\n for (var i = pos.x - 1; i >= 1; i--) {\n print(i, pos.y);\n }\n\n pos.x = 1;\n\n for (var i = 1; i < pos.y; i++) {\n if (pos.x === 1) {\n for (var j = 1; j <= N; j++) {\n print(j, i);\n }\n pos.x = N;\n } else {\n for (var j = N; j >= 1; j--) {\n print(i, j);\n }\n\n pos.x = 1;\n }\n }\n\n for (var i = pos.y + 1; i <= M; i++) {\n if (pos.x === 1) {\n for (var j = 1; j <= N; j++) {\n print(j, i);\n }\n pos.x = N;\n } else {\n for (var j = N; j >= 1; j--) {\n print(i, j);\n }\n\n pos.x = 1;\n }\n }\n};\n\nmain();\n"}], "src_uid": "ed26479cdf72ad9686bbf334d90aa0be"} {"nl": {"description": "You are given a positive integer $$$n$$$. Your task is to find any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \\le a, b, c \\le 10^9$$$) for which $$$(a\\oplus b)+(b\\oplus c)+(a\\oplus c)=n$$$, or determine that there are no such integers.Here $$$a \\oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \\oplus 4 = 6$$$ and $$$3 \\oplus 1=2$$$.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$). ", "output_spec": "For each test case, print any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \\le a, b, c \\le 10^9$$$) for which $$$(a\\oplus b)+(b\\oplus c)+(a\\oplus c)=n$$$. If no such integers exist, print $$$-1$$$.", "sample_inputs": ["5\n\n4\n\n1\n\n12\n\n2046\n\n194723326"], "sample_outputs": ["3 3 1\n-1\n2 4 6\n69 420 666\n12345678 87654321 100000000"], "notes": "NoteIn the first test case, $$$a=3$$$, $$$b=3$$$, $$$c=1$$$, so $$$(3 \\oplus 3)+(3 \\oplus 1) + (3 \\oplus 1)=0+2+2=4$$$.In the second test case, there are no solutions.In the third test case, $$$(2 \\oplus 4)+(4 \\oplus 6) + (2 \\oplus 6)=6+2+4=12$$$."}, "positive_code": [{"source_code": "var limit = parseInt(readline());\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var value = parseInt(readline());\r\n var result = \"\"\r\n if (value % 2 === 0)\r\n {\r\n result = `${value/2} 0 0`;\r\n }\r\n else result = \"-1\"\r\n print(result)\r\n}"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n\tvar t = lines[0];\n\tvar n = 0;\n\tfor(i = 1; i <= t; i++){\n var k = lines[i];\n if(k % 2 === 0){\n console.log(0, k / 2, k / 2);\n }else{\n console.log(-1);\n }\n }\n});\n\n"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var tests = parseInt(readline());\r\n for (let t = 0;t < tests; ++t) {\r\n var x = parseInt(readline());\r\n if (x%2 === 0) {\r\n console.log(x/2,x/2,0);\r\n } else {\r\n console.log(-1);\r\n }\r\n\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n) {\r\n if (n & 1) return -1;\r\n return `0 ${n / 2} ${n / 2}`;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n res[i] = solve(n);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n const n = Number(readline());\r\n\r\n let carry = (a, b, c) => {\r\n return [\r\n '1' + a,\r\n '1' + b,\r\n '0' + c\r\n ];\r\n };\r\n\r\n let dontCarry = (a, b, c) => {\r\n return [\r\n '0' + a,\r\n '0' + b,\r\n '0' + c\r\n ];\r\n }\r\n\r\n const bits = n.toString(2).split('').reverse().join(''); \r\n let a = '';\r\n let b = '';\r\n let c = '';\r\n\r\n if (bits[0] === '1') {\r\n output(-1);\r\n continue;\r\n }\r\n\r\n for (let bit = 1; bit < bits.length; bit++) {\r\n if (bits[bit] === '1') {\r\n [a, b, c] = carry(a, b, c);\r\n } else {\r\n [a, b, c] = dontCarry(a, b, c);\r\n }\r\n }\r\n\r\n a = parseInt(a, 2);\r\n b = parseInt(b, 2);\r\n c = parseInt(c, 2);\r\n\r\n output(`${a} ${b} ${c}`);\r\n }\r\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n/***\nCodeforces Round #804 (Div. 2)\n2022-07-04\n\nA. The Third Three Number Problem\n***/\n\nfunction main() {\n const t = parseInt(readline());\n\n for (let i = 0; i < t; i++) {\n const n = parseInt(readline());\n\n if (n % 2 == 0) {\n console.log(`${0} ${n / 2} ${(n, n / 2)}`);\n } else {\n console.log(\"-1\");\n }\n }\n}\n\nfunction formula(a, b, c) {\n return (a ^ b) + (b ^ c) + (a ^ c);\n}\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar arr = \"\";\r\nprocess.stdin.on(\"data\", function (chunk) {\r\n arr += chunk;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n arr = arr.split(\"\\n\");\r\n const testcases = parseInt(arr.shift());\r\n for (let t = 0; t < testcases; t++) {\r\n const n = parseInt(arr[t]);\r\n if (n % 2 === 0) {\r\n console.log(0, 0, n / 2);\r\n } else {\r\n console.log(-1);\r\n }\r\n }\r\n});\r\n"}], "negative_code": [{"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n\tvar t = lines[0];\n\tvar n = 0;\n\tfor(i = 1; i <= t * 2; i++){\n var k = lines[i];\n if(k % 2 === 0){\n console.log(0, k / 2, k / 2);\n }else{\n console.log(-1);\n }\n }\n});\n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n\tvar t = lines[0];\n\tvar n = 0;\n\tfor(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n var a = k[0], b = k[1], c = k[2];\n console.log(a + b + c, b + c, c);\n }\n});\n\n"}], "src_uid": "43041076ddd0bbfac62cd4abf4536282"} {"nl": {"description": "While working at DTL, Ela is very aware of her physical and mental health. She started to practice various sports, such as Archery, Yoga, and Football.Since she started engaging in sports activities, Ela switches to trying a new sport on days she considers being \"Luxury\" days. She counts the days since she started these activities, in which the day she starts is numbered as day $$$1$$$. A \"Luxury\" day is the day in which the number of this day is a luxurious number. An integer $$$x$$$ is called a luxurious number if it is divisible by $$${\\lfloor \\sqrt{x} \\rfloor}$$$.Here $$$\\lfloor r \\rfloor$$$ denotes the \"floor\" of a real number $$$r$$$. In other words, it's the largest integer not greater than $$$r$$$.For example: $$$8$$$, $$$56$$$, $$$100$$$ are luxurious numbers, since $$$8$$$ is divisible by $$$\\lfloor \\sqrt{8} \\rfloor = \\lfloor 2.8284 \\rfloor = 2$$$, $$$56$$$ is divisible $$$\\lfloor \\sqrt{56} \\rfloor = \\lfloor 7.4833 \\rfloor = 7$$$, and $$$100$$$ is divisible by $$$\\lfloor \\sqrt{100} \\rfloor = \\lfloor 10 \\rfloor = 10$$$, respectively. On the other hand $$$5$$$, $$$40$$$ are not, since $$$5$$$ are not divisible by $$$\\lfloor \\sqrt{5} \\rfloor = \\lfloor 2.2361 \\rfloor = 2$$$, and $$$40$$$ are not divisible by $$$\\lfloor \\sqrt{40} \\rfloor = \\lfloor 6.3246 \\rfloor = 6$$$.Being a friend of Ela, you want to engage in these fitness activities with her to keep her and yourself accompanied (and have fun together, of course). Between day $$$l$$$ and day $$$r$$$, you want to know how many times she changes the activities.", "input_spec": "Each test contains multiple test cases. The first line has the number of test cases $$$t$$$ ($$$1 \\le t \\le 10\\ 000$$$). The description of the test cases follows. The only line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le 10^{18}$$$) — the intervals at which you want to know how many times Ela changes her sports.", "output_spec": "For each test case, output an integer that denotes the answer.", "sample_inputs": ["5\n\n8 19\n\n8 20\n\n119 121\n\n1 100000000000000000\n\n1234567891011 1000000000000000000"], "sample_outputs": ["5\n6\n2\n948683296\n2996666667"], "notes": "NoteIn the first test case, $$$5$$$ luxury numbers in range $$$[8, 19]$$$ are: $$$8, 9, 12, 15, 16$$$."}, "positive_code": [{"source_code": "function solve() {\r\n var [l, r] = readArray(BigInt);\r\n var firstSqrt = BigInt(Math.floor(Math.sqrt(Number(l))));\r\n while(firstSqrt * firstSqrt < l) {\r\n firstSqrt = firstSqrt + 1n;\r\n }\r\n var lastSqrt = BigInt(Math.floor(Math.sqrt(Number(r))));\r\n while (lastSqrt * lastSqrt + 2n * lastSqrt > r) {\r\n lastSqrt = lastSqrt - 1n;\r\n }\r\n var prevFirstSqrt = firstSqrt - 1n;\r\n var afterLastSqrt = lastSqrt + 1n;\r\n var ans = 0n;\r\n if (firstSqrt <= lastSqrt) {\r\n ans = (lastSqrt - firstSqrt + 1n) * 3n;\r\n }\r\n [\r\n prevFirstSqrt * prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + 2n * prevFirstSqrt,\r\n afterLastSqrt * afterLastSqrt,\r\n afterLastSqrt * afterLastSqrt + afterLastSqrt,\r\n afterLastSqrt * afterLastSqrt + 2n * afterLastSqrt\r\n ].filter((x, i, a) => a.indexOf(x) === i).forEach((canBeAns) => {\r\n if (canBeAns >= l && canBeAns <= r) {\r\n ans = ans + 1n;\r\n }\r\n });\r\n write(ans);\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX;\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n ANS = '';\r\n MEMORY_INDEX = 0;\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst sqrt = (n) => {\r\n let low = 1n,\r\n high = n,\r\n ans;\r\n while (low <= high) {\r\n let mid = (low + high) / 2n;\r\n if (mid * mid <= n) {\r\n ans = mid;\r\n low = mid + 1n;\r\n } else high = mid - 1n;\r\n }\r\n return ans;\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [l, r] = BInpArr();\r\n let st = sqrt(l),\r\n end = sqrt(r);\r\n const helper = (val, i) => {\r\n let ans = 0;\r\n for (let j = 0; j < 3; j++, val += i) {\r\n if (val >= l && val <= r) ans++;\r\n }\r\n return ans;\r\n };\r\n if (end - st >= 4n) {\r\n let to = end - st + 1n - 2n;\r\n to = to * 3n;\r\n to += BigInt(helper(st * st, st));\r\n to += BigInt(helper(end * end, end));\r\n console.log(to + \"\");\r\n } else {\r\n let ans = 0;\r\n for (let i = st; i <= end; i++) {\r\n let val = i * i;\r\n ans += helper(val, i);\r\n }\r\n console.log(ans);\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const l = rb(),\r\n r = rb();\r\n const sqrt = n => {\r\n let l = 1n,\r\n r = n;\r\n while (l < r) {\r\n const m = (l + r + 1n) / 2n;\r\n if (m * m <= n) {\r\n l = m;\r\n } else {\r\n r = m - 1n;\r\n }\r\n }\r\n return l;\r\n };\r\n const calc = n => {\r\n const a = sqrt(n);\r\n let res = (a - 1n) * 3n;\r\n for (let i = a; i <= a + 2n; i++) {\r\n if (i * a > n) break;\r\n res++;\r\n }\r\n return res;\r\n };\r\n return calc(r) - calc(l - 1n);\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [{"source_code": "function solve() {\r\n var [l, r] = readArray(BigInt);\r\n var firstSqrt = BigInt(Math.floor(Math.sqrt(Number(l - 1n)) + 1));\r\n var lastSqrt = BigInt(Math.floor(Math.sqrt(Number(r + 1n))));\r\n var ans = 0n;\r\n if (lastSqrt > firstSqrt) {\r\n ans = (lastSqrt - firstSqrt) * 3n;\r\n }\r\n var prevFirstSqrt = firstSqrt - 1n;\r\n if (lastSqrt < firstSqrt) {\r\n prevFirstSqrt = lastSqrt - 1n;\r\n }\r\n [\r\n prevFirstSqrt * prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + 2n * prevFirstSqrt,\r\n lastSqrt * lastSqrt,\r\n lastSqrt * lastSqrt + lastSqrt,\r\n lastSqrt * lastSqrt + 2n * lastSqrt\r\n ].forEach((canBeAns) => {\r\n if (canBeAns >= l && canBeAns <= r) {\r\n ans = ans + 1n;\r\n }\r\n });\r\n write(ans);\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX;\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n ANS = '';\r\n MEMORY_INDEX = 0;\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}, {"source_code": "function solve() {\r\n var [l, r] = readArray(BigInt);\r\n var firstSqrt = BigInt(Math.floor(Math.sqrt(Number(l - 1n)) + 1));\r\n var lastSqrt = BigInt(Math.floor(Math.sqrt(Number(r + 1n))));\r\n var ans = 0n;\r\n if (lastSqrt < firstSqrt) {\r\n [\r\n lastSqrt * lastSqrt,\r\n lastSqrt * lastSqrt + lastSqrt,\r\n lastSqrt * lastSqrt + 2n * lastSqrt\r\n ].forEach((canBeAns) => {\r\n if (canBeAns >= l && canBeAns <= r) {\r\n ans = ans + 1n;\r\n }\r\n });\r\n write(ans);\r\n return;\r\n }\r\n ans = (lastSqrt - firstSqrt) * 3n;\r\n var prevFirstSqrt = firstSqrt - 1n;\r\n [\r\n prevFirstSqrt * prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + 2n * prevFirstSqrt,\r\n lastSqrt * lastSqrt,\r\n lastSqrt * lastSqrt + lastSqrt,\r\n lastSqrt * lastSqrt + 2n * lastSqrt\r\n ].forEach((canBeAns) => {\r\n if (canBeAns >= l && canBeAns <= r) {\r\n ans = ans + 1n;\r\n }\r\n });\r\n write(ans);\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX;\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n ANS = '';\r\n MEMORY_INDEX = 0;\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}, {"source_code": "function solve() {\r\n var [l, r] = readArray(BigInt);\r\n var firstSqrt = BigInt(Math.floor(Math.sqrt(Number(l - 1n)) + 1));\r\n var lastSqrt = BigInt(Math.floor(Math.sqrt(Number(r + 1n))));\r\n var ans = (lastSqrt - firstSqrt) * 3n;\r\n var prevFirstSqrt = firstSqrt - 1n;\r\n [\r\n prevFirstSqrt * prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + prevFirstSqrt,\r\n prevFirstSqrt * prevFirstSqrt + 2n * prevFirstSqrt,\r\n lastSqrt * lastSqrt,\r\n lastSqrt * lastSqrt + lastSqrt,\r\n lastSqrt * lastSqrt + 2n * lastSqrt\r\n ].forEach((canBeAns) => {\r\n if (canBeAns >= l && canBeAns <= r) {\r\n ans = ans + 1n;\r\n }\r\n });\r\n write(ans); \r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX;\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n ANS = '';\r\n MEMORY_INDEX = 0;\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}], "src_uid": "10812427d3052ce91cd0951911d3acb9"} {"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 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi,  ci ≤ 6) — 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": "const readline = require(\"readline\");\n\nconst rl = readline.createInterface({\n input: process.stdin\n});\n\nlet element = [];\nlet Mishka = 0;\nlet Chris = 0;\nrl.on(\"line\", item => {\n if (!item) return rl.close();\n\n element.push(item);\n}).on(\"close\", solveProblem);\n\nfunction solveProblem() {\n // let test = element.splice(0, 1);\n element.splice(0, 1);\n element.forEach(x => {\n let temp = x.split(\" \").map(num => parseInt(num));\n let Mi = temp[0];\n let Ci = temp[1];\n\n if (Mi > Ci) Mishka++;\n if (Mi < Ci) Chris++;\n });\n\n const result =\n Mishka === Chris\n ? \"Friendship is magic!^^\"\n : Mishka > Chris\n ? \"Mishka\"\n : \"Chris\";\n\n console.log(result);\n}"}, {"source_code": "function main() {\n // write code here:\n const n=Number(stdin[0]);\n var mishka=0;\n var chris=0;\n var name;\n for(let i=1;i<=n;i++){\n var arr=stdin[i].split(' ').map(Number);\n var m=arr[0];\n var c=arr[1];\n if(m>c){\n mishka+=1;\n }else if (mchris){\n name='Mishka';\n }else if (mishka input.push(line));\n\nreadLine.on('close', () => {\n let mishkaWins = 0\n let chrisWins = 0\n let friend = 0\n let result = 'Friendship is magic!^^'\n const games = [...input.slice(1)]\n games.forEach(item => {\n const res = item.split(' ')\n let mishka = parseInt(res[0], 10)\n let chris = parseInt(res[1], 10)\n if (mishka > chris)\n mishkaWins++\n else if (chris > mishka)\n chrisWins++\n else\n friend++\n })\n if (mishkaWins !== 0 || chrisWins !== 0) {\n if (mishkaWins > chrisWins) {\n result = 'Mishka'\n } else if (mishkaWins < chrisWins) {\n result = 'Chris'\n }\n }\n console.log(result)\n})"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var Mishka = 0;\n var Chris = 0;\n for(var i = 0; i < N; i++){\n var tmp = nextIntArray();\n if(tmp[0] > tmp[1]){\n Mishka++;\n }else if(tmp[0] < tmp[1]){\n Chris++;\n }\n }\n if(Mishka > Chris){\n myout(\"Mishka\");\n }else if(Mishka < Chris){\n myout(\"Chris\");\n }else{\n myout(\"Friendship is magic!^^\");\n }\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet x = y = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let [a, b] = d.split(' ').map(Number);\n\n if (a > b) {\n x++;\n }\n else if (b > a) {\n y++;\n }\n\n c++;\n});\n\nrl.on('close', () => {\n if (x > y) {\n console.log('Mishka');\n }\n else if (y > x) {\n console.log('Chris');\n }\n else {\n console.log('Friendship is magic!^^');\n }\n});\n"}, {"source_code": "const readLine = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadLine.on('line', line => input.push(line));\n\nreadLine.on('close', () => {\n let [n] = input[0].split(' ').map(x => parseInt(x));\n let m = 0, c = 0;\n\n input.forEach((x, i) => {\n if (i === 0) return;\n const nums = x.split(' ').map(x => parseInt(x));\n if (nums[0] > nums[1]) m += 1;\n else if (nums[0] < nums[1]) c += 1;\n });\n\n if (m === c) console.log(`Friendship is magic!^^`)\n else if (m > c) console.log(`Mishka`)\n else console.log(`Chris`)\n}); \n"}, {"source_code": "// Sample code to perform I/O:\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n main(stdin_input);\n});\n\nfunction splitter(str, seperator = '') {\n return str.trim().split(seperator);\n}\nfunction main(input) {\n let output = nameLookUp(input);\n process.stdout.write(output); // Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\n// Write your code here\nfunction nameLookUp(str) {\n\n let inputs = str.trim().split('\\n');\n let rounds = +inputs[0];\n let roundScores = inputs.slice(1);\n let win = 0;\n let msg = 'Mishka';\n while (rounds--) {\n let roundScore = roundScores[rounds];\n let score = splitter(roundScore, ' ');\n if (+score[0] > +score[1]) {\n win++;\n }\n else if (+score[0] < +score[1]) {\n win--;\n }\n }\n\n if (win > 0) {\n msg = 'Mishka';\n }\n else if (win < 0) {\n msg = 'Chris';\n }\n else {\n msg = 'Friendship is magic!^^';\n }\n\n return msg.toString();\n}\n\n\n\n\n\n\n\n\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let am = 0;\n let ac = 0;\n for (var i = 0; i < n; i++) {\n let mc = readLine().split(' ').map(v => parseInt(v))\n let m = mc[0];\n let c = mc[1];\n if (m > c) {\n am++;\n } else if (m < c) {\n ac++;\n }\n }\n if (am > ac) {\n console.log('Mishka');\n } else if (am == ac) {\n console.log('Friendship is magic!^^');\n } else {\n console.log('Chris');\n }\n}"}, {"source_code": "var n = +readline();\n\nvar mc = 0, cc = 0;\nfor(var i = 0; i < n; i++){\n var input = readline().split(\" \").map(Number);\n var m = input[0], c = input[1];\n\n if(m > c){\n mc++;\n }else if(m < c){\n cc++;\n }\n}\n\nif(mc > cc){\n write(\"Mishka\");\n}else if(mc < cc){\n write(\"Chris\");\n}else{\n write(\"Friendship is magic!^^\");\n}"}, {"source_code": "function cmp(x){\n\treturn parseInt(x);\n}\nvar n = parseInt(readline());\nvar a = [];\nfor(var i = 0; i < n; i++){\n\ta[i] = readline().split(\" \").map(cmp);\n}\nvar awin = 0, bwin = 0;\n\tvar result='';\n\tfor(var i = 0; i < n; i++)\n\t{\n\t\tif(a[i][0] > a[i][1]){\n\t\t\tawin ++;\n\t\t}\n\t\telse if(a[i][0] < a[i][1]){\n\t\t\tbwin ++;\n\t\t}\n\t\telse{\n\t\t\tcontinue;\n\t\t}\n\t}\n\tif(awin > bwin){\n\t\tresult='Mishka';\n\t}\n\telse if(awin < bwin){\n\t\tresult='Chris';\n\t}\n\telse{\n\t\tresult='Friendship is magic!^^';\n\t}\n\tprint(result);"}, {"source_code": "var res = sol(readline());\nprint(res);\n\nfunction sol(line1) {\n var input1 = line1.split(\" \").map((x) => Number(x));\n\n var n = input1[0];\n\n var mishka = 0;\n var chris = 0;\n\n while (n > 0) {\n var line = readline().split(\" \").map((x) => Number(x));\n\n if (line[0] > line[1]) {\n mishka++;\n } else if (line[0] < line[1]) {\n chris++;\n }\n\n n--;\n }\n\n var winner = \"\";\n if (mishka > chris) {\n winner = \"Mishka\";\n } else if (mishka < chris) {\n winner = \"Chris\";\n } else {\n winner = \"Friendship is magic!^^\";\n }\n\n return winner;\n}"}, {"source_code": "(function() {\n 'use strict';\n const n = readline();\n let m = 0;\n let c = 0;\n for (let i = 0; i < n; ++i) {\n const z = readline().split(' ').map(Number);\n if (z[0] > z[1]) {\n m += 1;\n } else if (z[0] < z[1]) {\n c += 1;\n }\n }\n if (m > c) {\n print('Mishka');\n } else if (m < c) {\n print('Chris');\n } else {\n print('Friendship is magic!^^');\n }\n \n \n}());"}, {"source_code": "var n = +readline();\nvar obj = {}, str, b = false, res = 0, a, b;\n\nfor(var i = 0; i < n; i++) {\n str = readline().split(' ');\n a = +str[0]; b = +str[1];\n if (a > b) res++;\n if (a < b) res--;\n}\n\nif (res == 0)\n print(\"Friendship is magic!^^\");\nelse if (res > 0)\n print(\"Mishka\");\nelse\n print(\"Chris\");\n//print(res);\n"}, {"source_code": "var n = readline();\nvar a = [];\nvar i = 0;\nvar count_m = 0,\n count_c = 0;\nwhile (i < n) {\n a = readline()\n .split(\" \")\n .map((a) => parseInt(a));\n if (a[0] > a[1]) {\n count_m++;\n } else if (a[0] < a[1]) {\n count_c++;\n }\n i++;\n}\nif (count_m > count_c) print(\"Mishka\");\nelse if (count_c > count_m) print(\"Chris\");\nelse print(\"Friendship is magic!^^\");"}, {"source_code": "n=Number(readline())\nmishka=0,chris=0\nfor (var i=0;iscore[1]){\n mishka++;\n } \n else if (score[0]chris){\n print('Mishka');\n} \nelse if (mishkastr[1])\n\t\tm++;\n\telse if (str[0]chris)\n\t\tprint(\"Mishka\");\n\telse if (m b) return 'm';\n}\n\nfor (var i = 0; i < roundsCount; i++) {\n\tvar results = readline().split(' ').map(function (result) {\n\t\treturn parseInt(result);\n\t});\n\twins[getWinner(results[0], results[1])]++;\n}\n\nif (wins['m'] === wins['c']) {\n\tprint('Friendship is magic!^^');\n} else if (wins['m'] > wins['c']) {\n\tprint('Mishka');\n} else if (wins['m'] < wins['c']) {\n\tprint('Chris');\n}\n"}, {"source_code": "var N = +readline(),\n f = 0, s = 0, arr,\n w1 = 'Mishka',\n w2 = 'Chris',\n w3 = 'Friendship is magic!^^';\n\nwhile (N--) {\n arr = readline().split(' ');\n f += arr[0] >= arr[1] ? 1 : 0;\n s += arr[0] <= arr[1] ? 1 : 0;\n}\n\nprint(f === s ? w3 : (f > s ? w1 : w2));"}, {"source_code": "var nline = readline();\nvar n = parseInt(nline);\n\nvar count = 0;\n\nfor(i=0;ic){\n\tcount+=1;\n } else if(m0){\n print('Mishka');\n} else if(count<0){\n print('Chris');\n}else{\n print('Friendship is magic!^^');\n}"}, {"source_code": "\"use strict\";\n\nvar main = function() {\n var n = +rd();\n var r = 0;\n \n for (var i = 0; i < n; ++i) {\n var input = rdAr();\n var m = input[0];\n var c = input[1];\n r += Math.sign(c - m);\n }\n\n wr(['Mishka', 'Friendship is magic!^^', 'Chris'][Math.sign(r) + 1]);\n};\n\nvar rd = readline;\nvar wr = write;\nvar pr = print;\nvar rdAr = () => rd().split(' ').map(v => +v);\nvar cmpLt = (a, b) => a - b;\nvar cmpGt = (a, b) => b - a;\n\nmain();"}, {"source_code": "n=Number(readline())\nm=0,c=0\nfor (var i=0;iX[1]) ++m\n else if (X[0]c) print('Mishka')\nelse if (m d[1];\n c += d[0] < d[1];\n}\n\nif (m > c) {\n write('Mishka');\n} else if (m < c) {\n write('Chris');\n} else {\n write('Friendship is magic!^^');\n}\n"}, {"source_code": "// var n = 3;\n\nvar n = parseInt(readline());\nvar m = 0;\nvar c = 0;\n\n// var a = [[3,3], [2,2], [4,4]];\n\nfor (var i = 0; i arr[1]) {\n ++m;\n } else if (arr[0] < arr[1]) {\n ++c;\n }\n}\n\nif (m > c) {\n write(\"Mishka\");\n} else if(m round[1]){\n mishka++;\n }\n else if(round[1] > round[0]){\n chris++;\n }\n}\nif(mishka === chris){\n print(\"Friendship is magic!^^\")\n}\nelse if(mishka > chris){\n print(\"Mishka\");\n}\nelse {\n print(\"Chris\")\n}"}], "negative_code": [{"source_code": "function cmp(x){\n\treturn parseInt(x);\n}\nfunction main(){\n\tvar n = parseInt(readline());\n\tvar a = [];\n\tfor(var i = 0; i < n; i++){\n\t\ta[i] = readline().split(\" \").map(cmp);\n\t}\n\tvar temp = test(a);\n\tprint(temp);\n}\nfunction test(){\n\t//var a =[[3,5],[1,2],[4,2]];\n\tvar awin = 0, bwin = 0;\n\tvar result='';\n\tfor(var i = 0; i < n; i++)\n\t{\n\t\tif(a[i][0] > a[i][1]){\n\t\t\tawin ++;\n\t\t}\n\t\telse if(a[i][0] < a[i][1]){\n\t\t\tbwin ++;\n\t\t}\n\t\telse{\n\t\t\tcontinue;\n\t\t}\n\t}\n\tif(awin > bwin){\n\t\tresult='Mishka';\n\t}\n\telse if(awin < bwin){\n\t\tresult='Chris';\n\t}\n\telse{\n\t\tresult='Friendship is magic!^^';\n\t}\n\treturn result;\n}"}, {"source_code": "var roundsCount = parseInt(readline(), 10);\nvar wins = {\n\tf: 0,\n\tm: 0,\n\tc: 0,\n};\n\nfunction getWinner(a, b) {\n\tif (a === b) return 'f';\n\tif (a < b) return 'c';\n\tif (a > b) return 'm';\n}\n\nfor (var i = 0; i < roundsCount; i++) {\n\tvar results = readline().split(' ').map((result) => parseInt(result));\n\twins[getWinner(results[0], results[1])]++;\n}\n\nvar sortedResults = Object\n\t.keys(wins)\n\t.sort((a, b) => wins[a] - wins[b]);\n\nvar resultsHash = {\n\tf: 'Friendship is magic!^^',\n\tm: 'Mishka',\n\tc: 'Chris',\n};\n\nprint(resultsHash[sortedResults[0]]);\n"}, {"source_code": "var roundsCount = parseInt(readline(), 10);\nvar wins = {\n\tf: 0,\n\tm: 0,\n\tc: 0,\n};\n\nfunction getWinner(a, b) {\n\tif (a === b) return 'f';\n\tif (a < b) return 'c';\n\tif (a > b) return 'm';\n}\n\nfor (var i = 0; i < roundsCount; i++) {\n\tvar results = readline().split(' ').map((result) => parseInt(result));\n\twins[getWinner(results[0], results[1])]++;\n}\n\nvar sortedResults = Object\n\t.keys(wins)\n\t.sort((a, b) => wins[a] - wins[b]);\n\nvar resultsHash = {\n\tf: 'Friendship is magic!^^',\n\tm: 'Mishka',\n\tc: 'Chris',\n};\n\nprint(resultsHash[sortedResults[0]]);"}, {"source_code": "var N = 3, f = 0, s = 0, arr,\n w1 = 'Mishka',\n w2 = 'Chris',\n w3 = 'Friendship is magic!^^';\n\nwhile (N--) {\n arr = readline().split(' ');\n f += arr[0] >= arr[1] ? 1 : 0;\n s += arr[0] <= arr[1] ? 1 : 0;\n}\n\nprint(f === s ? w3 : (f > s ? w1 : w2));"}], "src_uid": "76ecde4a445bbafec3cda1fc421e6d42"} {"nl": {"description": "You are given some Tetris field consisting of $$$n$$$ columns. The initial height of the $$$i$$$-th column of the field is $$$a_i$$$ blocks. On top of these columns you can place only figures of size $$$2 \\times 1$$$ (i.e. the height of this figure is $$$2$$$ blocks and the width of this figure is $$$1$$$ block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one $$$a_i$$$ is greater than $$$0$$$: You place one figure $$$2 \\times 1$$$ (choose some $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with $$$a_i + 2$$$); then, while all $$$a_i$$$ are greater than zero, replace each $$$a_i$$$ with $$$a_i - 1$$$. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.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$$$) — 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 100$$$) — the number of columns in the Tetris field. 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 initial height of the $$$i$$$-th column of the Tetris field.", "output_spec": "For each test case, print the answer — \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.", "sample_inputs": ["4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process, the field becomes $$$[2, 0, 2]$$$. Then place the figure in the second column and after the second step of the process, the field becomes $$$[0, 0, 0]$$$.And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes $$$[0, 2]$$$. Then place the figure in the first column and after the second step of the process, the field becomes $$$[0, 0]$$$.In the fourth test case of the example, place the figure in the first column, then the field becomes $$$[102]$$$ after the first step of the process, and then the field becomes $$$[0]$$$ after the second step of the process."}, "positive_code": [{"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nlet arr = ''\nlet ptr = 0\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main(arr)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a) {\n return parseInt(a[ptr++])\n}\n\nfunction readString(a) {\n return a[ptr++]\n}\n\nfunction readStrings(a) {\n return a[ptr++].split(' ')\n}\n\nfunction readInts(a) {\n return a[ptr++].split(' ').map(a => parseInt(a))\n}\n\nfunction main(input) {\n let t = readInt(input)\n while(t--) {\n const n = readInt(input)\n const aI = readInts(input)\n let max = Math.max(...aI)\n let f = false\n for(let i = 0; i < n && !f; i++) {\n if((max - aI[i]) % 2 === 1) f = true\n }\n if(f) wr('NO')\n else wr('YES')\n }\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let isOdd = false;\n let isEven = false;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] % 2) {\n isOdd = true;\n }\n else {\n isEven = true;\n }\n }\n\n if (isOdd && isEven) {\n console.log('NO');\n }\n else {\n console.log('YES');\n }\n\n c++;\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8')\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', input => { inputString += input })\nprocess.stdin.on('end', _ => { inputString = inputString.trim().split('\\n').map(str => str.trim()); main() })\nconst readline = () => { return inputString[currentLine++] }\n\n\n\nfunction main(){\n\tlet tests = parseInt(readline())\n\tfor (let i = 0; i < tests; i++) {\n\t\tlet num = parseInt(readline());\n\t\tlet arr = readline().split(' ').map(x => parseInt(x))\n\t\tlet od = 0, ev = 0;\n\t\tarr.forEach(x => {\n\t\t\tif (x & 1) od++;\n\t\t\telse ev++;\n\t\t});\n\t\tif (!ev || !od) console.log(\"YES\");\n\t\telse console.log(\"NO\");\n\t}\n}\n"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t-- > 0) {\n const n = getInt()\n const arr = getInts()\n let ok = true\n\n const mx = arr.reduce((out, cur) => {\n return Math.max(out, cur)\n }, 0)\n\n for (let i in arr) {\n if ((mx - arr[i]) % 2) ok = false\n }\n\n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "var t = Number(readline());\nfor(var r=0;r Number(x));\n var m = Math.max.apply(null, a);\n for(var i=0; iNumber(a));case 6:return i.split(\"\");case 7:return i.split(\"\").map((a)=>Number(a));case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main() {\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var n = nextInt();\n var list = nextIntArray();\n var odd = 0;\n var even = 0;\n for(var j = 0; j < n; j++){\n if(list[j] % 2 == 0){\n even++;\n }else{\n odd++;\n }\n }\n if(odd != 0 && even != 0){\n output[i] = \"NO\";\n }else{\n output[i] = \"YES\";\n }\n }\n myout(myconv(output,9));\n}"}, {"source_code": "var toInt = x =>parseInt(x);\n\nvar t = parseInt(readline());\n\nfor(var tt=0;tt (Math.max(i, j)) );\n var pass = true;\n //print(a.join(' '))\n a.forEach( v => (pass &= (max-v)%2 === 0 ) );\n print(pass ? \"YES\":\"NO\");\n \n}\n\n"}, {"source_code": "var t = readline();\nfor (var i = 0; i num % 2 !== ost)\n print(not ? 'NO' : 'YES')\n}\n"}, {"source_code": "var t = Number(readline());\nvar n;\nvar a;\nvar obj = {\n even: 0,\n odd: 0\n}\nfor(var i = 0 ; i < t; i++){\n n = Number(readline());\n obj.even = 0;\n obj.odd = 0;\n a = readline().split(\" \").map(cur => {\n Number(cur)%2 === 0 ? obj.even++ : obj.odd++ ; \n } );\n\n (obj.even !== 0 && obj.odd !== 0) ? print(\"NO\") : print(\"YES\");\n}\n"}, {"source_code": "var t = Number(readline());\nvar n;\nvar a;\nvar obj = {\n even: 0,\n odd: 0\n}\nfor(var i = 0 ; i < t; i++){\n n = Number(readline());\n obj.even = 0;\n obj.odd = 0;\n a = readline().split(\" \").map(cur => {\n Number(cur)%2 === 0 ? obj.even++ : obj.odd++ ; \n } );\n\n (obj.even !== 0 && obj.odd !== 0) ? print(\"NO\") : print(\"YES\");\n}\n//"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8')\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', input => { inputString += input })\nprocess.stdin.on('end', _ => { inputString.trim().split('\\n').map(str => str.trim()) })\nconst readline = () => { return inputString[currentLine++] }\n\nlet tests = parseInt(readline())\nfor(let i = 0; i < tests; i++){\n\tlet num = parseInt(readline());\n\tlet arr = readline().split(' ').map(x => parseInt(x))\n\tlet od = 0, ev = 0;\n\tarr.forEach(x => {\n\t\tif(x & 1) od++;\n\t\telse ev++;\n\t});\n\tif(!ev || !od) console.log(\"YES\");\n\telse console.log(\"NO\");\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = getInts()\n let limit = 5\n let ok = false\n while (limit --> 0 && !ok) {\n let mm = 1e9\n for (let i in arr) {\n mm = Math.min(mm, arr[i])\n }\n\n for (let i = 0; i < n; ++i) {\n if (arr[i] === mm) {\n if (i + 1 < n && arr[i + 1] === mm) {\n arr[i] ++\n arr[i + 1] ++\n } else {\n arr[i] ++\n arr[i] ++\n }\n\n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n break\n }\n }\n }\n }\n\n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = getInts()\n let limit = 333\n let ok = false\n while (limit --> 0) {\n let mm = 1e9\n for (let i in arr) {\n mm = Math.min(mm, arr[i])\n }\n \n for (let i = 0; i < n; ++i) {\n if (arr[i] === mm) {\n if (i + 1 < n && arr[i + 1] === mm) {\n arr[i] ++\n arr[i + 1] ++\n }\n \n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n break\n }\n }\n }\n }\n \n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t-- > 0) {\n const n = getInt()\n const arr = getInts()\n let limit = 33\n let ok = false\n let mx = 0\n for (let i in arr) {\n mx = Math.max(mx, arr[i])\n }\n\n while (limit-- > 0 && !ok) {\n for (let i = 0; i < n; ++i) {\n if (arr[i] < mx) {\n arr[i] += 2\n\n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n break\n }\n }\n }\n }\n\n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n }\n\n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = getInts()\n let limit = 1000\n let ok = false\n while (limit --> 0 && !ok) {\n let mm = 1e9\n for (let i in arr) {\n mm = Math.min(mm, arr[i])\n }\n\n for (let i = 0; i < n; ++i) {\n if (arr[i] === mm) {\n if (i + 1 < n && arr[i + 1] === mm) {\n arr[i] ++\n arr[i + 1] ++\n } else {\n arr[i] ++\n arr[i] ++\n }\n\n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n break\n }\n }\n }\n }\n\n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = getInts()\n let limit = 333\n let ok = false\n while (limit --> 0) {\n let mm = 1e9\n for (let i in arr) {\n mm = Math.min(mm, arr[i])\n }\n\n for (let i = 0; i < n; ++i) {\n if (arr[i] === mm) {\n if (i + 1 < n && arr[i + 1] === mm) {\n arr[i] ++\n arr[i + 1] ++\n } else {\n arr[i] ++\n arr[i] ++\n }\n\n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n break\n }\n }\n }\n }\n\n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = getInts()\n let limit = 333\n let ok = false\n while (limit --> 0 && !ok) {\n let mm = 1e9\n for (let i in arr) {\n mm = Math.min(mm, arr[i])\n }\n \n for (let i = 0; i < n; ++i) {\n if (arr[i] === mm) {\n if (i + 1 < n && arr[i + 1] === mm) {\n arr[i] ++\n arr[i + 1] ++\n }\n \n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n break\n }\n }\n }\n }\n \n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = getInts()\n let limit = 1000\n let ok = false\n while (limit --> 0 && !ok) {\n let mm = 1e9\n for (let i in arr) {\n mm = Math.min(mm, arr[i])\n }\n \n for (let i = 0; i < n; ++i) {\n if (arr[i] === mm) {\n if (i + 1 < n && arr[i + 1] === mm) {\n arr[i] ++\n arr[i + 1] ++\n }\n \n const st = new Set(arr)\n if (st.size === 1) {\n ok = true\n break\n }\n }\n }\n }\n \n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = getInts()\n let ok = true\n\n for (let i = 1; i + 1 < n; ++i) {\n const a = Math.abs(arr[i] - arr[i - 1])\n const b = Math.abs(arr[i] - arr[i + 1])\n if (a === b && a === 1) {\n ok = false\n break\n }\n }\n\n print(ok ? 'YES' : 'NO')\n }\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const arr = [1e9, ...getInts(), 1e9]\n let ok = true\n \n for (let i = 1; i + 1 < arr.length; ++i) {\n if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) {\n ok = false\n break\n }\n }\n\n if (n === 1) ok = true\n print(ok ? 'YES' : 'NO')\n }\n}\n\n"}, {"source_code": "var t = readline();\nfor (var i = 0; i= 0 && i < arr.length && j >= 0 && j < arr[0].length;\r\n}\r\n\r\nfunction bfs(i, j, arr){\r\n \r\n var q = new Queue();\r\n var allP = [];\r\n \r\n q.push({i, j});\r\n vis[i][j] = true;\r\n allP.push(q.top());\r\n while(!q.empty()){\r\n var crnt = q.pop();\r\n \r\n for(var x = 0; x < di.length; x++){\r\n var newI = crnt.i + di[x];\r\n var newJ = crnt.j + dj[x];\r\n if(inBounds(newI, newJ, arr) && arr[newI][newJ] === \"*\" && !vis[newI][newJ]){\r\n vis[newI][newJ] = true;\r\n q.push({i: newI, j: newJ});\r\n allP.push({i: newI, j: newJ})\r\n }\r\n }\r\n \r\n }\r\n if(allP.length === 3){\r\n var iS = allP.map((a) => a.i)\r\n var jS = allP.map((a) => a.j)\r\n var iDiff = Math.max(...iS) - Math.min(...iS)\r\n var jDiff = Math.max(...jS) - Math.min(...jS)\r\n \r\n if(iDiff === 1 && jDiff === 1) return true;\r\n \r\n }\r\n return false;\r\n\r\n}\r\n\r\n\r\nwhile(t--){\r\n \r\n var nm = readline().split(\" \").map((a) => parseInt(a));\r\n \r\n var n = nm[0];\r\n var m = nm[1];\r\n var shapes = [];\r\n \r\n for(var i = 0; i < n; i++){\r\n shapes.push(readline());\r\n vis[i] = new Array(m).fill(false);\r\n }\r\n \r\n var allIsL = true;\r\n for(var i = 0; i < n; i++){\r\n for(var j = 0; j < m; j++){\r\n if(shapes[i][j] === \"*\" && !vis[i][j]){\r\n if(!bfs(i, j, shapes))allIsL = false;\r\n }\r\n }\r\n }\r\n \r\n allIsL? print(\"YES\") : print(\"NO\");\r\n\r\n \r\n}"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = lines[l++].trim().split(' ').map(Number)\r\n const grid = lines.slice(l, l + n).map(str => str.trim())\r\n l += n\r\n output[i] = solve(n, m, grid) ? 'YES' : 'NO'\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(n, m, grid) {\r\n const ns = []\r\n for (let i = 0; i < n; i++) {\r\n ns[i] = []\r\n for (let j = 0; j < m; j++) {\r\n ns[i][j] = count(i, j)\r\n }\r\n }\r\n // console.log(ns)\r\n //\r\n let one = 0\r\n let two = 0\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (grid[i][j] === '.') continue\r\n const [c4, c8] = ns[i][j]\r\n // console.log(i, j, c4, c8)\r\n if (c4 === 2) {\r\n if (c8 !== 2) return false\r\n two++\r\n } else if (c4 === 1) {\r\n if (c8 !== 2) return false\r\n one++\r\n } else {\r\n return false\r\n }\r\n }\r\n }\r\n // console.log(one, two)\r\n return one === two * 2\r\n //\r\n function count(i, j) {\r\n const r = []\r\n let c = 0\r\n if (i + 1 < n && grid[i + 1][j] === '*') c++\r\n if (i - 1 >= 0 && grid[i - 1][j] === '*') c++\r\n if (j + 1 < m && grid[i][j + 1] === '*') c++\r\n if (j - 1 >= 0 && grid[i][j - 1] === '*') c++\r\n r.push(c)\r\n if (i + 1 < n && j + 1 < m && grid[i + 1][j + 1] === '*') c++\r\n if (i + 1 < n && j - 1 >= 0 && grid[i + 1][j - 1] === '*') c++\r\n if (i - 1 >= 0 && j + 1 < m && grid[i - 1][j + 1] === '*') c++\r\n if (i - 1 >= 0 && j - 1 >= 0 && grid[i - 1][j - 1] === '*') c++\r\n r.push(c)\r\n return r\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "var t = parseInt(readline());\r\nvar vis = []\r\nvar di = [-1, -1, -1, 0, 1, 1, 1, 0];\r\nvar dj = [-1, 0, 1, 1, 1, 0, -1, -1];\r\nfunction Queue(){\r\n this.arr = [];\r\n this.front = 0;\r\n this.rear = -1;\r\n \r\n this.top = function(){\r\n return this.arr[this.front];\r\n }\r\n this.push = function(el){\r\n this.arr.push(el)\r\n this.rear++;\r\n }\r\n this.pop = function (){\r\n var top = this.top();\r\n this.front++;\r\n return top;\r\n }\r\n this.empty = function(){\r\n return this.rear < this.front\r\n }\r\n}\r\nfunction inBounds(i, j, arr){\r\n return i >= 0 && i < arr.length && j >= 0 && j < arr[0].length;\r\n}\r\n\r\nfunction bfs(i, j, arr){\r\n \r\n var q = new Queue();\r\n var h = 0, v = 0, cells = 1;\r\n \r\n q.push({i, j});\r\n vis[i][j] = true;\r\n while(!q.empty()){\r\n var crnt = q.pop();\r\n \r\n\r\n for(var x = 0; x < di.length; x++){\r\n var newI = crnt.i + di[x];\r\n var newJ = crnt.j + dj[x];\r\n if(inBounds(newI, newJ, arr) && arr[newI][newJ] === \"*\" && !vis[newI][newJ]){\r\n vis[newI][newJ] = true;\r\n q.push({i: newI, j: newJ});\r\n h += Math.abs(i - newI);\r\n v += Math.abs(j - newJ);\r\n cells++;\r\n }\r\n }\r\n \r\n }\r\n return (cells === 3 && h && v && h+v <= 3)? true : false;\r\n \r\n}\r\n\r\n\r\nwhile(t--){\r\n \r\n var nm = readline().split(\" \").map((a) => parseInt(a));\r\n \r\n var n = nm[0];\r\n var m = nm[1];\r\n var shapes = [];\r\n \r\n for(var i = 0; i < n; i++){\r\n shapes.push(readline());\r\n vis[i] = new Array(m).fill(false);\r\n }\r\n \r\n var allIsL = true;\r\n for(var i = 0; i < n; i++){\r\n for(var j = 0; j < m; j++){\r\n if(shapes[i][j] === \"*\" && !vis[i][j]){\r\n if(!bfs(i, j, shapes))allIsL = false;\r\n }\r\n }\r\n }\r\n \r\n allIsL? print(\"YES\") : print(\"NO\");\r\n\r\n \r\n}"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = lines[l++].trim().split(' ').map(Number)\r\n const grid = lines.slice(l, l + n).map(str => str.trim())\r\n l += n\r\n output[i] = solve(n, m, grid) ? 'YES' : 'NO'\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(n, m, grid) {\r\n const ns = []\r\n for (let i = 0; i < n; i++) {\r\n ns[i] = []\r\n for (let j = 0; j < m; j++) {\r\n ns[i][j] = count(i, j)\r\n }\r\n }\r\n // console.log(ns)\r\n //\r\n let one = 0\r\n let two = 0\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < m; j++) {\r\n if (grid[i][j] === '.') continue\r\n const [c4, c8] = ns[i][j]\r\n // console.log(i, j, c4, c8)\r\n if (c4 === 2) {\r\n if (c8 !== 2) return false\r\n two++\r\n } else if (c4 === 1) {\r\n if (c8 !== 2) return false\r\n one++\r\n } else {\r\n return false\r\n }\r\n }\r\n }\r\n // console.log(one, two)\r\n return one * 2 === two\r\n //\r\n function count(i, j) {\r\n const r = []\r\n let c = 0\r\n if (i + 1 < n && grid[i + 1][j] === '*') c++\r\n if (i - 1 >= 0 && grid[i - 1][j] === '*') c++\r\n if (j + 1 < m && grid[i][j + 1] === '*') c++\r\n if (j - 1 >= 0 && grid[i][j - 1] === '*') c++\r\n r.push(c)\r\n if (i + 1 < n && j + 1 < m && grid[i + 1][j + 1] === '*') c++\r\n if (i + 1 < n && j - 1 >= 0 && grid[i + 1][j - 1] === '*') c++\r\n if (i - 1 >= 0 && j + 1 < m && grid[i - 1][j + 1] === '*') c++\r\n if (i - 1 >= 0 && j - 1 >= 0 && grid[i - 1][j - 1] === '*') c++\r\n r.push(c)\r\n return r\r\n }\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, m] = lines[l++].trim().split(' ').map(Number)\n const grid = lines.slice(l, l + n).map(str => str.trim())\n l += n\n output[i] = solve(n, m, grid) ? 'YES' : 'NO'\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, m, grid) {\n const ns = []\n for (let i = 0; i < n; i++) {\n ns[i] = []\n for (let j = 0; j < m; j++) {\n ns[i][j] = count(i, j)\n }\n }\n // console.log(ns)\n //\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (grid[i][j] === '.') continue\n const [c4, c8] = ns[i][j]\n // console.log(i, j, c4, c8)\n if (c4 === 2) {\n if (c8 !== 2) return false\n } else if (c4 === 1) {\n if (c8 !== 2) return false\n } else {\n return false\n }\n }\n }\n return true\n //\n function count(i, j) {\n const r = []\n let c = 0\n if (i + 1 < n && grid[i + 1][j] === '*') c++\n if (i - 1 >= 0 && grid[i - 1][j] === '*') c++\n if (j + 1 < m && grid[i][j + 1] === '*') c++\n if (j - 1 >= 0 && grid[i][j - 1] === '*') c++\n r.push(c)\n if (i + 1 < n && j + 1 < m && grid[i + 1][j + 1] === '*') c++\n if (i + 1 < n && j - 1 >= 0 && grid[i + 1][j - 1] === '*') c++\n if (i - 1 >= 0 && j + 1 < m && grid[i - 1][j + 1] === '*') c++\n if (i - 1 >= 0 && j - 1 >= 0 && grid[i - 1][j - 1] === '*') c++\n r.push(c)\n return r\n }\n}\n"}], "src_uid": "6a06ad39dbdd97ca8654023009c89a42"} {"nl": {"description": "Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\\lfloor a_i \\rfloor$$$ or $$$\\lceil a_i \\rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\\lfloor a_i \\rfloor$$$ and $$$\\lceil a_i \\rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.", "output_spec": "In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any.", "sample_inputs": ["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"], "sample_outputs": ["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"], "notes": "NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down."}, "positive_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var res = '';\n var b = 0, m = 0;\n var mas = [];\n for(var i = 0; i < n; i++) {\n mas[i] = read.number();\n if(mas[i] > 0) {\n b += Math.floor( mas[i] );\n }\n else {\n m += Math.ceil( mas[i] );\n }\n }\n\n if(b + m === 0) {\n for(var i = 0; i < n; i++) {\n var a = mas[i]\n if(a > 0) {\n a = Math.floor(a);\n }\n else {\n a = Math.ceil(a);\n }\n res += a + '\\n';\n }\n }\n else if(b + m > 0) {\n var c = b + m;\n for(var i = 0; i < n; i++) {\n var a = mas[i]\n if(a > 0) {\n a = Math.floor(a);\n }\n else {\n if(c && Math.ceil(a) !== a) {\n a = Math.floor(a);\n c--;\n }\n else {\n a = Math.ceil(a);\n }\n }\n res += a + '\\n';\n }\n }\n else if(b + m < 0) {\n var c = b + m;\n for(var i = 0; i < n; i++) {\n var a = mas[i]\n if(a > 0) {\n if(c && Math.ceil(a) !== a) {\n a = Math.ceil(a);\n c++;\n }\n else {\n a = Math.floor(a);\n }\n }\n else {\n a = Math.ceil(a);\n }\n res += a + '\\n';\n }\n }\n print(res);\n}());"}, {"source_code": "\"use strict\";\n\nvar n = +readline();\n\nvar preSum = 0;\nvar A = [];\nfor (var i = 0; i < n; ++i) {\n A.push(+readline());\n preSum += Math.floor(A[i]);\n}\n\nfor (var i = 0; i < n; ++i) {\n if (preSum < 0) {\n write(Math.ceil(A[i]));\n if (Math.floor(A[i]) < Math.ceil(A[i])) {\n preSum += 1;\n }\n } else {\n write(Math.floor(A[i]));\n }\n write('\\n');\n}"}], "negative_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var res = '';\n for(var i = 0; i < n; i++) {\n var a = read.number();\n if(a > 0) {\n a = Math.floor(a);\n }\n else {\n a = Math.ceil(a);\n }\n res += a + '\\n';\n }\n print(res);\n}());"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var res = '';\n var b = 0, m = 0;\n var mas = [];\n for(var i = 0; i < n; i++) {\n mas[i] = read.number();\n } \n for(var i = 0; i < n; i++) {\n var a = mas[i]\n if(a > 0) {\n a = Math.floor(a);\n b += a;\n }\n else {\n a = Math.ceil(a);\n m += a;\n }\n res += a + '\\n';\n }\n \n if(m + b !== 0) {\n var res = '';\n for(var i = 0; i < n; i++) {\n var a = mas[i]\n if(a > 0) {\n a = Math.ceil(a);\n b += a;\n }\n else {\n a = Math.floor(a);\n m += a;\n }\n res += a + '\\n';\n }\n }\n print(res);\n}());"}, {"source_code": "\"use strict\";\n\nvar n = +readline();\n\nvar preSum = 0;\nvar A = [];\nfor (var i = 0; i < n; ++i) {\n A.push(+readline());\n preSum += Math.floor(A[i]);\n}\n\nfor (var i = 0; i < n; ++i) {\n if (preSum > 0) {\n write(Math.ceil(A[i]));\n if (Math.floor(A[i]) < Math.ceil(A[i])) {\n preSum += 1;\n }\n } else {\n write(Math.floor(A[i]));\n }\n write('\\n');\n}"}, {"source_code": "\"use strict\";\n\nvar n = +readline();\n\nvar preSum = 0;\nvar A = [];\nfor (var i = 0; i < n; ++i) {\n A.push(+readline());\n preSum += Math.floor(A[i]);\n}\n\nfor (var i = 0; i < n; ++i) {\n if (A[i] * preSum > 0) {\n write(Math.ceil(A[i]));\n if (Math.floor(A[i]) < Math.ceil(A[i])) {\n preSum += 1;\n }\n } else {\n write(Math.floor(A[i]));\n }\n write('\\n');\n}"}, {"source_code": "\"use strict\";\n\nvar n = +readline();\n\nvar preSum = 0;\nvar A = [];\nfor (var i = 0; i < n; ++i) {\n A.push(+readline());\n preSum += Math.floor(A[i]);\n}\n\nfor (var i = 0; i < n; ++i) {\n if (preSum < 0) {\n write(Math.ceil(A[i]));\n preSum += 1;\n } else {\n write(Math.floor(A[i]));\n }\n write('\\n');\n}"}, {"source_code": "\"use strict\";\n\nvar n = +readline();\n\nvar preSum = 0;\nvar A = [];\nfor (var i = 0; i < n; ++i) {\n A.push(+readline());\n preSum += Math.floor(A[i]);\n}\n\nfor (var i = 0; i < n; ++i) {\n if (A[i] * preSum > 0) {\n write(Math.ceil(A[i]));\n preSum += 1;\n } else {\n write(Math.floor(A[i]));\n }\n write('\\n');\n}"}], "src_uid": "6059cfa13594d47b3e145d7c26f1b0b3"} {"nl": {"description": "There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.", "input_spec": "The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105).", "output_spec": "Output a single integer — the optimal number of visible kangaroos.", "sample_inputs": ["8\n2\n5\n7\n6\n9\n8\n4\n2", "8\n9\n1\n6\n2\n6\n5\n8\n3"], "sample_outputs": ["5", "5"], "notes": null}, "positive_code": [{"source_code": "n = parseInt(readline());\nvar s = [];\nfor(var i = 0; i < n; i++)\n s[i] = parseInt(readline());\n\ns.sort(function(a, b) {return a - b;});\n// print(s);\n\nvar lb = 0, ub = Math.floor(n/2) + 1;\n\nfunction check(mid) {\n for(var i = 0; i < mid; i++)\n if(s[i] * 2 > s[n - mid + i])\n return false;\n return true;\n}\n\nwhile(ub - lb > 1) {\n var mid = Math.floor(lb + (ub - lb) / 2);\n // if(n === 77777)\n // print(lb, ub);\n if(check(mid))\n lb = mid;\n else\n ub = mid;\n}\n\nprint(n - lb);\n"}, {"source_code": "var n = readline() - 0;\n\nvar a = new Array(n);\nfor (var i = 0; i < n; i++) a[i] = readline() - 0;\na.sort(function(i, j) {\n return i - j;\n});\n\nfunction search(n, f) {\n var i = 0;\n var j = n;\n\n while (i < j) {\n var h = i + (j - i) / 2 | 0;\n if (!f(h))\n i = h + 1;\n else\n j = h;\n }\n\n return i;\n}\n\nvar ans = search(n / 2 + 1 | 0, function(j) {\n if (j == n / 2 + 1 | 0) \n return true;\n if (j == 0)\n return false;\n\n for (var i = 0; i < j; i++)\n if (a[n - j + i] < a[i] * 2)\n return true;\n return false;\n});\n\nprint(n - ans + 1);"}], "negative_code": [{"source_code": "n = parseInt(readline());\nvar s = [];\nfor(var i = 0; i < n; i++)\n s[i] = parseInt(readline());\n\ns.sort(function(a, b) {return a - b;});\n// print(s);\n\nvar lb = 0, ub = n/2 + 1;\n\nfunction check(mid) {\n for(var i = 0; i < mid; i++)\n if(s[i] * 2 > s[n - mid + i])\n return false;\n return true;\n}\n\nwhile(ub - lb > 1) {\n var mid = Math.floor(lb + (ub - lb) / 2);\n // if(n === 77777)\n print(lb, ub);\n if(check(mid))\n lb = mid;\n else\n ub = mid;\n}\n\nprint(n - lb);\n"}, {"source_code": "n = parseInt(readline());\nvar s = [];\nfor(var i = 0; i < n; i++)\n s[i] = parseInt(readline());\n\ns.sort(function(a, b) {return a - b;});\n// print(s);\n\nif(n !== 77777) {\n\nvar lb = 0, ub = n/2 + 1;\n\nfunction check(mid) {\n for(var i = 0; i < mid; i++)\n if(s[i] * 2 > s[n - mid + i])\n return false;\n return true;\n}\n\nwhile(ub - lb > 1) {\n var mid = Math.floor(lb + (ub - lb) / 2);\n if(check(mid))\n lb = mid;\n else\n ub = mid;\n}\n\nprint(n - lb);\n} else {\n print(n);\n}"}, {"source_code": "n = parseInt(readline());\nvar s = [];\nfor(var i = 0; i < n; i++)\n s[i] = parseInt(readline());\n\ns.sort();\n// print s;\n\nvar lb = 0, ub = n/2 + 1;\n\nfunction check(mid) {\n for(var i = 0; i < mid; i++)\n if(s[i] * 2 > s[n - mid + i])\n return false;\n return true;\n}\n\nwhile(ub - lb > 1) {\n var mid = Math.floor(lb + (ub - lb) / 2);\n if(check(mid))\n lb = mid;\n else\n ub = mid;\n}\n\nprint(n - lb);"}, {"source_code": "var n = readline() - 0;\n\nvar a = readline().split(' ');\nfor (var i = 0; i < n; i++) a[i] = a[i] - 0;\na.sort(function(i, j) {\n return i - j;\n});\n\nfunction search(n, f) {\n var i = 0;\n var j = n;\n\n while (i < j) {\n var h = i + (j - i) / 2 | 0;\n if (!f(h))\n i = h + 1;\n else\n j = h;\n }\n\n return i;\n}\n\nvar ans = search(n / 2 + 1 | 0, function(j) {\n if (j == n / 2 + 1 | 0) \n return true;\n\n for (var i = 0; i < j; i++)\n if (a[n - j + i] < a[i] * 2)\n return true;\n return false;\n});\n\nprint(n - ans + 1);"}, {"source_code": "var n = readline() - 0;\n\nvar a = readline().split(' ');\nfor (var i = 0; i < n; i++) a[i] = a[i] - 0;\na.sort(function(i, j) {\n return i - j;\n});\n\nfunction search(n, f) {\n var i = 0;\n var j = n;\n\n while (i < j) {\n var h = i + (j - i) / 2 | 0;\n if (!f(h))\n i = h + 1;\n else\n j = h;\n }\n\n return i;\n}\n\nvar ans = search(n / 2 + 1 | 0, function(j) {\n if (j == n / 2 + 1 | 0) \n return true;\n\n for (var i = 0; i < j; i++)\n if (a[n - j + i] < a[i] * 2)\n return true;\n return false;\n});\n\nprint(n - ans + 2);"}, {"source_code": "var n = readline() - 0;\n\nvar a = new Array(n);\n\nfor (var i = 0; i < n; i++) a[i] = readline() - 0;\na.sort();\n\nfunction search(n, f) {\n var i = 0;\n var j = n;\n\n while (i < j) {\n var h = i + (j - i) / 2 | 0;\n if (!f(h))\n i = h + 1;\n else\n j = h;\n }\n\n return i;\n}\n\nvar ans = search(n / 2 + 1 | 0, function(j) {\n if (j == n / 2 + 1 | 0) return true;\n for (var i = 0; i < j; i++)\n if (a[n - j + i] < a[i] * 2)\n return true;\n return false;\n});\n\nprint(n - ans + 1);"}], "src_uid": "361f65484d86051fa9ff013f5e8c9154"} {"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$$$) — the number of test cases. Each test case consists of one line containing $$$s$$$ — a string consisting of exactly two different lowercase Latin letters (i. e. a correct word of the Berland language).", "output_spec": "For each test case, print one integer — 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": "var limit = parseInt(readline());\r\n var alphabets = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\",\r\n \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\",\r\n \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\r\n for (var i = 0; i < limit; i++) {\r\n var caseWord = readline();\r\n var firstWordIndex = alphabets.indexOf(caseWord[0]);\r\n var secondWordIndex = alphabets.indexOf(caseWord[1]);\r\n var secondWord = (firstWordIndex > secondWordIndex) ? secondWordIndex + 1 : secondWordIndex;\r\n var result = (25 * firstWordIndex) + secondWord;\r\n print(result);\r\n }"}, {"source_code": "var dict = {};\n\nvar alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n\nvar cnt = 1;\nfor (var i = 0; i < alphabet.length; i++) {\n for (var k = 0; k < alphabet.length; k++) {\n if (i === k) {\n continue;\n }\n dict[alphabet[i] + alphabet[k]] = cnt;\n cnt++;\n }\n}\n\nvar n = parseInt(readline());\n\nfor (var i = 0; i < n; i++) {\n var s = readline();\n print(dict[s]);\n}\n"}, {"source_code": "var tests = parseInt(readline());\r\n var a;\r\n\r\n function cToI(c) {\r\n return c.charCodeAt(0) - 'a'.charCodeAt(0);\r\n }\r\n for (var t=0; t < tests; t++) {\r\n a = readline();\r\n var ans = cToI(a.charAt(0)) * 25;\r\n var add = cToI(a.charAt(1)) + 1;\r\n if (a.charAt(1) > a.charAt(0)) {\r\n add--;\r\n }\r\n print(ans + add);\r\n }"}, {"source_code": "abcStr = 'abcdefghijklmnopqrstuvwxyz'\r\nabc = abcStr.split('') \r\nwords = {}\r\nacc = 1\r\nfor(i = 0; i < 26; i++){\r\n for(j = 0; j < 26; j++){\r\n if(abc[i] !=abc[j]){\r\n words[acc] = abc[i] + abc[j]\r\n acc++\r\n }\r\n }\r\n}\r\n\r\n\r\n\r\nT = readline()\r\nwhile (T--) {\r\n ans = 0\r\n s = readline()\r\n \r\n for(key in words){\r\n if(words[key] === s)\r\n ans = key\r\n }\r\n\r\n\r\n print(ans)\r\n}\r\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n let line=buf.split('\\n');\r\n let t=parseInt(line[0]);\r\n let arr=new Array(26*26+10);\r\n let a=['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'];\r\n let cnt=0;\r\n for(let i=0;i<26;i++)\r\n {\r\n for(let j=0;j<26;j++)\r\n {\r\n if(i!=j) arr[++cnt]=a[i]+a[j];\r\n }\r\n }\r\n // console.log(line);\r\n for(let i=1;i<=t;i++)\r\n {\r\n let str=line[i][0]+line[i][1];\r\n // console.log(str.length);\r\n for(let j=1;j<=cnt;j++)\r\n {\r\n if(arr[j]===str)\r\n {\r\n console.log(j);\r\n break;\r\n }\r\n }\r\n }\r\n})"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar list = [];\r\n\tvar alpha = \"abcdefghijklmnopqrstuvwxyz\";\r\n\tfor(var i = 0; i < alpha.length; i++){\r\n\t\tfor(var j = 0; j < alpha.length; j++){\r\n\t\t\tif(i != j){\r\n\t\t\t\tlist.push(alpha[i] + alpha[j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\twhile(hasNext()){\r\n\t\tvar s = next();\r\n\t\tmyout(list.indexOf(s) + 1);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n for (let test = 0; test < N; test++) {\r\n let s = readline();\r\n\r\n const alphabet = [...Array(26)].map((_, i) => String.fromCharCode(i + 97));\r\n const letterPos = {};\r\n alphabet.forEach((letter, i) => letterPos[letter] = i + 1);\r\n\r\n let res = 25 * (letterPos[s[0]] - 1);\r\n if (letterPos[s[1]] > letterPos[s[0]]) {\r\n res += letterPos[s[1]] - 1;\r\n } else {\r\n res += letterPos[s[1]];\r\n }\r\n\r\n output(res);\r\n }\r\n}\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var v = ['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 for(i = 1; i <= n; i++){\n var k = lines[i].split('');\n var a = k[0]; var b = k[1];\n var a1 = 0;\n var b1 = 0;\n for(j = 0; j < 26; j++){\n if(v[j] == a){\n a1 = j;\n }if(v[j] == b){\n b1 = j;\n }if(a1 !== 0 && b1 !== 0){\n break;\n }\n }\n var ans = a1 * 25 + b1;\n if(a > b){\n ans++;\n }\n console.log(ans); \n }\n});"}, {"source_code": "/*\r\n * File Created: Thursday, 11th February 2021 1:42:08 pm\r\n * Author: Lukas Rimkus\r\n */\r\n'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n let testCases = parseInt(data.shift());\r\n\r\n while(testCases--) {\r\n\r\n const s = data.shift();\r\n \r\n console.log(b(s));\r\n }\r\n});\r\n\r\nfunction get_ints() { \r\n return data[currentLine++].split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n \r\nfunction a(n,arr){\r\n let k = 0;\r\n let j = 0;\r\n for(let i = 0 ; i < n; i++){\r\n if(arr[i] < 0){\r\n arr[j++] *= -1;\r\n arr[i] *= -1;\r\n }\r\n }\r\n if(isSorted(arr)) {\r\n return 'YES';\r\n } else { \r\n return 'NO'\r\n }\r\n}\r\n\r\nfunction isSorted(arr){\r\n for(let i = 0 ; i < arr.length - 1; i++){\r\n if(arr[i] > arr[i+1]) return false;\r\n }\r\n return true;\r\n}\r\n\r\nfunction b(s) {\r\n let arr = [];\r\n for(let i = 97; i <= 122; i++ ){\r\n for(let j = 97; j <= 122; j++){\r\n if(i != j) arr.push(String.fromCharCode(i,j));\r\n }\r\n }\r\n let count = 1;\r\n let index = 0;\r\n while(true){\r\n if(s != arr[index]) {\r\n count++;\r\n index++;\r\n } else{\r\n return count;\r\n }\r\n }\r\n}\r\n\r\nmodule.exports = b;"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var n = lines[0];\n var v = ['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 for(i = 1; i <= n; i++){\n var k = lines[i].split('');\n var a = k[0]; var b = k[1];\n var a1 = 0;\n var b1 = 0;\n for(j = 0; j < 26; j++){\n if(v[j] == a){\n a1 = j;\n }if(v[j] == b){\n b1 = j;\n }if(a1 !== 0 && b1 !== 0){\n break;\n }\n }\n var ans = a1 * 25 + b1;\n if(a > b){\n ans++;\n }\n console.log(ans); \n }\n});"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\nfunction Main(){\r\n // input in nodeJs\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tconst stringArr = nextCharArray();\r\n\t\tlet a = stringArr[0];\r\n\t\tlet b = stringArr[1];\r\n\r\n\t\tlet first = a.charCodeAt(0) - 97;\r\n\t\tlet second = b.charCodeAt(0) - 97;\r\n\t\t// console.log({first, second})\r\n\t\tif (second < first) {\r\n\t\t\tsecond++\r\n\t\t}\r\n\t\t// console.log({first, second})\r\n\r\n\t\tmyout((first * 25) + second );\r\n\t}\r\n}"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst cnk = (n, k) => {\n let res = 1;\n for (let i = 1; i <= k; i++)\n res = res * (n - k + i) / i;\n return Math.round(res + 0.01);\n}\n\n\nconst sumab = (a, b) => {\n let x = (b - a + 1);\n let y = a + b;\n if (x % 2 === 0) {\n x = Math.round(x / 2);\n } else {\n y = Math.round(y / 2);\n }\n return BigInt(x) * BigInt(y);\n}\n\n\n\nconst calc = (s)=>{\n let aCode = 'a'.charCodeAt(0);\n let fIdx = s.charCodeAt(0) - aCode;\n let sIdx = s.charCodeAt(1) - aCode;\n let result = fIdx * 25 + (sIdx < fIdx ? sIdx + 1 : sIdx);\n return result;\n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let s = readline();\n console.log(`${calc(s)}`);\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet dictionary = new Map();\r\nfor (let i = 0; i < 26; i++) {\r\n const a = String.fromCharCode(i + 97);\r\n for (let j = 0; j < 26; j++) {\r\n const b = String.fromCharCode(j + 97);\r\n if (a === b) continue;\r\n dictionary.set(a + b, dictionary.size + 1);\r\n }\r\n}\r\nfunction solve(s) {\r\n console.log(dictionary.get(s));\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const s1 = await read();\r\n solve(s1);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\n\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst lines = []\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst L = process.env.DEBUG ? console.log : ()=>{};\n \nconst pcalc = function(){\n print(calc.apply(null, arguments)); }\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\n\n// SOLUTION\n \nlet a = [];\n let base = 'a'.charCodeAt(0)\nfor (let i=0; i<26; i++)\nfor (let j=0; j<26; j++){\n if (i!=j)\n a.push(String.fromCharCode(base+i, base+j));\n}\n\nconst calc = (s)=>{\n return a.indexOf(s)+1\n};\n \nfunction main() {\n let T = +readline()\n while (T--){\n let s = readline();\n L('Ans:');\n pcalc(s);\n }\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const str = lines[l++]\n output[i] = solve(str)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(str) {\n const a = str.charCodeAt(0) - 'a'.charCodeAt(0)\n let b = str.charCodeAt(1) - 'a'.charCodeAt(0)\n if (str.charCodeAt(1) > str.charCodeAt(0)) {\n b--\n }\n return a * 25 + b + 1\n}\n"}], "negative_code": [{"source_code": "var limit = parseInt(readline());\r\nvar alphabets = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\",\r\n \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\",\r\n \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var caseWord = readline();\r\n var firstWordIndex = 25 * alphabets.indexOf(caseWord[0]);\r\n var secondWordIndex = 0;\r\n if (alphabets.indexOf(caseWord[0]) > alphabets.indexOf(caseWord[1]))\r\n {\r\n secondWordIndex = alphabets.indexOf[1] + 1;\r\n }\r\n else \r\n {\r\n secondWordIndex = alphabets.indexOf[1];\r\n }\r\n var result = firstWordIndex + secondWordIndex;\r\n print(result);\r\n}"}, {"source_code": "var limit = parseInt(readline());\r\nvar alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',\r\n 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',\r\n 't', 'u', 'v', 'w', 'x', 'y', 'z'];\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var caseWord = readline();\r\n var firstWordIndex = 25 * alphabets.indexOf(caseWord[0]);\r\n var secondWordIndex = 0\r\n if (alphabets.indexOf(caseWord[0]) > alphabets.indexOf(caseWord[1]))\r\n {\r\n secondWordIndex = alphabets.indexOf[1] + 1;\r\n }\r\n else \r\n {\r\n secondWordIndex = alphabets.indexOf[1];\r\n }\r\n var result = firstWordIndex + secondWordIndex;\r\n print(result);\r\n}"}, {"source_code": "var limit = parseInt(readline());\r\nvar alphabets = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\",\r\n \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\",\r\n \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var caseWord = readline();\r\n var firstWordIndex = 25 * alphabets.indexOf(caseWord[0]);\r\n var secondWordIndex = 0\r\n if (alphabets.indexOf(caseWord[0]) > alphabets.indexOf(caseWord[1]))\r\n {\r\n secondWordIndex = alphabets.indexOf[1] + 1;\r\n }\r\n else \r\n {\r\n secondWordIndex = alphabets.indexOf[1];\r\n }\r\n var result = firstWordIndex + secondWordIndex;\r\n print(result);\r\n}"}, {"source_code": "var dict = {};\n\nvar alphabet = \"abcdefghigklmnopqrstuvwxyz\";\n\nvar cnt = 1;\nfor (var i = 0; i < alphabet.length; i++) {\n for (var k = 0; k < alphabet.length; k++) {\n if (i === k) {\n continue;\n }\n dict[alphabet[i] + alphabet[k]] = cnt;\n cnt++;\n }\n}\n\nvar n = parseInt(readline());\n\nfor (var i = 0; i < n; i++) {\n var s = readline();\n print(dict[s]);\n}\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n let line=buf.split('\\n');\r\n let t=parseInt(line[0]);\r\n let arr=new Array(26*26+10);\r\n let a=['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'];\r\n let cnt=0;\r\n for(let i=0;i<26;i++)\r\n {\r\n for(let j=0;j<26;j++)\r\n {\r\n if(i!=j) arr[++cnt]=a[i]+a[j];\r\n }\r\n }\r\n for(let i=1;i<=t;i++)\r\n {\r\n let str=line[i];\r\n for(let j=1;j<=cnt;j++)\r\n {\r\n if(arr[j]===str)\r\n {\r\n console.log(j);\r\n break;\r\n }\r\n }\r\n }\r\n})"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar list = [];\r\n\tvar alpha = \"abcdefghijklmnopqrstivwxyz\";\r\n\tfor(var i = 0; i < alpha.length; i++){\r\n\t\tfor(var j = 0; j < alpha.length; j++){\r\n\t\t\tif(i != j){\r\n\t\t\t\tlist.push(alpha[i] + alpha[j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\twhile(hasNext()){\r\n\t\tvar s = next();\r\n\t\tmyout(list.indexOf(s) + 1);\r\n\t}\r\n}\r\n"}], "src_uid": "2e3006d663a3c7ad3781aba1e37be3ca"} {"nl": {"description": "You are given an array $$$a$$$ of $$$2n$$$ distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $$$2$$$ neighbours.More formally, find an array $$$b$$$, such that: $$$b$$$ is a permutation of $$$a$$$.For every $$$i$$$ from $$$1$$$ to $$$2n$$$, $$$b_i \\neq \\frac{b_{i-1}+b_{i+1}}{2}$$$, where $$$b_0 = b_{2n}$$$ and $$$b_{2n+1} = b_1$$$. It can be proved that under the constraints of this problem, such array $$$b$$$ always exists.", "input_spec": "The first line of input contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 1000)$$$ — the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(1 \\leq n \\leq 25)$$$. The second line of each testcase contains $$$2n$$$ integers $$$a_1, a_2, \\ldots, a_{2n}$$$ $$$(1 \\leq a_i \\leq 10^9)$$$ — elements of the array. Note that there is no limit to the sum of $$$n$$$ over all testcases.", "output_spec": "For each testcase, you should output $$$2n$$$ integers, $$$b_1, b_2, \\ldots b_{2n}$$$, for which the conditions from the statement are satisfied.", "sample_inputs": ["3\n3\n1 2 3 4 5 6\n2\n123 456 789 10\n1\n6 9"], "sample_outputs": ["3 1 4 2 5 6\n123 10 456 789\n9 6"], "notes": "NoteIn the first testcase, array $$$[3, 1, 4, 2, 5, 6]$$$ works, as it's a permutation of $$$[1, 2, 3, 4, 5, 6]$$$, and $$$\\frac{3+4}{2}\\neq 1$$$, $$$\\frac{1+2}{2}\\neq 4$$$, $$$\\frac{4+5}{2}\\neq 2$$$, $$$\\frac{2+6}{2}\\neq 5$$$, $$$\\frac{5+3}{2}\\neq 6$$$, $$$\\frac{6+1}{2}\\neq 3$$$."}, "positive_code": [{"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n/**\r\n * 05/28/21 morning\r\n * https://codeforces.com/contest/1526/problem/A\r\n */\r\n\r\nconst solve = (n, a) => {\r\n stin(a);\r\n for (let i = 1; i + 1 < n; i += 2) {\r\n swap(a, i, i + 1);\r\n }\r\n // pr(test(a));\r\n pr(a.join(\" \"))\r\n};\r\n\r\nconst test = (a) => {\r\n let n = a.length;\r\n for (let i = 1; i + 1 < n; i++) {\r\n if (a[i - 1] + a[i + 1] >> 1 == a[i]) {\r\n pr(a[i - 1], a[i + 1], a[i - 1] + a[i + 1] >> 1, a[i])\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(2 * input[i][0], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "let y = '';\nprocess.stdin.on('data', c => y += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = y.split(EOL);\n\tvar t = lines[0];\n\tvar e = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n e = lines[i] * 2;\n }else{\n var k = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});\n var start = 0;\n var end = e - 1;\n var ans = '';\n while(start < end){\n ans += k[start] + ' ';\n start++;\n if(start > end){\n break;\n }\n ans += k[end] + ' ';\n end--;\n if(start > end){\n break;\n }\n }\n console.log(ans);\n }\n }\n});\n\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\n// declare global variables\r\nvar input_stdin = \"\";\r\nvar chunks = \"\";\r\n\r\n// standard input is stored into input_stdin\r\nprocess.stdin.on('data', function (data) {\r\n\r\n //for local environment windows\r\n if(data.trim() == 'end' ){\r\n chunks = input_stdin.split(\"\\n\");\r\n start();\r\n }\r\n \r\n input_stdin += data;\r\n\r\n});\r\n\r\n// standard input is done and stored into an array\r\nprocess.stdin.on('end', function () {\r\n//process.on('SIGINT', function(){\r\n chunks = input_stdin.split(\"\\n\");\r\n main();\r\n});\r\n\r\nfunction main(){\r\n var s=1;\r\n var t=parseInt(chunks[0]);\r\n var result=[];\r\n while(t--){\r\n var n=parseInt(chunks[s++]);\r\n var arr=chunks[s++].split(\" \").map(Number);\r\n arr.sort((a,b)=>b-a);\r\n var f=0;\r\n var l=2*n-1;\r\n var ans=\"\";\r\n for(var i=0;i {\r\n return parseInt(val);\r\n });\r\n arr.sort((a, b) => {\r\n return a - b;\r\n });\r\n var ans = [];\r\n for (var i = 0; i < n; i++) {\r\n ans.push(arr[i]);\r\n ans.push(arr[2*n-1-i]);\r\n }\r\n print(ans.join(\" \"));\r\n}"}, {"source_code": "var t = +readline();\r\nwhile (t--) {\r\n var n = parseInt(readline());\r\n var arr = readline()\r\n .split(\" \")\r\n .map((val) => {\r\n return parseInt(val);\r\n });\r\n arr.sort((a, b) => {\r\n return a - b;\r\n });\r\n var ans = [];\r\n var end = 2 * n - 1;\r\n for (var i = 0; i < n; i++) {\r\n ans.push(arr[i]);\r\n ans.push(arr[end]);\r\n end--;\r\n }\r\n print(ans.join(\" \"));\r\n}\r\n"}], "negative_code": [{"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n/**\r\n * 05/28/21 morning\r\n * https://codeforces.com/contest/1526/problem/A\r\n */\r\n\r\nconst solve = (n, a) => {\r\n for (let i = 1; i + 1 < n; i++) {\r\n if (a[i - 1] + a[i + 1] >> 1 == a[i]) {\r\n swap(a, i - 1, i);\r\n }\r\n }\r\n // pr(test(a));\r\n pr(a.join(\" \"))\r\n};\r\n\r\nconst test = (a) => {\r\n let n = a.length;\r\n for (let i = 1; i + 1 < n; i++) {\r\n if (a[i - 1] + a[i + 1] >> 1 == a[i]) {\r\n pr(a[i - 1], a[i + 1], a[i - 1] + a[i + 1] >> 1, a[i])\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(2 * input[i][0], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n/**\r\n * 05/28/21 morning\r\n * https://codeforces.com/contest/1526/problem/A\r\n */\r\nconst solve = (n, a) => {\r\n let res = [];\r\n let tot = n / 2;\r\n while (tot--) {\r\n res.push(a.shift());\r\n res.push(a.pop());\r\n }\r\n // pr(res)\r\n // pr(test(res));\r\n pr(res.join(\" \"))\r\n};\r\n\r\nconst test = (a) => {\r\n let n = a.length;\r\n for (let i = 1; i + 1 < n; i++) {\r\n if (a[i - 1] + a[i + 1] >> 1 == a[i]) {\r\n pr(a[i - 1], a[i + 1], a[i - 1] + a[i + 1] >> 1, a[i])\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(2 * input[i][0], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n/**\r\n * 05/28/21 morning\r\n * https://codeforces.com/contest/1526/problem/A\r\n */\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n for (let i = 2; i < n - 1; i++) {\r\n swap(a, i - 1, i);\r\n }\r\n // pr(a)\r\n pr(a.join(\" \"))\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(2 * input[i][0], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "var t= readline(parseInt());\r\nwhile(t--){\r\n var n=readline(parseInt());\r\n var arr1=readline().split(' ');\r\n var arr2=[];\r\n var ans=[];\r\n for(var i=0;i<2*n;i++){\r\n arr2.push(arr1[i]);\r\n }\r\n arr2.sort();\r\n for(var i=0;i {\r\n return parseInt(val);\r\n });\r\n arr.sort((a, b) => {\r\n return a - b;\r\n });\r\n var ans = [];\r\n var end = 2 * n - 1;\r\n for (var i = 0; i < n; i++) {\r\n ans.push(arr[i]);\r\n ans.push(arr[end]);\r\n end--;\r\n }\r\n print(ans);\r\n}\r\n"}], "src_uid": "4296da660a39a6e98b41387929701c0a"} {"nl": {"description": "You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.", "input_spec": "The first line contains integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \\le r, g, b \\le 10^8$$$) — the number of red, green and blue candies, respectively.", "output_spec": "Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.", "sample_inputs": ["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"], "sample_outputs": ["1\n2\n2\n10\n5\n9"], "notes": "NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten."}, "positive_code": [{"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let j = 0; j < t; j++) {\n const a = arr[j].split(' ').map(a => parseInt(a)).sort((a, b) => b - a)\n\n let count = 0\n\n if(a[0] >= (a[1] + a[2])) {\n count = a[1] + a[2]\n }\n else {\n let diff = a[0] - a[1]\n count += diff\n a[0] -= diff\n a[2] -= diff\n \n diff = a[0] - a[2]\n count += diff\n a[0] -= diff\n a[1] -= diff\n }\n \n if(a[0] == a[1] && a[1] == a[2]) {\n if(a[0] % 2 == 0) count += (a[0] / 2) * 3\n else count += ((a[0] - 1) / 2) * 3 + 1\n }\n\n console.log(count)\n \n }\n})"}, {"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = '';\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n let chunks = '';\n chunks = input_stdin.split('\\n');\n start(chunks); \n});\n\nfunction start(input) {\n let q = +input.shift();\n while(q--) {\n const [a,b,c] = input.shift().split(' ').map(Number).sort((x, y) => x - y);\n\n if(a + b <= c) {\n console.log(a + b);\n } else {\n console.log(c + Math.floor((a - c + b)/2));\n }\n }\n}"}, {"source_code": "let buffer = '';\nprocess.stdin.on('data', c => buffer += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = buffer.split(EOL);\n lines.pop();\n \n main(lines);\n});\n\n \nfunction main(lines) {\n const N = Number(lines.shift());\n const arr = lines.map(row => row.split(' ').map(Number));\n let diff;\n \n arr.forEach(row => {\n row.sort((a, b) => a - b);\n\n diff = Math.min(row[0], row[2] - row[1]);\n row[0] -= diff;\n row[1] += diff;\n \n console.log(\n Math.min(\n row[1] + Math.ceil(row[0] / 2),\n row[2] + Math.floor(row[0] / 2)\n )\n );\n });\n}"}, {"source_code": "var n = Number(readline());\nfor(var i=0;i Number(l) ).sort(function(a,b){return a-b;});\n if(a[0]<=a[2]-a[1]) print(a[0]+a[1]);\n else print(Math.floor((a[0]+a[1]+a[2])/2));\n}"}], "negative_code": [{"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = '';\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n let chunks = '';\n chunks = input_stdin.split('\\n');\n start(chunks); \n});\n\nfunction start(input) {\n let q = +input.shift();\n while(q--) {\n const [a,b,c] = input.shift().split(' ').map(Number).sort((x, y) => x - y);\n\n if(a + b <= c) {\n console.log(a + b);\n } else {\n console.log(c - Math.floor((a - c + b)/2));\n }\n }\n}"}, {"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = '';\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n let chunks = '';\n chunks = input_stdin.split('\\n');\n start(chunks); \n});\n\nfunction start(input) {\n let q = +input.shift();\n console.log(input);\n while(q--) {\n const [a,b,c] = input.shift().split(' ').map(Number).sort((x, y) => x - y);\n\n if(a + b <= c) {\n console.log(a + b);\n } else {\n console.log(c + Math.floor((a - c + b)/2));\n }\n }\n}"}, {"source_code": "\"use strict\";\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = '';\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n let chunks = '';\n chunks = input_stdin.split('\\n');\n start(chunks); \n});\n\nfunction start(input) {\n let q = +input.shift();\n console.log(input);\n while(q--) {\n const [a,b,c] = input.shift().split(' ').map(Number).sort((x, y) => x - y);\n\n if(a + b <= c) {\n console.log(a + b);\n } else {\n console.log(c - Math.floor((a - c + b)/2));\n }\n }\n}"}, {"source_code": "let buffer = '';\nprocess.stdin.on('data', c => buffer += c)\nprocess.stdin.on('end', main)\n\n\nfunction main() {\n const {EOL} = require('os');\n const lines = buffer.split(EOL);\n \n const N = Number(lines.shift());\n const arr = lines.map(row => row.split(' ').map(Number));\n \n arr.forEach(row => {\n row.sort((a, b) => a - b);\n console.log(row[0] + Math.min(row[1], row[2] - row[0]));\n });\n}\n"}, {"source_code": "let buffer = '';\nprocess.stdin.on('data', c => buffer += c)\nprocess.stdin.on('end', main)\n\n\nfunction main() {\n const {EOL} = require('os');\n const lines = buffer.split(EOL);\n lines.pop();\n \n const N = Number(lines.shift());\n const arr = lines.map(row => row.split(' ').map(Number));\n \n arr.forEach(row => {\n row.sort((a, b) => a - b);\n console.log(row[0] + Math.min(row[1], row[2] - row[0]));\n });\n}\n"}, {"source_code": "let buffer = '';\nprocess.stdin.on('data', c => buffer += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = buffer.split(EOL);\n lines.pop();\n \n return lines;\n});\n\n \nfunction main(lines) {\n const N = Number(lines.shift());\n const arr = lines.map(row => row.split(' ').map(Number));\n let diff;\n \n arr.forEach(row => {\n row.sort((a, b) => a - b);\n\n diff = Math.min(row[0], row[2] - row[1]);\n row[0] -= diff;\n row[1] += diff;\n \n console.log(\n Math.min(\n row[1] + Math.ceil(row[0] / 2),\n row[2] + Math.floor(row[0] / 2)\n )\n );\n });\n}"}, {"source_code": "var n = Number(readline());\nfor(var i=0;i Number(l) ).sort();\n if(a[0]<=a[2]-a[1]) print(a[0]+a[1]);\n else print(Math.floor((a[0]+a[1]+a[2])/2));\n}"}, {"source_code": "var n = Number(readline());\nfor(var i=0;i Number(l) ).sort();\n if(a[0] {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=1\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]===x[j])\r\n {\r\n j--\r\n if(j===-1)\r\n return Number(n-i-2)\r\n }\r\n }\r\n return Number(30)\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;i 0 && t.length > 0){\n if(s[s.length - 1] == t[t.length - 1]){\n t.pop();\n }else{\n cnt++;\n }\n s.pop();\n }\n return cnt;\n};\nlet q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n var e = 0;\n for(i = 1; i <= t; i++){\n var s = lines[i];\n console.log(Math.min(thisisveryeasyhahahah(s, '00'), Math.min(thisisveryeasyhahahah(s, '25'), Math.min(thisisveryeasyhahahah(s, '50'), thisisveryeasyhahahah(s, '75')))));\n }\n});"}, {"source_code": "var tocount = function(s, t){\n var count = 0;\n s = s.split('').map(Number);\n t = t.split('').map(Number);\n var l = s.length;\n while(s.length > 0 && t.length > 0){\n if(s[s.length - 1] == t[t.length - 1]){\n t.pop();\n }else{\n count++;\n }\n s.pop();\n }\n if(t.length === 0){\n return count;\n }\n return l;\n};\nlet q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var s = lines[i];\n console.log(Math.min(tocount(s, '00'), Math.min(tocount(s, '25'), Math.min(tocount(s, '50'), tocount(s,'75')))));\n }\n});\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rl();\r\n\r\n\t\tn = n.split('').reverse().join('');\r\n\r\n\t\tfunction pos (x, i = -1) {\r\n\t\t\twhile (++i < n.length) {\r\n\t\t\t\tif (n[i] == x)\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\treturn i;\r\n\t\t}\r\n\r\n\t\tconst ans1 = Math.min(pos('2', pos('5')), pos('7', pos('5')));\r\n\t\tconst ans2 = Math.min(pos('0', pos('0')), pos('5', pos('0')));\r\n\r\n\t\tconst ans = Math.min(ans1, ans2) - 1;\r\n\t\t\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 20;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rl();\r\n\r\n\t\tn = n.split('').reverse().join('');\r\n\r\n\t\tlet ans1, ans2;\r\n\t\tfor (let i = 0; i < n.length; i++) {\r\n\t\t\tif (n[i] == '0' && ans1 === undefined) {\r\n\t\t\t\tans1 = INF;\r\n\t\t\t\tfor (let j = i+1; j < n.length; j++) {\r\n\t\t\t\t\tif (n[j] == '0' || n[j] == '5') {\r\n\t\t\t\t\t\tans1 = j-1;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (n[i] == '5' && ans2 == undefined) {\r\n\t\t\t\tans2 = INF;\r\n\t\t\t\tfor (let j = i+1; j < n.length; j++) {\r\n\t\t\t\t\tif (n[j] == '2' || n[j] == '7') {\r\n\t\t\t\t\t\tans2 = j-1;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tans1 = ans1 == undefined ? INF : ans1;\r\n\t\tans2 = ans2 == undefined ? INF : ans2;\r\n\r\n\t\tconst ans = Math.min(ans1, ans2);\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction calcTurns(findIn, num) {\n let digitIndex = 1;\n let turns = 0;\n findIn.split('').reverse().forEach(digit => {\n if (digitIndex < 0) {\n return;\n }\n if (digit === num[digitIndex]) {\n digitIndex--;\n } else {\n turns += 1;\n }\n });\n return digitIndex === -1 ? turns : Infinity;\n}\n\nfunction main() {\n const n = parseInt(readline());\n for (let i = 0; i < n; i++) {\n const num = readline();\n console.log(Math.min(calcTurns(num, '00'), calcTurns(num, '25'), calcTurns(num, '50'), calcTurns(num, '75')));\n }\n}\n"}, {"source_code": "// dist/FinalCode/Common/InputOutputClass.js\nvar Input = function() {\n function Input2(inputData) {\n var _this = this;\n this.SettleStream = function() {\n var re = /\\s+/;\n _this.inputWords = _this.inputStream.split(re);\n _this.inputWordsLength = _this.inputWords.length;\n };\n this.getLength = function() {\n return _this.inputWordsLength;\n };\n this.getEveryWord = function() {\n return _this.inputWords;\n };\n this.getNextWord = function() {\n _this.inputWordsCount++;\n if (_this.inputWordsLength < _this.inputWordsCount) {\n return \"\";\n }\n return _this.inputWords[_this.inputWordsCount - 1];\n };\n this.getNextString = function() {\n return _this.getNextWord();\n };\n this.getNextBigInt = function() {\n return BigInt(_this.getNextWord());\n };\n this.getNextNumber = function() {\n return Number(_this.getNextWord());\n };\n this.getNextInt = function() {\n return parseInt(_this.getNextWord(), 10);\n };\n this.getNextFloat = function() {\n return parseFloat(_this.getNextWord());\n };\n this.inputWordsCount = 0;\n this.inputStream = inputData;\n }\n Input2.prototype.SetStream = function(chunk) {\n this.inputStream += chunk;\n };\n Input2.prototype.getNextIntArray = function(elementCount) {\n var resultArray = new Array(elementCount);\n for (var idx = 0; idx < elementCount; idx++) {\n resultArray[idx] = this.getNextInt();\n }\n return resultArray;\n };\n return Input2;\n}();\nvar InputOutputClass_default = Input;\nvar writeLine = function(outputElement) {\n var _internalWrite = function(_internalOutputElement) {\n process.stdout.write(_internalOutputElement);\n };\n _internalWrite(String(outputElement) + \"\\n\");\n};\n\n// dist/main.js\nvar rw = new InputOutputClass_default(\"\");\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nprocess.stdin.on(\"data\", function(chunk) {\n rw.SetStream(chunk);\n});\nprocess.stdin.on(\"end\", function() {\n rw.SettleStream();\n mainFunc();\n});\nvar mainFunc = function() {\n testCases();\n};\nvar testCases = function() {\n var test = rw.getNextInt();\n for (var i = 0; i < test; i++) {\n solveCase();\n }\n};\nvar solveCase = function() {\n var n = rw.getNextString();\n var answer = n.length + 1e3;\n for (var i = n.length - 1; i >= 0; i--) {\n for (var j = i - 1; j >= 0; j--) {\n var a = Number(n[i]);\n var b = Number(n[j]);\n if ((b * 10 + a) % 25 === 0) {\n if (answer > n.length - j - 2) {\n answer = n.length - j - 2;\n }\n }\n }\n }\n writeLine(answer);\n};\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=1\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]===x[j])\r\n {\r\n j--\r\n if(j===-1)\r\n return Number(n-i-2)\r\n }\r\n }\r\n return Number(30)\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;i {\r\n if (count === -1) {\r\n count = +data\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\nfunction solve(num) {\r\n const lastN = num.lastIndexOf('0')\r\n const lastF = num.lastIndexOf('5')\r\n let tmp, arr = [];\r\n // 25\r\n if (lastF !== -1) {\r\n tmp = num.slice(0, lastF).lastIndexOf('2')\r\n if (tmp !== -1) {\r\n arr.push(((num.length - 1 - lastF) + (lastF - tmp - 1)))\r\n }\r\n }\r\n\r\n // 00\r\n if (lastN !== -1) {\r\n tmp = num.slice(0, lastN).lastIndexOf('0')\r\n if (tmp !== -1) {\r\n arr.push(((num.length - 1 - lastN) + (lastN - tmp - 1)))\r\n }\r\n }\r\n // 50\r\n if (lastN !== -1) {\r\n tmp = num.slice(0, lastN).lastIndexOf('5')\r\n if (tmp !== -1) {\r\n arr.push(((num.length - 1 - lastN) + (lastN - tmp - 1)))\r\n }\r\n }\r\n // 75\r\n if (lastF !== -1) {\r\n tmp = num.slice(0, lastF).lastIndexOf('7')\r\n if (tmp !== -1) {\r\n arr.push(((num.length - 1 - lastF) + (lastF - tmp - 1)))\r\n }\r\n }\r\n console.log(Math.min(...arr))\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const str = lines[l++].trim()\n output[i] = solve(str)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(str) {\n const target = ['00', '25', '50', '75']\n let ans = str.length\n for (let i = 0; i < target.length; i++) {\n let k = 1\n for (let j = str.length - 1; j >= 0; j--) {\n // console.log(target[i][k], str[j], str)\n if (str[j] === target[i][k]) {\n if (k === 0) {\n ans = Math.min(ans, str.length - j - 2)\n // console.log('found', str, target[i], str.length - j - 2)\n break\n }\n k--\n }\n }\n }\n return ans\n}\n"}, {"source_code": "var t = parseInt(readline())\r\n\r\nfor(var T = 1 ; T <= t; ++T){\r\n\tsolve();\r\n}\r\n\r\nfunction solve(){\r\n\tvar n = readline();\r\n\tvar len = n.length;\r\n\tvar ans = len;\r\n\tfor(var i=0; i {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=0\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]===x[j])\r\n {\r\n j++\r\n if(j===2)\r\n return Number(Number(n)-Number(i)-Number(2))\r\n }\r\n }\r\n return Number(30)\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;ix)\r\n ans=x;\r\n x=Number(solve(s,\"00\"))\r\n if(ans>x)\r\n ans=x;\r\n x=Number(solve(s,\"75\"))\r\n if(ans>x)\r\n ans=x;\r\n x=Number(solve(s,\"50\"))\r\n if(ans>x)\r\n ans=x;\r\n console.log(ans)\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=0\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]===x[j])\r\n {\r\n j++\r\n if(j===2)\r\n return Number(Number(n)-Number(i)-Number(2))\r\n }\r\n }\r\n return Number(30)\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;ix)\r\n ans=x;\r\n x=Number(solve(s,\"00\"))\r\n if(ans>x)\r\n ans=x;\r\n x=Number(solve(s,\"75\"))\r\n if(ans>x)\r\n ans=x;\r\n x=Number(solve(s,\"50\"))\r\n if(ans>x)\r\n ans=x;\r\n console.log(ans)\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=0\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]===x[j])\r\n {\r\n j++\r\n if(j===2)\r\n return Number(n-i-2)\r\n }\r\n }\r\n return Number(30)\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;ix)\r\n ans=x;\r\n x=Number(solve(s,\"00\"))\r\n if(ans>x)\r\n ans=x\r\n x=Number(solve(s,\"75\"))\r\n if(ans>x)\r\n ans=x\r\n x=Number(solve(s,\"25\"))\r\n if(ans>x)\r\n ans=x\r\n console.log(ans)\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=0\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]===x[j])\r\n {\r\n j++\r\n if(j===2)\r\n return Number(n-i-2)\r\n }\r\n }\r\n return Number(30)\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;i {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=0\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]==x[j])\r\n {\r\n j++;\r\n if(j==2)\r\n return n-i-2\r\n }\r\n }\r\n return 30\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;i {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction solve(s,x)\r\n{\r\n let n=s.length\r\n let j=0\r\n for(let i=n-1;i>=0;i--)\r\n {\r\n if(s[i]==x[j])\r\n {\r\n j++;\r\n if(j==2)\r\n return n-i-2\r\n }\r\n }\r\n}\r\nfunction main() { \r\n let t=Number(readline())\r\n for(let i=0;i {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction getNumberState(arr, lastDigitVal) {\n const valueMap = {\n 0: [0, 5],\n 5: [2, 7]\n }\n return arr.reduce((acc, digit) => {\n const { lastDigit, isAnswerFound, turns } = acc;\n if (isAnswerFound) {\n return acc;\n }\n if (lastDigit !== null) {\n return valueMap[lastDigit].includes(digit) ? {...acc, isAnswerFound: true} : {...acc, turns: turns + 1};\n } else {\n const isSuitableLastDigit = lastDigitVal !== undefined ? digit === lastDigitVal : digit === 5 || digit === 0;\n return isSuitableLastDigit ? {...acc, lastDigit: digit } : {...acc, turns: turns + 1};\n }\n\n }, {lastDigit: null, isAnswerFound: false, turns: 0});\n}\n\nfunction calcTurns(str) {\n const arr = str.split('').reverse().map(Number);\n let state = getNumberState(arr);\n return state.isAnswerFound ? state.turns : getNumberState(arr, state.lastDigit === 0 ? 5 : 0).turns;\n}\n\nfunction main() {\n const n = parseInt(readline());\n for (let i = 0; i < n; i++) {\n console.log(calcTurns(readline()));\n }\n}\n"}, {"source_code": "\r\nvar t = parseInt(readline())\r\n\r\nfor(var T = 1 ; T <= t; ++T){\r\n\tsolve();\r\n}\r\n\r\nfunction solve(){\r\n\tvar n = parseInt(readline());\r\n\tvar str = String(n);\r\n\tvar len = parseInt(str.length);\r\n\tvar ans = len;\r\n\tfor(var i=0; i {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n console.log(solve(n, arr))\n }\n// })()\n})\n\nfunction solve(n, arr) {\n const limit = 20\n\n let ans = 0\n for (let j = 0; j < limit; j++) {\n let cur = []\n const mask = ~((1 << (j + 1)) - 1)\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] & (1 << j)) {\n cur.push(arr[i] & mask)\n }\n\n if (!(arr[i] & (1 << j)) || i === n - 1) {\n const xor = []\n const map = {\n 0: -1\n }\n if (cur.length < ans) {\n cur = []\n continue\n }\n for (let k = 0; k < cur.length; k++) {\n xor[k] = k ? xor[k - 1] ^ cur[k] : cur[k]\n if (!(xor[k] in map)) {\n map[xor[k]] = k\n }\n if (xor[k] in map) {\n const len = k - map[xor[k]]\n if (!(len & 1)) {\n // console.log(xor[k], k, map[xor[k]], len)\n ans = Math.max(ans, len)\n }\n }\n }\n cur = []\n }\n }\n }\n return ans\n}\n"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n console.log(solve(n, arr))\n }\n// })()\n})\n\nfunction solve(n, arr) {\n const limit = 25\n\n let ans = 0\n for (let j = 0; j < limit; j++) {\n let cur = []\n const mask = ~((1 << (j + 1)) - 1)\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] & (1 << j)) {\n cur.push(arr[i] & mask)\n }\n\n if (!(arr[i] & (1 << j)) || i === n - 1) {\n const xor = []\n const map = {}\n // if (cur.length) {\n // console.log(cur, i)\n // }\n for (let k = 0; k < cur.length; k++) {\n xor[k] = k ? xor[k - 1] ^ cur[k] : cur[k]\n if (!(xor[k] in map)) {\n map[xor[k]] = k\n }\n if (xor[k] in map) {\n const len = k - map[xor[k]] + 1\n if (!(len & 1)) {\n ans = Math.max(ans, len)\n }\n }\n }\n cur = []\n }\n }\n }\n return ans\n}\n"}], "src_uid": "d3e972b7652c0c1321c2e8f15dbc264b"} {"nl": {"description": "This is the easy version of the problem. The only difference between the two versions is the constraint on $$$n$$$. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $$$1$$$ to $$$n$$$, and they would like to add edges to their forests such that: After adding edges, both of their graphs are still forests. They add the same edges. That is, if an edge $$$(u, v)$$$ is added to Mocha's forest, then an edge $$$(u, v)$$$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.", "input_spec": "The first line contains three integers $$$n$$$, $$$m_1$$$ and $$$m_2$$$ ($$$1 \\le n \\le 1000$$$, $$$0 \\le m_1, m_2 < n$$$) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next $$$m_1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) — the edges in Mocha's forest. Each of the next $$$m_2$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) — the edges in Diana's forest.", "output_spec": "The first line contains only one integer $$$h$$$, the maximum number of edges Mocha and Diana can add (in each forest). Each of the next $$$h$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$) — the edge you add each time. If there are multiple correct answers, you can print any one of them.", "sample_inputs": ["3 2 2\n1 2\n2 3\n1 2\n1 3", "5 3 2\n5 4\n2 1\n4 3\n4 3\n1 4", "8 1 2\n1 7\n2 6\n1 5"], "sample_outputs": ["0", "1\n2 4", "5\n5 2\n2 3\n3 4\n4 7\n6 8"], "notes": "NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge $$$(2, 4)$$$."}, "positive_code": [{"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nfunction createHeuristicFindSet(e) {\r\n const t = new Array(e + 1),\r\n n = new Array(e + 1)\r\n let i = e\r\n return {\r\n init: function (e) {\r\n ;(i = e), n.fill(1, i + 1, 1)\r\n for (let e = 1; e <= i; ++e) t[e] = e\r\n },\r\n root: r,\r\n merge: function (e, i) {\r\n const s = r(e),\r\n o = r(i)\r\n if (s === o) return s\r\n if (n[s] > n[o]) return (t[o] = s), (n[s] += n[o]), s\r\n return (t[s] = o), o\r\n },\r\n }\r\n function r(e) {\r\n return t[e] === e ? e : (t[e] = r(t[e]))\r\n }\r\n}\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(String(e))\r\n }\r\n println(e) {\r\n stdout.write(String(e)), stdout.write('\\n')\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(t => {\r\n stdin.on('data', t => e.push(t)),\r\n stdin.on('end', function () {\r\n const n = e.join('').split(os.EOL)\r\n t(n)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const t = new InputAndOutput()\r\n await t.init(), e(t)\r\n}\r\nfunction solve() {\r\n return -1\r\n}\r\nconst MAX_N = 100010,\r\n findset1 = createHeuristicFindSet(MAX_N),\r\n findset2 = createHeuristicFindSet(MAX_N),\r\n pos1 = new Array(MAX_N).fill(0),\r\n pos2 = new Array(MAX_N).fill(0)\r\n__main__(function (e) {\r\n for (let t = 1; t <= 1; ++t) {\r\n const [t, n, i] = e.readIntegersOfLine()\r\n findset1.init(t), findset2.init(t)\r\n for (let t = 0; t < n; ++t) {\r\n const [t, n] = e.readIntegersOfLine()\r\n findset1.merge(t, n)\r\n }\r\n for (let t = 0; t < i; ++t) {\r\n const [t, n] = e.readIntegersOfLine()\r\n findset2.merge(t, n)\r\n }\r\n e.println(t - 1 - Math.max(n, i))\r\n const r = Math.min(Math.floor(Math.random() * t) + 1, t)\r\n for (let n = 1; n <= t; ++n) {\r\n const t = findset1.root(n),\r\n i = findset1.root(r),\r\n s = findset2.root(n),\r\n o = findset2.root(r)\r\n t !== i &&\r\n s !== o &&\r\n (findset1.merge(t, i), findset2.merge(s, o), e.println(r + ' ' + n))\r\n }\r\n let s = 0\r\n for (let e = 1; e <= t; ++e) {\r\n const t = findset1.root(e),\r\n n = findset1.root(r)\r\n t !== n && (findset1.merge(t, n), (pos1[s++] = e))\r\n }\r\n let o = 0\r\n for (let e = 1; e <= t; ++e) {\r\n const t = findset2.root(e),\r\n n = findset2.root(r)\r\n t !== n && (findset2.merge(t, n), (pos2[o++] = e))\r\n }\r\n for (let t = 0, n = Math.min(s, o); t < n; ++t) {\r\n const n = pos1[t],\r\n i = pos2[t]\r\n e.println(n + ' ' + i)\r\n }\r\n }\r\n})\r\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nfunction createHeuristicFindSet(e) {\r\n const t = new Array(e + 1),\r\n n = new Array(e + 1)\r\n let r = e\r\n return {\r\n init: function (e) {\r\n ;(r = e), n.fill(1, r + 1, 1)\r\n for (let e = 1; e <= r; ++e) t[e] = e\r\n },\r\n root: i,\r\n merge: function (e, r) {\r\n const s = i(e),\r\n o = i(r)\r\n if (s === o) return s\r\n if (n[s] > n[o]) return (t[o] = s), (n[s] += n[o]), s\r\n return (t[s] = o), o\r\n },\r\n }\r\n function i(e) {\r\n return t[e] === e ? e : (t[e] = i(t[e]))\r\n }\r\n}\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(String(e))\r\n }\r\n println(e) {\r\n stdout.write(String(e)), stdout.write('\\n')\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(t => {\r\n stdin.on('data', t => e.push(t)),\r\n stdin.on('end', function () {\r\n const n = e.join('').split(os.EOL)\r\n t(n)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const t = new InputAndOutput()\r\n await t.init(), e(t)\r\n}\r\nfunction solve() {\r\n return -1\r\n}\r\n__main__(function (e) {\r\n const t = 100010,\r\n n = createHeuristicFindSet(t),\r\n r = createHeuristicFindSet(t)\r\n for (let t = 1; t <= 1; ++t) {\r\n const [t, i, s] = e.readIntegersOfLine()\r\n n.init(t), r.init(t)\r\n for (let t = 0; t < i; ++t) {\r\n const [t, r] = e.readIntegersOfLine()\r\n n.merge(t, r)\r\n }\r\n for (let t = 0; t < s; ++t) {\r\n const [t, n] = e.readIntegersOfLine()\r\n r.merge(t, n)\r\n }\r\n e.println(t - 1 - Math.max(i, s))\r\n const o = Math.min(Math.floor(Math.random() * t) + 1, t)\r\n for (let i = 1; i <= t; ++i) {\r\n const t = n.root(i),\r\n s = n.root(o),\r\n u = r.root(i),\r\n c = r.root(o)\r\n t !== s &&\r\n u !== c &&\r\n (n.merge(t, s), r.merge(u, c), e.println(o + ' ' + i))\r\n }\r\n const u = []\r\n for (let e = 1; e <= t; ++e) {\r\n const t = n.root(e),\r\n r = n.root(o)\r\n t !== r && (n.merge(t, r), u.push(e))\r\n }\r\n const c = []\r\n for (let e = 1; e <= t; ++e) {\r\n const t = r.root(e),\r\n n = r.root(o)\r\n t !== n && (r.merge(t, n), c.push(e))\r\n }\r\n for (let t = 0, n = Math.min(u.length, c.length); t < n; ++t) {\r\n const n = u[t],\r\n r = c[t]\r\n e.println(n + ' ' + r)\r\n }\r\n }\r\n})\r\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nfunction createHeuristicFindSet(e) {\r\n const t = new Array(e + 1),\r\n n = new Array(e + 1)\r\n let r = e\r\n return {\r\n init: function (e) {\r\n ;(r = e), n.fill(1, r + 1, 1)\r\n for (let e = 1; e <= r; ++e) t[e] = e\r\n },\r\n root: i,\r\n merge: function (e, r) {\r\n const o = i(e),\r\n s = i(r)\r\n if (o === s) return o\r\n if (n[o] > n[s]) return (t[s] = o), (n[o] += n[s]), o\r\n return (t[o] = s), s\r\n },\r\n }\r\n function i(e) {\r\n return t[e] === e ? e : (t[e] = i(t[e]))\r\n }\r\n}\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(e)\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(t => {\r\n stdin.on('data', t => e.push(t)),\r\n stdin.on('end', function () {\r\n const n = e.join('').split(os.EOL)\r\n t(n)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const t = new InputAndOutput()\r\n await t.init(), e(t)\r\n}\r\nfunction solve() {\r\n return -1\r\n}\r\n__main__(function (e) {\r\n const t = 100010,\r\n n = createHeuristicFindSet(t),\r\n r = createHeuristicFindSet(t)\r\n for (let t = 1; t <= 1; ++t) {\r\n const [t, i, o] = e.readIntegersOfLine()\r\n n.init(t), r.init(t)\r\n for (let t = 0; t < i; ++t) {\r\n const [t, r] = e.readIntegersOfLine()\r\n n.merge(t, r)\r\n }\r\n for (let t = 0; t < o; ++t) {\r\n const [t, n] = e.readIntegersOfLine()\r\n r.merge(t, n)\r\n }\r\n const s = [],\r\n u = Math.floor(Math.random() * t) + 1\r\n for (let e = 1; e <= t; ++e) {\r\n const t = n.root(e),\r\n i = n.root(u),\r\n o = r.root(e),\r\n c = r.root(u)\r\n t !== i && o !== c && (n.merge(t, i), r.merge(o, c), s.push([u, e]))\r\n }\r\n const c = []\r\n for (let e = 1; e <= t; ++e) {\r\n const t = n.root(e),\r\n r = n.root(u)\r\n t !== r && (n.merge(t, r), c.push(e))\r\n }\r\n const a = []\r\n for (let e = 1; e <= t; ++e) {\r\n const t = r.root(e),\r\n n = r.root(u)\r\n t !== n && (r.merge(t, n), a.push(e))\r\n }\r\n for (let e = 0, t = Math.min(c.length, a.length); e < t; ++e)\r\n s.push([c[e], a[e]])\r\n e.print(s.length + '\\n')\r\n for (const t of s) e.print(t.join(' ') + '\\n')\r\n }\r\n})\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst mxN = 1005;\r\n\r\nclass dsu {\r\n\tconstructor (n) {\r\n\t\tthis.components = n;\r\n\t\tthis.data = Array(n).fill(-1);\r\n\t}\r\n\tunite (a, b) {\r\n\t\ta = this.find(a);\r\n\t\tb = this.find(b);\r\n\t\tthis.data[a] += this.data[b];\r\n\t\tthis.data[b] = a;\r\n\t\tthis.components--;\r\n\t}\r\n\tfind (a) {\r\n\t\treturn this.data[a] < 0 ? a : this.data[a] = this.find(this.data[a]);\r\n\t}\r\n\tsize (a) {\r\n\t\treturn -this.data[this.find(a)];\r\n\t}\r\n\tgetcomponents () {\r\n\t\treturn this.components;\r\n\t}\r\n}\r\n\r\nfunction main () {\r\n\tconst [n, m1, m2] = rna();\r\n\r\n\tconst d1 = new dsu(n);\r\n\tconst d2 = new dsu(n);\r\n\r\n\tfor (let i = 0; i < m1; i++) {\r\n\t\tlet [u, v] = rna();\r\n\t\tu--; v--;\r\n\t\td1.unite(u, v);\r\n\t}\r\n\r\n\tfor (let i = 0; i < m2; i++) {\r\n\t\tlet [u, v] = rna();\r\n\t\tu--; v--;\r\n\t\td2.unite(u, v);\r\n\t}\r\n\r\n\tlet ans = [];\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tfor (let j = i + 1; j < n; j++) {\r\n\t\t\tif (d1.find(i) != d1.find(j) && d2.find(i) != d2.find(j)) {\r\n\t\t\t\td1.unite(i, j);\r\n\t\t\t\td2.unite(i, j);\r\n\t\t\t\tans.push([i+1, j+1]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tconsole.log(ans.length);\r\n\tfor (const edg of ans) {\r\n\t\tconsole.log(edg.join(' '));\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst mxN = 1005;\r\n\r\nconst f = Array.from(Array(2), x => []);\r\n\r\nfunction getf (id, x) {\r\n\tif (x == f[id][x]) return x;\r\n\treturn f[id][x] = getf(id, f[id][x]);\r\n}\r\n\r\nfunction main () {\r\n\tconst [n, m1, m2] = rna();\r\n\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tf[0][i] = f[1][i] = i;\r\n\t}\r\n\r\n\r\n\tfor (let i = 0; i < m1; i++) {\r\n\t\tlet [u, v] = rna();\r\n\t\tu--; v--;\r\n\t\tu = getf(0, u);\r\n\t\tv = getf(0, v);\r\n\t\tf[0][u] = v;\r\n\t}\r\n\r\n\tfor (let i = 0; i < m2; i++) {\r\n\t\tlet [u, v] = rna();\r\n\t\tu--; v--;\r\n\t\tu = getf(1, u);\r\n\t\tv = getf(1, v);\r\n\t\tf[1][u] = v;\r\n\t}\r\n\r\n\tlet ans = [];\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tfor (let j = i + 1; j < n; j++) {\r\n\t\t\tif (getf(0, i) != getf(0, j) && getf(1, i) != getf(1, j)) {\r\n\t\t\t\tf[0][getf(0, i)] = getf(0, j);\r\n\t\t\t\tf[1][getf(1, i)] = getf(1, j);\r\n\t\t\t\tans.push([i+1, j+1]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tconsole.log(ans.length);\r\n\tfor (const edg of ans) {\r\n\t\tconsole.log(edg.join(' '));\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nfunction createHeuristicFindSet(e) {\r\n const t = new Array(e + 1),\r\n n = new Array(e + 1)\r\n let r = e\r\n return {\r\n init: function (e) {\r\n ;(r = e), n.fill(1, r + 1, 1)\r\n for (let e = 1; e <= r; ++e) t[e] = e\r\n },\r\n root: i,\r\n merge: function (e, r) {\r\n const s = i(e),\r\n o = i(r)\r\n if (s === o) return s\r\n if (n[s] > n[o]) return (t[o] = s), (n[s] += n[o]), s\r\n return (t[s] = o), o\r\n },\r\n }\r\n function i(e) {\r\n return t[e] === e ? e : (t[e] = i(t[e]))\r\n }\r\n}\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(String(e))\r\n }\r\n println(e) {\r\n stdout.write(String(e)), stdout.write('\\n')\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(t => {\r\n stdin.on('data', t => e.push(t)),\r\n stdin.on('end', function () {\r\n const n = e.join('').split(os.EOL)\r\n t(n)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const t = new InputAndOutput()\r\n await t.init(), e(t)\r\n}\r\nfunction solve() {\r\n return -1\r\n}\r\n__main__(function (e) {\r\n const t = 100010,\r\n n = createHeuristicFindSet(t),\r\n r = createHeuristicFindSet(t)\r\n for (let t = 1; t <= 1; ++t) {\r\n const [t, i, s] = e.readIntegersOfLine()\r\n n.init(t), r.init(t)\r\n for (let t = 0; t < i; ++t) {\r\n const [t, r] = e.readIntegersOfLine()\r\n n.merge(t, r)\r\n }\r\n for (let t = 0; t < s; ++t) {\r\n const [t, n] = e.readIntegersOfLine()\r\n r.merge(t, n)\r\n }\r\n e.println(t - 1 - Math.max(i, s))\r\n const o = Math.floor(Math.random() * t) + 1\r\n for (let i = 1; i <= t; ++i) {\r\n const t = n.root(i),\r\n s = n.root(o),\r\n u = r.root(i),\r\n c = r.root(o)\r\n t !== s &&\r\n u !== c &&\r\n (n.merge(t, s), r.merge(u, c), e.println(o + ' ' + i))\r\n }\r\n const u = []\r\n for (let e = 1; e <= t; ++e) {\r\n const t = n.root(e),\r\n r = n.root(o)\r\n t !== r && (n.merge(t, r), u.push(e))\r\n }\r\n const c = []\r\n for (let e = 1; e <= t; ++e) {\r\n const t = r.root(e),\r\n n = r.root(o)\r\n t !== n && (r.merge(t, n), c.push(e))\r\n }\r\n for (let t = 0, n = Math.min(u.length, c.length); t < n; ++t) {\r\n const n = u[t]\r\n e.println(o + ' ' + n)\r\n }\r\n }\r\n})\r\n"}], "src_uid": "e3d2b67a62ac431718071ae20f3794aa"} {"nl": {"description": "You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\\{1, 2, 3\\}$$$ and $$$\\{1, 2, 4\\}$$$ are considered different, the sets $$$\\{2, 4, 6\\}$$$ and $$$\\{2, 6\\}$$$ — too, but sets $$$\\{3, 5\\}$$$ and $$$\\{5, 3\\}$$$ — not.For example, let the string $$$s =$$$ \"abababacababa\" and the string $$$t =$$$ \"aba\". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form \"ab...bac...ba\". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.", "input_spec": "The first line of the input contains a single integer $$$q$$$ ($$$1 \\le q \\le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \\le |s| \\le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \\le |t| \\le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.", "output_spec": "For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.", "sample_inputs": ["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"], "sample_outputs": ["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"], "notes": "NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ \"xyz\", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$."}, "positive_code": [{"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const s1 = lines[l++]\r\n const s2 = lines[l++]\r\n output[i] = solve(s1, s2)\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(s, t) {\r\n const ps = []\r\n for (let i = 0; i + t.length - 1 < s.length; i++) {\r\n if (s.slice(i, i + t.length) === t) ps.push(i)\r\n }\r\n if (!ps.length) return [0, 1].join(' ')\r\n// console.log(ps)\r\n const dp = Array(ps.length).fill(Infinity)\r\n const count = Array(ps.length).fill(1)\r\n let min = Infinity\r\n for (let i = 0; i < ps.length; i++) {\r\n for (let j = i - 1; j >= 0; j--) {\r\n if (ps[j] + t.length - 1 >= ps[i]) continue\r\n let has = 0\r\n for (let k = j + 1; k < i; k++) {\r\n if (ps[j] + t.length - 1 < ps[k] && ps[k] + t.length - 1 < ps[i]) {\r\n has = 1\r\n break\r\n }\r\n }\r\n if (has) continue\r\n // dp[i] = Math.min(dp[i], dp[j] + 1)\r\n // count[i] = add(count[i], count[j])\r\n if (dp[j] + 1 < dp[i]) {\r\n dp[i] = dp[j] + 1\r\n count[i] = count[j]\r\n } else if (dp[j] + 1 === dp[i]) {\r\n count[i] = add(count[i], count[j])\r\n }\r\n }\r\n if (dp[i] === Infinity) {\r\n dp[i] = 1\r\n // count[i] = 1\r\n }\r\n if (ps[i] + t.length - 1 >= ps[ps.length - 1]) {\r\n min = Math.min(min, dp[i])\r\n }\r\n }\r\n let ans = 0\r\n for (let i = 0; i < ps.length; i++) {\r\n if (ps[i] + t.length - 1 >= ps[ps.length - 1]\r\n && dp[i] === min) {\r\n ans = add(ans, count[i])\r\n }\r\n }\r\n// console.log(dp, count)\r\n return min + ' ' + ans\r\n}\r\nfunction add(a, b) {\r\n return (a + b) % (1e9 + 7)\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const s = read(),\r\n t = read();\r\n const n = s.length,\r\n m = t.length;\r\n const MOD = 10 ** 9 + 7;\r\n const mod = num => num % MOD;\r\n const p = new Array(n).fill(0);\r\n for (let i = 0; i <= n - m; i++) {\r\n let flag = 1;\r\n for (let j = 0; j < m; j++) {\r\n if (s[i + j] !== t[j]) {\r\n flag = 0;\r\n break;\r\n }\r\n }\r\n p[i + m - 1] = flag;\r\n }\r\n const dp = [];\r\n for (let i = 0; i <= n - m; i++) {\r\n if (!p[i + m - 1]) continue;\r\n let ans = [Infinity, Infinity];\r\n for (let j = 0; j < i; j++) {\r\n if (dp[j] && dp[j][2] >= i - 1) {\r\n if (dp[j][0] < ans[0]) {\r\n ans = [...dp[j]];\r\n } else if (dp[j][0] === ans[0]) {\r\n ans[1] = mod(ans[1] + dp[j][1]);\r\n }\r\n }\r\n }\r\n if (ans[0] === Infinity) ans = [1, 1, n - 1];else {\r\n ans[0]++;\r\n ans[2] = n - 1;\r\n }\r\n for (let j = i + m * 2 - 1; j < n; j++) {\r\n if (p[j]) {\r\n ans[2] = j - 1;\r\n break;\r\n }\r\n }\r\n dp[i + m - 1] = ans;\r\n }\r\n let res = 0,\r\n max = Infinity;\r\n for (let i = 0; i < n; i++) {\r\n if (dp[i] && dp[i][2] === n - 1) {\r\n if (dp[i][0] < max) {\r\n max = dp[i][0];\r\n res = dp[i][1];\r\n } else if (dp[i][0] === max) {\r\n res = mod(res + dp[i][1]);\r\n }\r\n }\r\n }\r\n if (max === Infinity) return `0 1`;\r\n return `${max} ${res}`;\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= 100) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r\\n?/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const s1 = lines[l++]\n const s2 = lines[l++]\n output[i] = solve(s1, s2)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(s, t) {\n const ps = []\n for (let i = 0; i + t.length - 1 < s.length; i++) {\n if (s.slice(i, i + t.length) === t) ps.push(i)\n }\n if (!ps.length) return [0, 1].join(' ')\n// console.log(ps)\n const dp = Array(ps.length).fill(Infinity)\n const count = Array(ps.length).fill(1)\n let ans = 0\n for (let i = 0; i < ps.length; i++) {\n for (let j = i - 1; j >= 0; j--) {\n if (ps[j] + t.length - 1 >= ps[i]) continue\n let has = 0\n for (let k = j + 1; k < i; k++) {\n if (ps[j] + t.length - 1 < ps[k] && ps[k] + t.length - 1 < ps[i]) {\n has = 1\n break\n }\n }\n if (has) continue\n // dp[i] = Math.min(dp[i], dp[j] + 1)\n // count[i] = add(count[i], count[j])\n if (dp[j] + 1 < dp[i]) {\n dp[i] = dp[j] + 1\n count[i] = count[j]\n } else if (dp[j] + 1 === dp[i]) {\n count[i] = add(count[i], count[j])\n }\n }\n if (dp[i] === Infinity) {\n dp[i] = 1\n // count[i] = 1\n }\n if (ps[i] + t.length - 1 >= ps[ps.length - 1]) {\n ans = add(ans, count[i])\n }\n }\n// console.log(dp, count)\n return dp[ps.length - 1] + ' ' + ans\n}\nfunction add(a, b) {\n return (a + b) % (1e9 + 7)\n}\n"}], "src_uid": "904af5d6a9d84b7b7b7ff8d63e6f0254"} {"nl": {"description": "You are given a binary string $$$s$$$ of length $$$n$$$.Let's define $$$d_i$$$ as the number whose decimal representation is $$$s_i s_{i+1}$$$ (possibly, with a leading zero). We define $$$f(s)$$$ to be the sum of all the valid $$$d_i$$$. In other words, $$$f(s) = \\sum\\limits_{i=1}^{n-1} d_i$$$.For example, for the string $$$s = 1011$$$: $$$d_1 = 10$$$ (ten); $$$d_2 = 01$$$ (one) $$$d_3 = 11$$$ (eleven); $$$f(s) = 10 + 01 + 11 = 22$$$. In one operation you can swap any two adjacent elements of the string. Find the minimum value of $$$f(s)$$$ that can be achieved if at most $$$k$$$ operations are allowed.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^5$$$). Description of the test cases follows. First line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^5$$$, $$$0 \\le k \\le 10^9$$$) — the length of the string and the maximum number of operations allowed. The second line of each test case contains the binary string $$$s$$$ of length $$$n$$$, consisting of only zeros and ones. It is also given that sum of $$$n$$$ over all the test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print the minimum value of $$$f(s)$$$ you can obtain with at most $$$k$$$ operations.", "sample_inputs": ["3\n\n4 0\n\n1010\n\n7 1\n\n0010100\n\n5 2\n\n00110"], "sample_outputs": ["21\n22\n12"], "notes": "Note For the first example, you can't do any operation so the optimal string is $$$s$$$ itself. $$$f(s) = f(1010) = 10 + 01 + 10 = 21$$$. For the second example, one of the optimal strings you can obtain is \"0011000\". The string has an $$$f$$$ value of $$$22$$$. For the third example, one of the optimal strings you can obtain is \"00011\". The string has an $$$f$$$ value of $$$12$$$. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i + 1;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i < Math.min(m + 1, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n break;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, k] = ra();\n let s = readline();\n LT({n, k, s});\n // PROCESSING:\n let sum = 0;\n let lastPos = -1;\n let firstPos = -1;\n for (let i=0; i0)\n sum += 1;\n lastPos = i;\n if (firstPos==-1)\n firstPos = i;\n }\n L({lastPos, n, k})\n let taken = false;\n if (lastPos=0 && n-1-lastPos<=k){\n sum -= 10;\n k-= n-lastPos-1;\n taken = true;\n if (lastPos==0)\n sum += 1;\n }\n if ((firstPos!=lastPos || !taken) && firstPos>0 && firstPos<=k && firstPos 0; i--) {\r\n if (S[i] === \"0\") zeroPadRight += 1;\r\n else break;\r\n }\r\n if (zeroPadRight === N - 1) zeroPadRight = 0;\r\n\r\n if (S[N - 1] === \"1\") sum += 1;\r\n else if (life > 0 && zeroPadRight > 0 && life >= zeroPadRight) {\r\n sum -= 10;\r\n life -= zeroPadRight;\r\n S[N - 1] = \"1\";\r\n S[N - 1 - zeroPadRight] = \"0\";\r\n }\r\n\r\n let zeroPadLeft = 0;\r\n for (let i = 0; i < N - 1; i++) {\r\n if (S[i] === \"0\") zeroPadLeft += 1;\r\n else break;\r\n }\r\n if (zeroPadLeft === N - 1) zeroPadLeft = 0;\r\n\r\n if (S[0] === \"1\") sum += 10;\r\n else if (life > 0 && zeroPadLeft > 0 && life >= zeroPadLeft) {\r\n sum -= 1;\r\n }\r\n\r\n if (S[0] === \"1\" && S[N - 1] === \"0\" && life >= N - 1) {\r\n sum -= 9;\r\n }\r\n\r\n results.push(sum);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "/**\n * Format:\n * {type: 'number', namedVariable?: string }\n * {type: 'repeat', instructionCount: number, count: number, namedVariable?: string }\n * {type: 'array', namedVariable?: string }\n * {type: 'string', namedVariable?: string }\n */\nconst readline = require('readline');\n\nfunction createCLIReader(instructions) {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const mappedVariables = {};\n\n let resolvePromise = null;\n const donePromise = new Promise((res, rej) => {\n resolvePromise = res;\n });\n\n function waitUntilDone() {\n return donePromise;\n }\n\n /**\n * {type: 'repeat', count: number, iteration: number, basePointer: number, pointer: number, instructionCount: number, context: array }\n */\n const stack = [];\n let pc = -1;\n\n function finished() {\n if (pc >= instructions.length) {\n return true;\n }\n return false;\n }\n\n function checkFinished() {\n // console.log(`Finish check ${pc}, ${JSON.stringify(stack)}, ${pc >= instructions.length}, ${stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1}`);\n if (pc >= instructions.length) {\n return true;\n }\n if (stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1) {\n return true;\n }\n return false;\n }\n\n function getNextInstructionContext() {\n if (!stack.length) {\n return {\n index: ++pc,\n }\n }\n const lastStack = stack[stack.length - 1];\n if (lastStack.pointer === lastStack.instructionCount) {\n lastStack.pointer = 0;\n lastStack.iteration = lastStack.iteration + 1;\n }\n if (lastStack.count === lastStack.iteration) {\n stack.pop();\n pc = lastStack.basePointer + lastStack.instructionCount + 1;\n return {\n index: pc,\n }\n }\n\n lastStack.pointer = lastStack.pointer + 1;\n return {\n index: lastStack.basePointer + lastStack.pointer,\n context: {\n namedPath: [...lastStack.context.namedPath, lastStack.iteration]\n }\n }\n }\n\n function pushRepeatToStack(instruction, index, context) {\n stack.push({\n type: 'repeat',\n count: typeof instruction.count === 'number' ? instruction.count : context && context.namedPath ? getIn(mappedVariables, [...context.namedPath, instruction.count]) : mappedVariables[instruction.count],\n iteration: 0,\n basePointer: index,\n pointer: 0,\n instructionCount: instruction.instructionCount,\n context: {\n namedPath: context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable],\n }\n })\n setIn(mappedVariables, context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable], []);\n }\n\n function nextInstruction() {\n if (finished()) {\n // console.warn('Calling nextInstruction after finished, something is wrong');\n return;\n }\n while (true) {\n const { index, context } = getNextInstructionContext();\n const instruction = instructions[index];\n\n // console.log(`Debugging: ${index}, ${JSON.stringify(context)}, ${JSON.stringify(instruction)}`);\n switch (instruction.type) {\n case 'number':\n case 'array':\n case 'string':\n return {\n ...instruction,\n namedPath: instruction.namedVariable ? context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable] : undefined,\n }\n case 'repeat':\n pushRepeatToStack(instruction, index, context);\n break;\n default:\n // console.warn('Unclear instruction, abort');\n return;\n }\n }\n }\n\n function getIn(object, path) {\n for (let i = 0; i < path.length; ++i) {\n object = object[path[i]];\n }\n return object;\n }\n\n function setIn(object, path, value) {\n for (let i = 0; i < path.length - 1; ++i) {\n if (object[path[i]] == null) {\n object[path[i]] = {};\n }\n object = object[path[i]];\n }\n object[path[path.length - 1]] = value;\n }\n\n rl.on('line', line => {\n if (finished()) {\n return;\n }\n const { type, namedPath } = nextInstruction();\n switch (type) {\n case 'number':\n if (namedPath) {\n setIn(mappedVariables, namedPath, parseInt(line));\n }\n break;\n case 'string':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim());\n }\n break;\n case 'array':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim().split(' ').map(x => parseInt(x)));\n }\n break;\n default:\n // console.warn(`Value unread, received type ${type}.`);\n }\n\n if (checkFinished()) {\n resolvePromise(mappedVariables);\n rl.close();\n }\n });\n return {\n waitUntilDone,\n };\n}\n\nfunction solve(testCase) {\n let k = testCase.lengthAndPermit[1];\n\n let oneCount = 0;\n let firstOne = -1;\n let lastOne = -1;\n for (let i = 0; i < testCase.theInput.length; ++i) {\n if (testCase.theInput[i] === '1') {\n if (firstOne === -1) {\n firstOne = i;\n }\n lastOne = i;\n ++oneCount;\n }\n }\n\n if (oneCount === 0) {\n return 0;\n }\n\n if (oneCount === testCase.theInput.length) {\n return 11 * (oneCount - 1);\n }\n\n let preliminarySum = 11 * oneCount;\n const distanceToLast = testCase.theInput.length - 1 - lastOne;\n const distanceToFirst = firstOne;\n\n let usedOne = false;\n if (k - distanceToLast >= 0) {\n k -= distanceToLast;\n preliminarySum -= 10;\n usedOne = true;\n }\n if (k - distanceToFirst >= 0 && (oneCount > 1 || !usedOne)) {\n preliminarySum -= 1;\n }\n\n return preliminarySum;\n}\n\n(async function main() {\n const reader = createCLIReader([\n { type: 'number', namedVariable: 'numberOfTestCase' },\n { type: 'repeat', instructionCount: 2, count: 'numberOfTestCase', namedVariable: 'testCase' },\n { type: 'array', namedVariable: 'lengthAndPermit' },\n { type: 'string', namedVariable: 'theInput' }\n ]);\n const schema = await reader.waitUntilDone();\n\n for (let i = 0; i < schema.numberOfTestCase; ++i) {\n console.log(solve(schema.testCase[i]));\n }\n})();\n"}, {"source_code": "class Scaner {\r\n data = [];\r\n constructor() {\r\n process.stdin.setEncoding('utf-8');\r\n process.stdin.on('data', _data => {\r\n let lasttext = this.data.pop();\r\n if (lasttext == undefined)\r\n lasttext = \"\"\r\n _data = lasttext + _data;\r\n const l = _data.split('\\n');\r\n this.data = this.data.concat(l.slice(0, -1).map(string => string.trim()), l[l.length - 1]);\r\n });\r\n }\r\n read = async () => {\r\n process.stdin.resume();\r\n while (this.data.length < 2) {\r\n await delay(0);\r\n }\r\n process.stdin.pause();\r\n let res = this.data.shift();\r\n if (res == \"\")\r\n return await read();\r\n return res;\r\n };\r\n}\r\nconst delay = (ms=0) => new Promise(resolve => setTimeout(resolve, ms));\r\nconst print = (text) => process.stdout.write(\"\" + text);\r\nconst scaner = new Scaner()\r\nconst read = scaner.read;\r\n//----------------------------------------------------------------\r\n//-----------------------the-code---------------------------------\r\n//----------------------------------------------------------------\r\n\r\n(async () => {\r\n let t = parseInt(await read());\r\n while (t--) {\r\n let [n,k]=(await read()).split(' ').map(Number);\r\n let a=await read();\r\n let ans=0;\r\n let i,j;\r\n for (i = a.length-1; i >= 0; i--){\r\n const e = a[i];\r\n if(e=='1'){\r\n const cost=a.length-i-1;\r\n if(cost<=k){\r\n k-=cost;\r\n ans+=1;\r\n }else{\r\n i++;\r\n }\r\n break;\r\n }\r\n }\r\n for (j = 0; j < i; j++){\r\n const e = a[j];\r\n if(e=='1'){\r\n const cost=j;\r\n if(cost<=k){\r\n k-=cost;\r\n ans+=10;\r\n }else{\r\n ans+=11;\r\n }\r\n break;\r\n \r\n }\r\n }\r\n for (j++; j < i; j++){\r\n if(a[j]=='1'){\r\n ans+=11;\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n})().then(() => { }\r\n)\r\n\r\n\r\n\r\n"}, {"source_code": "function solve() {\r\n let [n, k] = readArray(Number);\r\n const bitStr = read();\r\n let countOne = 0;\r\n let firstOne = n;\r\n let lastOne = -1;\r\n for (let i = 0; i < n; i++) {\r\n if (bitStr[i] === '0') {\r\n continue;\r\n }\r\n countOne++;\r\n if (i > lastOne) {\r\n lastOne = i;\r\n }\r\n if (i < firstOne) {\r\n firstOne = i;\r\n }\r\n }\r\n if (countOne === 0) {\r\n write(0);\r\n return;\r\n }\r\n const leftSwaps = firstOne;\r\n const rigthSwaps = n - lastOne - 1;\r\n if (countOne === 1) {\r\n if (rigthSwaps <= k) {\r\n write(1);\r\n return;\r\n }\r\n if (leftSwaps <= k) {\r\n write(10);\r\n return;\r\n }\r\n write(11);\r\n return;\r\n }\r\n let ans = countOne * 11;;\r\n if (rigthSwaps <= k) {\r\n k -= rigthSwaps;\r\n ans -= 10;\r\n }\r\n if (leftSwaps <= k) {\r\n ans -= 1;\r\n }\r\n write(ans);\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e + e.stack);\r\n }\r\n}\r\n\r\nfunction modPow(a, n, mod) {\r\n let d = a;\r\n let curN = n;\r\n let ans = 1n;\r\n while(curN) {\r\n if (curN & 1n) {\r\n ans = modMul(ans, d, mod);\r\n }\r\n curN >>= 1n;\r\n d = modMul(d, d, mod);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction modMul(a, b, mod) {\r\n return (a * b) % mod;\r\n}\r\n\r\nfunction modSum(a, b, mod) {\r\n return (a + b) % mod;\r\n}\r\n\r\nfunction modDiff(a, b, mod) {\r\n return (a + mod - b) % mod;\r\n}\r\n\r\nfunction isZero(num) {\r\n if (typeof num === 'bigint') {\r\n return num === 0n;\r\n }\r\n return num === 0;\r\n}\r\nfunction div(a, b) {\r\n if (typeof a !== typeof b) {\r\n throw new Error('Different types on division');\r\n }\r\n if (typeof a === 'bigint') {\r\n return a / b;\r\n }\r\n return Math.floor(a / b);\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if (isZero(y)) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction lcm(x, y) {\r\n return div(x * y, gcd(x, y));\r\n}\r\n\r\nfunction allIndexOf(arr, value) {\r\n var index = arr.indexOf(value)\r\n var ans = [];\r\n while (index !== -1) {\r\n ans.push(index);\r\n index = arr.indexOf(value, index + 1);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction xor(a, b, k) {\r\n if (k === 2) {\r\n return a ^ b;\r\n }\r\n}\r\n\r\nfunction decToBin(num) {\r\n let n = num;\r\n const ans = [];\r\n while(n > 0) {\r\n ans.push(n & 1);\r\n n = (n >> 1);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction binToDec(binN) {\r\n let ans = 0;\r\n for (let i = binN.length - 1; i >= 0; i--) {\r\n ans = ((ans << 1) | binN[i]);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i + 1;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i < Math.min(m + 1, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n const t1=t\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n if(t1===243&&t1-t===69){\r\n console.log(`${m} ${n} ${s}`)\r\n return\r\n }\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i + 1;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i < Math.min(m + 1, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n const t1=t\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n if(t===243&&t1-t===69){\r\n console.log(`${m} ${n} ${s}`)\r\n return\r\n }\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i + 1;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i < Math.min(m + 1, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n const t1=t\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n if(t===243&&t1-t===69)console.log(`${m} ${n} ${s}`)\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i + 1;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i < Math.min(m + 1, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i <= Math.min(m, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += Number(s[i - 1] + s[i]);\r\n }\r\n let t = 0;\r\n if (s[n - 1] !== '1') {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (s[i] === '1') break;\r\n t++;\r\n }\r\n if (m >= t) {\r\n sum -= 10;\r\n m -= t;\r\n }\r\n }\r\n if (s[0] !== '1') {\r\n for (let i = 0; i < Math.min(n - t - 1, m + 1); i++) {\r\n if (s[i] === '1') {\r\n return sum - 1;\r\n }\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i <= Math.min(m, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const nums = s.split('').map(str => Number(str));\r\n let t = n;\r\n if (nums[n - 1] === 0) {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (nums[i]) {\r\n if (n - i - 1 <= m) {\r\n m -= n - i - 1;\r\n nums[i] = 0;\r\n nums[n - 1] = 1;\r\n t = i + 1;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n if (nums[0] === 0) {\r\n for (let i = 0; i < Math.min(m + 1, t - 1); i++) {\r\n if (nums[i]) {\r\n nums[i] = 0;\r\n nums[0] = 1;\r\n }\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += nums[i - 1] * 10 + nums[i];\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += Number(s[i - 1] + s[i]);\r\n }\r\n let t = 0;\r\n if (s[n - 1] !== '1') {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (s[i] === '1') break;\r\n t++;\r\n }\r\n if (m >= t) {\r\n sum -= 10;\r\n m -= t;\r\n }\r\n }\r\n if (s[0] !== '1') {\r\n for (let i = 0; i < Math.min(n - t - 1, m + 1); i++) {\r\n if (s[i] === '1') {\r\n return sum - 1;\r\n }\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += Number(s[i - 1] + s[i]);\r\n }\r\n let t = 0;\r\n if (s[n - 1] !== '1') {\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (s[i] === '1') break;\r\n t++;\r\n }\r\n if (m >= t) {\r\n sum -= 10;\r\n m -= t;\r\n }\r\n }\r\n if (s[0] !== '1') {\r\n for (let i = 0; i < n - t - 1; i++) {\r\n if (s[i] === '1') {\r\n if (i <= m) return sum - 1;else break;\r\n }\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n sum += Number(s[i - 1] + s[i]);\r\n }\r\n if (s[n - 1] !== '1') {\r\n let i = 0;\r\n while (m-- > 0) {\r\n if (s[n - i - 1] === '1') {\r\n sum -= 10;\r\n break;\r\n }\r\n i++;\r\n }\r\n }\r\n if (s[0] !== '0') {\r\n let i = 0;\r\n while (m-- > 0) {\r\n if (s[i] === '1') {\r\n sum -= 1;\r\n break;\r\n }\r\n i++;\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, k] = ra();\n let s = readline();\n LT({n, k, s});\n // PROCESSING:\n let sum = 0;\n let lastPos = -1;\n let firstPos = -1;\n for (let i=0; i0)\n sum += 1;\n lastPos = i;\n if (firstPos==-1)\n firstPos = i;\n }\n L({lastPos, n, k})\n let taken = true;\n if (lastPos=0 && n-lastPos<=k+1){\n sum -= 10;\n k-= n-lastPos-1;\n //taken = true;\n if (lastPos==0)\n sum += 1;\n }\n if ((firstPos!=lastPos || !taken) && firstPos>0 && firstPos<=k){\n sum--;\n }\n return sum;\n};\n \n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, k] = ra();\n let s = readline();\n LT({n, k, s});\n // PROCESSING:\n let sum = 0;\n let lastPos = -1;\n let firstPos = -1;\n for (let i=0; i0)\n sum += 1;\n lastPos = i;\n if (firstPos==-1)\n firstPos = i;\n }\n L({lastPos, n, k})\n let taken = false;\n if (lastPos=0 && n-lastPos<=k+1){\n sum -= 10;\n k-= n-lastPos-1;\n //taken = true;\n if (lastPos==0)\n sum += 1;\n }\n if ((firstPos!=lastPos || !taken) && firstPos>0 && firstPos<=k){\n sum--;\n }\n return sum;\n};\n \n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, k] = ra();\n let s = readline();\n LT({n, k, s});\n // PROCESSING:\n let sum = 0;\n let lastPos = -1;\n let firstPos = -1;\n for (let i=0; i0)\n sum += 1;\n lastPos = i;\n if (firstPos==-1)\n firstPos = i;\n }\n L({lastPos, n, k})\n let taken = false;\n if (lastPos=0 && n-lastPos<=k+1){\n sum -= 10;\n k-= n-lastPos-1;\n taken = true;\n if (lastPos==0)\n sum += 1;\n }\n if ((firstPos!=lastPos || !taken) && firstPos>0 && firstPos<=k){\n sum--;\n }\n return sum;\n};\n \n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, k] = ra();\n let s = readline();\n LT({n, k, s});\n // PROCESSING:\n let sum = 0;\n let lastPos = -1;\n let firstPos = -1;\n for (let i=0; i0)\n sum += 1;\n lastPos = i;\n if (firstPos==-1)\n firstPos = i;\n }\n L({lastPos, n, k})\n if (lastPos=0 && n-lastPos<=k+1){\n sum -= 10;\n k-= n-lastPos-1;\n if (lastPos==0)\n sum += 1;\n }\n if (firstPos!=lastPos && firstPos>0 && firstPos<=k){\n sum--;\n }\n return sum;\n};\n \n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, k] = ra();\n let s = readline();\n LT({n, k, s});\n // PROCESSING:\n let sum = 0;\n let lastPos = -1;\n for (let i=0; i0)\n sum += 1;\n lastPos = i;\n }\n L({lastPos, n, k})\n if (lastPos=0 && n-lastPos<=k+1){\n sum -= 10;\n if (lastPos==0)\n sum += 1;\n\n }\n return sum;\n};\n \n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, k] = ra();\n let s = readline();\n LT({n, k, s});\n // PROCESSING:\n let sum = 0;\n let lastPos = -1;\n for (let i=0; i0)\n sum += 1;\n lastPos = i;\n }\n L({lastPos, n, k})\n if (lastPos>=0 && n-lastPos<=k+1){\n sum -= 10;\n if (lastPos==0)\n sum += 1;\n\n }\n return sum;\n};\n \n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n const results = [];\r\n for (let tc = 0; tc < T; tc++) {\r\n const [N, K] = input.next().value.split(\" \").map(Number);\r\n let S = input.next().value.split(\"\");\r\n let life = K;\r\n let sum = 0;\r\n for (let i = 1; i < N - 1; i++) {\r\n if (S[i] === \"1\") sum += 11;\r\n }\r\n\r\n let zeroPadRight = 0;\r\n for (let i = N - 1; i > 0; i--) {\r\n if (S[i] === \"0\") zeroPadRight += 1;\r\n else break;\r\n }\r\n if (zeroPadRight === N - 1) zeroPadRight = 0;\r\n\r\n if (S[N - 1] === \"1\") sum += 1;\r\n else if (life > 0 && zeroPadRight > 0 && life >= zeroPadRight) {\r\n sum -= 10;\r\n life -= zeroPadRight;\r\n S[N - 1] = \"1\";\r\n S[N - 1 - zeroPadRight] = \"0\";\r\n }\r\n\r\n let zeroPadLeft = 0;\r\n for (let i = 0; i < N - 1; i++) {\r\n if (S[i] === \"0\") zeroPadLeft += 1;\r\n else break;\r\n }\r\n if (zeroPadLeft === N - 1) zeroPadLeft = 0;\r\n\r\n if (S[0] === \"1\") sum += 10;\r\n else if (life > 0 && zeroPadLeft > 0 && life > zeroPadLeft) {\r\n sum -= 10;\r\n }\r\n\r\n if (S[0] === \"1\" && S[N - 1] === \"0\" && life >= N - 1) {\r\n sum -= 9;\r\n }\r\n\r\n results.push(sum);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n const results = [];\r\n for (let tc = 0; tc < T; tc++) {\r\n const [N, K] = input.next().value.split(\" \").map(Number);\r\n let S = input.next().value.split(\"\");\r\n let life = K;\r\n let sum = 0;\r\n for (let i = 1; i < N - 1; i++) {\r\n if (S[i] === \"1\") sum += 11;\r\n }\r\n\r\n let zeroPadRight = 0;\r\n for (let i = N - 1; i > 0; i--) {\r\n if (S[i] === \"0\") zeroPadRight += 1;\r\n else break;\r\n }\r\n if (zeroPadRight === N - 1) zeroPadRight = 0;\r\n\r\n if (S[N - 1] === \"1\") sum += 1;\r\n else if (life > 0 && zeroPadRight > 0 && life >= zeroPadRight) {\r\n sum -= 10;\r\n life -= zeroPadRight;\r\n S[N - 1] = \"1\";\r\n S[N - 1 - zeroPadRight] = \"0\";\r\n }\r\n\r\n let zeroPadLeft = 0;\r\n for (let i = 0; i < N - 1; i++) {\r\n if (S[i] === \"0\") zeroPadLeft += 1;\r\n else break;\r\n }\r\n if (zeroPadLeft === N - 1) zeroPadLeft = 0;\r\n\r\n if (S[0] === \"1\") sum += 10;\r\n else if (life > 0 && zeroPadLeft > 0 && life > zeroPadLeft) {\r\n sum -= 10;\r\n }\r\n\r\n if (S[0] === \"1\" && S[N - 1] === \"1\" && life >= N - 1) {\r\n sum -= 9;\r\n }\r\n\r\n results.push(sum);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n const results = [];\r\n for (let tc = 0; tc < T; tc++) {\r\n const [N, K] = input.next().value.split(\" \").map(Number);\r\n let S = input.next().value.split(\"\");\r\n let life = K;\r\n let sum = 0;\r\n for (let i = 1; i < N - 1; i++) {\r\n if (S[i] === \"1\") sum += 11;\r\n }\r\n\r\n let zeroPadRight = 0;\r\n for (let i = N - 1; i >= 0; i--) {\r\n if (S[i] === \"0\") zeroPadRight += 1;\r\n else break;\r\n }\r\n if (zeroPadRight === N) zeroPadRight = 0;\r\n\r\n if (S[N - 1] === \"1\") sum += 1;\r\n else if (life > 0 && zeroPadRight > 0 && life >= zeroPadRight) {\r\n sum -= 10;\r\n life -= zeroPadRight;\r\n S[N - 1] = \"1\";\r\n S[N - 1 - zeroPadRight] = \"0\";\r\n }\r\n\r\n let zeroPadLeft = 0;\r\n for (let i = 0; i < N - 1; i++) {\r\n if (S[i] === \"0\") zeroPadLeft += 1;\r\n else break;\r\n }\r\n if (zeroPadLeft === N - 1) zeroPadLeft = 0;\r\n\r\n if (S[0] === \"1\") sum += 10;\r\n else if (life > 0 && zeroPadLeft > 0 && life > zeroPadLeft) {\r\n sum -= 10;\r\n }\r\n\r\n results.push(sum);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n const results = [];\r\n for (let tc = 0; tc < T; tc++) {\r\n const [N, K] = input.next().value.split(\" \").map(Number);\r\n let S = input.next().value.split(\"\");\r\n let life = K;\r\n let sum = 0;\r\n for (let i = 1; i < N - 1; i++) {\r\n if (S[i] === \"1\") sum += 11;\r\n }\r\n\r\n let zeroPadRight = 0;\r\n for (let i = N - 1; i >= 0; i--) {\r\n if (S[i] === \"0\") zeroPadRight += 1;\r\n else break;\r\n }\r\n if (zeroPadRight === N) zeroPadRight = 0;\r\n\r\n if (S[N - 1] === \"1\") sum += 1;\r\n else if (life > 0 && zeroPadRight > 0 && life >= zeroPadRight) {\r\n sum -= 10;\r\n life -= zeroPadRight;\r\n S[N - 1] = \"1\";\r\n S[N - 1 - zeroPadRight] = \"0\";\r\n }\r\n\r\n let zeroPadLeft = 0;\r\n for (let i = 0; i < N; i++) {\r\n if (S[i] === \"0\") zeroPadLeft += 1;\r\n else break;\r\n }\r\n if (zeroPadLeft === N) zeroPadLeft = 0;\r\n\r\n if (S[0] === \"1\") sum += 10;\r\n else if (life > 0 && zeroPadLeft > 0 && life > zeroPadLeft) {\r\n sum -= 10;\r\n }\r\n\r\n results.push(sum);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n const results = [];\r\n for (let tc = 0; tc < T; tc++) {\r\n const [N, K] = input.next().value.split(\" \").map(Number);\r\n let S = input.next().value.split(\"\");\r\n let life = K;\r\n let sum = 0;\r\n for (let i = 1; i < N - 1; i++) {\r\n if (S[i] === \"1\") sum += 11;\r\n }\r\n\r\n let zeroPadRight = 0;\r\n for (let i = N - 1; i >= 0; i--) {\r\n if (S[i] === \"0\") zeroPadRight += 1;\r\n else break;\r\n }\r\n\r\n if (S[N - 1] === \"1\") sum += 1;\r\n else if (life > 0 && zeroPadRight > 0 && life >= zeroPadRight) {\r\n sum -= 10;\r\n life -= zeroPadRight;\r\n S[N - 1] = \"1\";\r\n S[N - 1 - zeroPadRight] = \"0\";\r\n }\r\n\r\n let zeroPadLeft = 0;\r\n for (let i = 0; i < N; i++) {\r\n if (S[i] === \"0\") zeroPadLeft += 1;\r\n else break;\r\n }\r\n if (S[0] === \"1\") sum += 10;\r\n else if (life > 0 && zeroPadLeft > 0 && life > zeroPadLeft) {\r\n sum -= 10;\r\n }\r\n\r\n results.push(sum);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n}).on(\"close\", function () {\r\n solution(input);\r\n process.exit();\r\n});\r\n\r\nfunction solution(_input) {\r\n const input = _input[Symbol.iterator]();\r\n const T = Number(input.next().value);\r\n const results = [];\r\n for (let tc = 0; tc < T; tc++) {\r\n const [N, K] = input.next().value.split(\" \").map(Number);\r\n let S = input.next().value.split(\"\");\r\n let life = K;\r\n let sum = 0;\r\n for (let i = 1; i < N - 1; i++) {\r\n if (S[i] === \"1\") sum += 11;\r\n }\r\n\r\n let zeroPadRight = 0;\r\n for (let i = N - 1; i >= 0; i--) {\r\n if (S[i] === \"0\") zeroPadRight += 1;\r\n else break;\r\n }\r\n\r\n if (S[N - 1] === \"1\") sum += 1;\r\n else if (life !== 0 && life >= zeroPadRight) {\r\n sum -= 10;\r\n life -= zeroPadRight;\r\n S[N - 1] = \"1\";\r\n S[N - 1 - zeroPadRight] = \"0\";\r\n }\r\n\r\n let zeroPadLeft = 0;\r\n for (let i = 0; i < N; i++) {\r\n if (S[i] === \"0\") zeroPadLeft += 1;\r\n else break;\r\n }\r\n if (S[0] === \"1\") sum += 10;\r\n else if (life !== 0 && life > zeroPadLeft) {\r\n sum -= 10;\r\n }\r\n\r\n results.push(sum);\r\n }\r\n console.log(results.join(\"\\n\"));\r\n}\r\n"}, {"source_code": "/**\n * Format:\n * {type: 'number', namedVariable?: string }\n * {type: 'repeat', instructionCount: number, count: number, namedVariable?: string }\n * {type: 'array', namedVariable?: string }\n * {type: 'string', namedVariable?: string }\n */\nconst readline = require('readline');\n\nfunction createCLIReader(instructions) {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const mappedVariables = {};\n\n let resolvePromise = null;\n const donePromise = new Promise((res, rej) => {\n resolvePromise = res;\n });\n\n function waitUntilDone() {\n return donePromise;\n }\n\n /**\n * {type: 'repeat', count: number, iteration: number, basePointer: number, pointer: number, instructionCount: number, context: array }\n */\n const stack = [];\n let pc = -1;\n\n function finished() {\n if (pc >= instructions.length) {\n return true;\n }\n return false;\n }\n\n function checkFinished() {\n // console.log(`Finish check ${pc}, ${JSON.stringify(stack)}, ${pc >= instructions.length}, ${stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1}`);\n if (pc >= instructions.length) {\n return true;\n }\n if (stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1) {\n return true;\n }\n return false;\n }\n\n function getNextInstructionContext() {\n if (!stack.length) {\n return {\n index: ++pc,\n }\n }\n const lastStack = stack[stack.length - 1];\n if (lastStack.pointer === lastStack.instructionCount) {\n lastStack.pointer = 0;\n lastStack.iteration = lastStack.iteration + 1;\n }\n if (lastStack.count === lastStack.iteration) {\n stack.pop();\n pc = lastStack.basePointer + lastStack.instructionCount + 1;\n return {\n index: pc,\n }\n }\n\n lastStack.pointer = lastStack.pointer + 1;\n return {\n index: lastStack.basePointer + lastStack.pointer,\n context: {\n namedPath: [...lastStack.context.namedPath, lastStack.iteration]\n }\n }\n }\n\n function pushRepeatToStack(instruction, index, context) {\n stack.push({\n type: 'repeat',\n count: typeof instruction.count === 'number' ? instruction.count : context && context.namedPath ? getIn(mappedVariables, [...context.namedPath, instruction.count]) : mappedVariables[instruction.count],\n iteration: 0,\n basePointer: index,\n pointer: 0,\n instructionCount: instruction.instructionCount,\n context: {\n namedPath: context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable],\n }\n })\n setIn(mappedVariables, context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable], []);\n }\n\n function nextInstruction() {\n if (finished()) {\n // console.warn('Calling nextInstruction after finished, something is wrong');\n return;\n }\n while (true) {\n const { index, context } = getNextInstructionContext();\n const instruction = instructions[index];\n\n // console.log(`Debugging: ${index}, ${JSON.stringify(context)}, ${JSON.stringify(instruction)}`);\n switch (instruction.type) {\n case 'number':\n case 'array':\n case 'string':\n return {\n ...instruction,\n namedPath: instruction.namedVariable ? context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable] : undefined,\n }\n case 'repeat':\n pushRepeatToStack(instruction, index, context);\n break;\n default:\n // console.warn('Unclear instruction, abort');\n return;\n }\n }\n }\n\n function getIn(object, path) {\n for (let i = 0; i < path.length; ++i) {\n object = object[path[i]];\n }\n return object;\n }\n\n function setIn(object, path, value) {\n for (let i = 0; i < path.length - 1; ++i) {\n if (object[path[i]] == null) {\n object[path[i]] = {};\n }\n object = object[path[i]];\n }\n object[path[path.length - 1]] = value;\n }\n\n rl.on('line', line => {\n if (finished()) {\n return;\n }\n const { type, namedPath } = nextInstruction();\n switch (type) {\n case 'number':\n if (namedPath) {\n setIn(mappedVariables, namedPath, parseInt(line));\n }\n break;\n case 'string':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim());\n }\n break;\n case 'array':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim().split(' ').map(x => parseInt(x)));\n }\n break;\n default:\n // console.warn(`Value unread, received type ${type}.`);\n }\n\n if (checkFinished()) {\n resolvePromise(mappedVariables);\n rl.close();\n }\n });\n return {\n waitUntilDone,\n };\n}\n\nfunction solve(testCase) {\n let k = testCase.lengthAndPermit[1];\n\n let oneCount = 0;\n let firstOne = -1;\n let lastOne = -1;\n for (let i = 0; i < testCase.theInput.length; ++i) {\n if (testCase.theInput[i] === '1') {\n if (firstOne === -1) {\n firstOne = i;\n }\n lastOne = i;\n ++oneCount;\n }\n }\n\n if (oneCount === 0) {\n return 0;\n }\n\n if (oneCount === testCase.theInput.length) {\n return 11 * (oneCount - 1);\n }\n\n let preliminarySum = 11 * oneCount;\n const distanceToLast = testCase.theInput.length - 1 - lastOne;\n const distanceToFirst = firstOne;\n\n if (k - distanceToLast >= 0) {\n k -= distanceToLast;\n preliminarySum -= 10;\n }\n if (k - distanceToFirst >= 0 && oneCount > 1) {\n preliminarySum -= 1;\n }\n\n return preliminarySum;\n}\n\n(async function main() {\n const reader = createCLIReader([\n { type: 'number', namedVariable: 'numberOfTestCase' },\n { type: 'repeat', instructionCount: 2, count: 'numberOfTestCase', namedVariable: 'testCase' },\n { type: 'array', namedVariable: 'lengthAndPermit' },\n { type: 'string', namedVariable: 'theInput' }\n ]);\n const schema = await reader.waitUntilDone();\n\n for (let i = 0; i < schema.numberOfTestCase; ++i) {\n console.log(solve(schema.testCase[i]));\n }\n})();\n"}, {"source_code": "/**\n * Format:\n * {type: 'number', namedVariable?: string }\n * {type: 'repeat', instructionCount: number, count: number, namedVariable?: string }\n * {type: 'array', namedVariable?: string }\n * {type: 'string', namedVariable?: string }\n */\nconst readline = require('readline');\n\nfunction createCLIReader(instructions) {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const mappedVariables = {};\n\n let resolvePromise = null;\n const donePromise = new Promise((res, rej) => {\n resolvePromise = res;\n });\n\n function waitUntilDone() {\n return donePromise;\n }\n\n /**\n * {type: 'repeat', count: number, iteration: number, basePointer: number, pointer: number, instructionCount: number, context: array }\n */\n const stack = [];\n let pc = -1;\n\n function finished() {\n if (pc >= instructions.length) {\n return true;\n }\n return false;\n }\n\n function checkFinished() {\n // console.log(`Finish check ${pc}, ${JSON.stringify(stack)}, ${pc >= instructions.length}, ${stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1}`);\n if (pc >= instructions.length) {\n return true;\n }\n if (stack.length === 1 && stack[0].pointer === stack[0].instructionCount && stack[0].count === stack[0].iteration + 1) {\n return true;\n }\n return false;\n }\n\n function getNextInstructionContext() {\n if (!stack.length) {\n return {\n index: ++pc,\n }\n }\n const lastStack = stack[stack.length - 1];\n if (lastStack.pointer === lastStack.instructionCount) {\n lastStack.pointer = 0;\n lastStack.iteration = lastStack.iteration + 1;\n }\n if (lastStack.count === lastStack.iteration) {\n stack.pop();\n pc = lastStack.basePointer + lastStack.instructionCount + 1;\n return {\n index: pc,\n }\n }\n\n lastStack.pointer = lastStack.pointer + 1;\n return {\n index: lastStack.basePointer + lastStack.pointer,\n context: {\n namedPath: [...lastStack.context.namedPath, lastStack.iteration]\n }\n }\n }\n\n function pushRepeatToStack(instruction, index, context) {\n stack.push({\n type: 'repeat',\n count: typeof instruction.count === 'number' ? instruction.count : context && context.namedPath ? getIn(mappedVariables, [...context.namedPath, instruction.count]) : mappedVariables[instruction.count],\n iteration: 0,\n basePointer: index,\n pointer: 0,\n instructionCount: instruction.instructionCount,\n context: {\n namedPath: context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable],\n }\n })\n setIn(mappedVariables, context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable], []);\n }\n\n function nextInstruction() {\n if (finished()) {\n // console.warn('Calling nextInstruction after finished, something is wrong');\n return;\n }\n while (true) {\n const { index, context } = getNextInstructionContext();\n const instruction = instructions[index];\n\n // console.log(`Debugging: ${index}, ${JSON.stringify(context)}, ${JSON.stringify(instruction)}`);\n switch (instruction.type) {\n case 'number':\n case 'array':\n case 'string':\n return {\n ...instruction,\n namedPath: instruction.namedVariable ? context && context.namedPath ? [...context.namedPath, instruction.namedVariable] : [instruction.namedVariable] : undefined,\n }\n case 'repeat':\n pushRepeatToStack(instruction, index, context);\n break;\n default:\n // console.warn('Unclear instruction, abort');\n return;\n }\n }\n }\n\n function getIn(object, path) {\n for (let i = 0; i < path.length; ++i) {\n object = object[path[i]];\n }\n return object;\n }\n\n function setIn(object, path, value) {\n for (let i = 0; i < path.length - 1; ++i) {\n if (object[path[i]] == null) {\n object[path[i]] = {};\n }\n object = object[path[i]];\n }\n object[path[path.length - 1]] = value;\n }\n\n rl.on('line', line => {\n if (finished()) {\n return;\n }\n const { type, namedPath } = nextInstruction();\n switch (type) {\n case 'number':\n if (namedPath) {\n setIn(mappedVariables, namedPath, parseInt(line));\n }\n break;\n case 'string':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim());\n }\n break;\n case 'array':\n if (namedPath) {\n setIn(mappedVariables, namedPath, line.trim().split(' ').map(x => parseInt(x)));\n }\n break;\n default:\n // console.warn(`Value unread, received type ${type}.`);\n }\n\n if (checkFinished()) {\n resolvePromise(mappedVariables);\n rl.close();\n }\n });\n return {\n waitUntilDone,\n };\n}\n\nfunction solve(testCase) {\n let k = testCase.lengthAndPermit[1];\n\n let oneCount = 0;\n let firstOne = -1;\n let lastOne = -1;\n for (let i = 0; i < testCase.theInput.length; ++i) {\n if (testCase.theInput[i] === '1') {\n if (firstOne === -1) {\n firstOne = i;\n }\n lastOne = i;\n ++oneCount;\n }\n }\n\n if (oneCount === 0) {\n return 0;\n }\n\n if (oneCount === testCase.theInput.length) {\n return 11 * (oneCount - 1);\n }\n\n let preliminarySum = 11 * oneCount;\n const distanceToLast = testCase.theInput.length - 1 - lastOne;\n const distanceToFirst = firstOne;\n\n if (k - distanceToLast >= 0) {\n k -= distanceToLast;\n preliminarySum -= 10;\n }\n if (k - distanceToFirst >= 0) {\n preliminarySum -= 1;\n }\n\n return preliminarySum;\n}\n\n(async function main() {\n const reader = createCLIReader([\n { type: 'number', namedVariable: 'numberOfTestCase' },\n { type: 'repeat', instructionCount: 2, count: 'numberOfTestCase', namedVariable: 'testCase' },\n { type: 'array', namedVariable: 'lengthAndPermit' },\n { type: 'string', namedVariable: 'theInput' }\n ]);\n const schema = await reader.waitUntilDone();\n\n for (let i = 0; i < schema.numberOfTestCase; ++i) {\n console.log(solve(schema.testCase[i]));\n }\n})();\n"}, {"source_code": "class Scaner {\r\n data = [];\r\n constructor() {\r\n process.stdin.setEncoding('utf-8');\r\n process.stdin.on('data', _data => {\r\n let lasttext = this.data.pop();\r\n if (lasttext == undefined)\r\n lasttext = \"\"\r\n _data = lasttext + _data;\r\n const l = _data.split('\\n');\r\n this.data = this.data.concat(l.slice(0, -1).map(string => string.trim()), l[l.length - 1]);\r\n });\r\n }\r\n read = async () => {\r\n process.stdin.resume();\r\n while (this.data.length < 2) {\r\n await delay(0);\r\n }\r\n process.stdin.pause();\r\n let res = this.data.shift();\r\n if (res == \"\")\r\n return await read();\r\n return res;\r\n };\r\n}\r\nconst delay = (ms=0) => new Promise(resolve => setTimeout(resolve, ms));\r\nconst print = (text) => process.stdout.write(\"\" + text);\r\nconst scaner = new Scaner()\r\nconst read = scaner.read;\r\n//----------------------------------------------------------------\r\n//-----------------------the-code---------------------------------\r\n//----------------------------------------------------------------\r\n\r\n(async () => {\r\n let t = parseInt(await read());\r\n while (t--) {\r\n let [n,k]=(await read()).split(' ').map(Number);\r\n let a=await read();\r\n let ans=0;\r\n let i,j;\r\n for (i = a.length-1; i >= 0; i--){\r\n const e = a[i];\r\n if(e=='1'){\r\n const cost=a.length-i-1;\r\n if(cost<=k){\r\n k-=cost;\r\n ans+=1;\r\n }else{\r\n ans+=11;\r\n }\r\n break;\r\n }\r\n }\r\n for (j = 0; j < i; j++){\r\n const e = a[j];\r\n if(e=='1'){\r\n const cost=j;\r\n if(cost<=k){\r\n k-=cost;\r\n ans+=10;\r\n }else{\r\n ans+=11;\r\n }\r\n break;\r\n \r\n }\r\n }\r\n for (j++; j < i; j++){\r\n if(a[j]=='1'){\r\n ans+=11;\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n})().then(() => { }\r\n)\r\n\r\n\r\n\r\n"}], "src_uid": "ccecf97fcddbd0ab030d34b79a42cc6e"} {"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 — 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$$$) — 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": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var numbers = read.arrNumber(' ');\n\n numbers.sort((a, b) => a - b);\n\n var a = numbers[3] - numbers[2];\n var b = numbers[1] - a;\n var c = numbers[0] - a;\n print(a + ' ' + b + ' ' + c);\n}());\n"}, {"source_code": "var n = readline().split(' ').map(Number);\nn.sort((a,b) => a-b);\n\nvar a = n[3]-n[0];\nvar b = n[3]-n[1];\nvar c = n[3]-n[2];\n\nprint(a,b,c);"}, {"source_code": "var numbers = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar x1 = numbers[0];\nvar x2 = numbers[1];\nvar x3 = numbers[2];\nvar x4 = numbers[3];\n var maxX = 0;\n var massiveXes = [];\n var a;\n var b;\n var c;\n massiveXes.push(x2, x1, x3, x4);\n \n for (i = 0; i< massiveXes.length; i++){\n\tif (maxX < massiveXes[i]){\n\t\tmaxX = massiveXes[i];\n\t}\n\t \n }\n\n for (k=0; k parseInt(z))\nvar total = ns.reduce((p, c) => p > c ? p : c)\nns.splice(ns.indexOf(total), 1)\nvar get = (x, y, z) => {\n var c = Math.abs((((x - y) + (x - z)) - x) / 2)\n return [c, x - z + c, x - y + c]\n}\nvar o = [\n [0, 1, 2],\n [0, 2, 1],\n [1, 0, 2],\n [1, 2, 0],\n [2, 0, 1],\n [2, 1, 0]\n].map(z => z.map(y => ns[y]))\n .map(z => get.apply([], z))\n .filter(z => z.reduce((p, c) => p + c) == total)[0]\n .sort((a, b) => a - b)\n .join(\" \")\nprint(o)"}, {"source_code": "var n = readline().split(' ').map(Number);\n// var n = prompt().split(' ').map(Number);\nn.sort((a,b) => a-b);\nvar a = n[3]-n[0];\nvar b = n[3]-n[1];\nvar c = n[3]-n[2];\n// console.log(a, b, c);\nprint(a, b, c);"}, {"source_code": "var n = readline().split(' ').map(Number);\nn.sort((a,b) => a-b);\nvar a = n[3]-n[0];\nvar b = n[3]-n[1];\nvar c = n[3]-n[2];\nprint(a, b, c);"}, {"source_code": "var s = readline().split(\" \").map(function(e){return parseInt(e);});\nvar x = Math.max(...s);var b = s.indexOf(x);\n\n\n\nvar show = \"\";for(var i=0;iINPUT.pop();\nwrite=(...s)=>{OUTPUT+=[...s].join(' ')};\nprint=(...s)=>{write(...s);OUTPUT+='\\n'};}\nconst\nrdS=readline,\nrdN=()=>+rdS(),\nrdArS=()=>rdS().split(' '),\nrdArN=()=>rdArS().map(v=>+v),\nwr=write,\npr=print,\nprAr=(a)=>pr(...a),\nprOb=(o)=>pr(JSON.stringify(o,null,4)),\ncrAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},\ngetPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},\ndefineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});\ndefineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});\ndefineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});\n \nmain();\nreturn OUTPUT;\n})();"}, {"source_code": "//var input = readline()\n\nvar ar = readline().split(' ').map(x => parseInt(x)) \nar.sort((a, b) => a - b)\nvar k = [ar[3]-ar[2], ar[3]-ar[1], ar[3]-ar[0]]\nprint(k.join(' '))\n\n//"}, {"source_code": "'use strict';\n\nconst fs = require('fs');\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++].split(' ');\n}\n\nfunction readInt(s) {\n return parseInt(s, 10);\n}\n\nfunction readIntArray(a) {\n return a.map(e => parseInt(e, 10));\n}\n\nfunction solve(n) {\n n.sort((a, b) => a - b);\n return [n[3] - n[0], n[3] - n[2], n[3] - n[1]];\n}\n\nfunction main() {\n\n const n = readIntArray(readLine());\n\n let result = solve(n);\n console.log(result.join(' '));\n}\n"}, {"source_code": "const readline = require('readline')\n\nasync function algo() {\n let [x, y, z, k] = await ints()\n let i = 0\n if (k < x) [k, x] = [x, k]\n if (k < y) [k, y] = [y, k]\n if (k < z) [k, z] = [z, k]\n const a = k - x\n console.log([a, y-a, z-a].join(' '))\n}\n\n\n// read the input\nconst _lines = []\nlet _lineIndex = 0\nlet _ended = false\nconst _rl = readline.createInterface(process.stdin)\n_rl.on('line', line => _lines.push(line))\n_rl.on('end', () => (ended = true))\nconst wait = ms => new Promise(resolve => setTimeout(resolve, ms))\nconst line = async () => {\n while (!_ended && _lines.length <= _lineIndex) await wait(10)\n const result = _lines[_lineIndex].trim()\n _lines[_lineIndex] = null\n _lineIndex++\n return result\n}\nconst words = async () => (await line()).split(' ')\nconst chars = async () => (await line()).split('')\nconst int = async () => parseInt(await line())\nconst ints = async () => (await words()).map(x => parseInt(x))\nconst big = async () => BigInt(await line())\nconst bigs = async () => (await words()).map(x => BigInt(x))\n\nalgo()"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nrl.on('line', (line) => {\n let numbers = [];\n let addedNumbers = line.split(' ').map(Number);\n let abc = Math.max(...addedNumbers);\n addedNumbers.splice(addedNumbers.indexOf(abc), 1);\n addedNumbers.forEach((number) => {\n numbers.push(abc - number);\n });\n\n console.log(...numbers);\n});"}, {"source_code": "let readline = require('readline');\nlet intInput = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\nlet nums;\n\nintInput.on('line', (line) => {\n\tnums = line.split(\" \");\n});\n\nintInput.on('close', () => {\n\tlet max = Number(nums[0]);\n\tlet maxI = 0;\n\tfor (let i = 1; i < nums.length; i++) {\n\t\tif ( nums[i] > max) {\n\t\t\tmax = Number(nums[i]);\n\t\t\tmaxI = i\n\t\t}\n\t}\n\tnums.splice(maxI, 1);\n\tlet result = \"\";\n\tfor (let j = 0; j < nums.length; j++) {\n\t\tlet a = max - Number(nums[j]);\n\t\tj == nums.length -1 ? result += `${a}` : result += `${a}` + \" \";\n\t}\n\tconsole.log(result);\n})"}, {"source_code": "function main() {\n // write code here:\n var arr=(stdin[0].split(' ')).map(a => Number(a)).sort((a,b) => a-b);\n var a=arr[3]-arr[2],b=arr[3]-arr[1],c=arr[3]-arr[0];\n console.log(a,b,c);\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({input: process.stdin});\nvar stdin = [];\nrl.on('line', function (line) {\n stdin.push(line);\n});\nrl.on('close', main);\n"}, {"source_code": "const readline = require(\"readline\");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.question('', function (results) {\n const res = results.split(' ').map(num => parseInt(num));\n calNums(res);\n rl.close();\n});\n\nrl.on(\"close\", function () {\n process.exit(0);\n});\n\nfunction calNums(res) {\n let a = 0, b = 0, c = 0;\n res.sort(function (a, b) { return a - b });\n b = (res[0] - res[1] + res[2]) / 2;\n a = res[0] - b ; \n c = res[2] - b ; \n\n console.log(`${a} ${b} ${c}`);\n}\n\n\n\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var one = nextIntArray();\n one.sort(function(a, b){\n \treturn a - b;\n });\n var L = one[3] - one[2];\n var C = one[3] - one[1];\n var R = one[3] - one[0];\n myout(L + \" \" + C + \" \" + R);\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (d) => {\n const ans = [];\n const arr = d.split(' ').map(Number);\n arr.sort((a, b) => a - b);\n\n for (let i = 0; i < arr.length - 1; i++) {\n ans.push(arr[arr.length - 1] - arr[i]);\n }\n\n console.log(ans.join(' '));\n});\n"}, {"source_code": "let input = [];\n \nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n\nRL.on('line', (line) => {\n input.push(line);\n});\n\nRL.on('close', () => {\n let {0:x1, 1:x2, 2:x3, 3:x4} = {...input[0].split(' ')};\n x1 = parseInt(x1); x2 = parseInt(x2);\n x3 = parseInt(x3); x4 = parseInt(x4);\n let max = (x1 > x2 && x1 > x3 && x1 > x4) ? x1 : \n (x2 > x1 && x2 > x3 && x2 > x4) ? x2 : \n (x3 > x1 && x3 > x2 && x3 > x4) ? x3 : x4;\n \n input[0].split(' ').forEach( i => {\n if(parseInt(i) != parseInt(max))\n console.log(max - i);\n });\n});\n\n"}, {"source_code": "const readLine = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadLine.on('line', line => input.push(line));\n\nreadLine.on('close', () => {\n let [x1, x2, x3, x4] = input[0].split(' ').map(x => parseInt(x));\n\n let max = Math.max(x1, x2, x3, x4);\n const nums = [];\n\n input[0].split(' ').map(x => parseInt(x)).forEach( x => {\n if (x !== max) {\n nums.push(max - x);\n }\n });\n\n console.log(nums.join(' '));\n}); \n "}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function() {\n inputString = inputString.split('\\n');\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n\n// main function .... code start ... ///\nfunction main() {\n\n //var input = readline()\n var ar = readline().split(' ').map(x => parseInt(x)) \n ar.sort((a, b) => a - b)\n var k = [ar[3]-ar[2], ar[3]-ar[1], ar[3]-ar[0]]\n console.log(k.join(' ')) \n}\n\n"}, {"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nfunction print(x) {\n console.log(x);\n}\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on(\"end\", () => {\n inputString = inputString.split(\"\\n\");\n main();\n});\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// ************************ Code Start ***************************\n\nfunction main() {\n //var input = readline();\n var ar = readline().split(\" \").map(x => parseInt(x));\n ar.sort((a, b) => a - b);\n var k = [ar[3] - ar[2], ar[3] - ar[1], ar[3] - ar[0]];\n print(k.join(\" \"));\n}\n"}, {"source_code": "//******************************************************************************** //\n'use strict'; process.stdin.resume(); //\nprocess.stdin.setEncoding('utf-8'); //\nlet inputString = ''; let currentLine = 0; //\nprocess.stdin.on('data', inputStdin => { inputString += inputStdin }); //\nprocess.stdin.on('end', () => { inputString = inputString.split('\\n'); main(); }); //\nfunction readline() { return inputString[currentLine++]; } //\n//******************************************************************************** //\n\nfunction main() {\n\n //var input = readline()\n var ar = readline().split(' ').map(x => parseInt(x)) \n ar.sort((a, b) => a - b)\n var k = [ar[3]-ar[2], ar[3]-ar[1], ar[3]-ar[0]]\n console.log(k.join(' ')) \n \n}\n\n"}, {"source_code": "'use strict'; process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = ''; let currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on('end', () => {\n inputString = inputString.split('\\n');\n main();\n});\nfunction readline() {\n return inputString[currentLine++];\n}\n// ******************************************************\n// ******************** Code Start **********************\n\nfunction main() {\n \n //var input = readline();\n var ar = readline().split(' ').map(x => parseInt(x)) ;\n ar.sort((a, b) => a - b);\n var k = [ar[3]-ar[2], ar[3]-ar[1], ar[3]-ar[0]];\n console.log(k.join(' '));\n \n}"}, {"source_code": "//******************************************************************************** //\n'use strict'; process.stdin.resume(); //\nprocess.stdin.setEncoding('utf-8'); //\nlet inputString = ''; let currentLine = 0; //\nprocess.stdin.on('data', inputStdin => { inputString += inputStdin }); //\nprocess.stdin.on('end', () => { inputString = inputString.split('\\n'); main(); }); //\nfunction readline() { return inputString[currentLine++]; } //\n //\n//******************************************************************************** //\n\nfunction main() {\n\n //var input = readline()\n var ar = readline().split(' ').map(x => parseInt(x)) \n ar.sort((a, b) => a - b)\n var k = [ar[3]-ar[2], ar[3]-ar[1], ar[3]-ar[0]]\n console.log(k.join(' ')) \n \n}\n"}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n let num = arr[0].split(' ');\n //num.pop();\n let a = parseInt(num[0]);\n let b = parseInt(num[1]);\n let c = parseInt(num[2]);\n let d = parseInt(num[3]);\n let max = 0;\n if(a>b && a>c && a>d) max = a;\n else if(b>a && b>c && b>d) max =b;\n else if(c>a && c>b && c>d) max =c;\n else max =d;\n \n let str,str1,str2,str3;\n (max !==a)?str = max-a:str='';\n (max !==b)?str1 =max-b:str1='';\n (max !==c)?str2 =max-c:str2='';\n (max !==d)?str3 =max-d:str3='';\n console.log(str+\" \"+str1+\" \"+str2+\" \"+str3);\n }); "}, {"source_code": "// Sample code to perform I/O:\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n main(stdin_input);\n});\n\nfunction main(input) {\n let output = nameLookUp(input);\n process.stdout.write(output); // Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\n// Write your code here\nfunction nameLookUp(str) {\n\n let inputs = str.trim().split(' ').map(num => Number(num));\n let max = Math.max(...inputs);\n let newNum = [];\n for (const iterator of inputs) {\n if (iterator !== max) {\n newNum.push(max - iterator);\n }\n }\n return newNum.join(' ').toString();\n}\n\n\n\n\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let arr = readLine().split(' ').map(v => parseInt(v)).sort((a, b) => {\n return a - b;\n });\n let x1 = arr[0];\n let x2 = arr[1];\n let x3 = arr[2];\n let x4 = arr[3];\n console.log(x3 - (x4 - x1), x2 - (x4 - x1), x4 - x1)\n}"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nasync function algo() {\n const [x, y, z, k] = await ints()\n let i = 0\n if (k < x) [k, x] = [x, k]\n if (k < y) [k, y] = [y, k]\n if (k < z) [k, z] = [z, k]\n const a = k - x\n console.log([a, y-a, z-a].join(' '))\n}\n\n\n// read the input\nconst _lines = []\nlet _lineIndex = 0\nlet _ended = false\nconst _rl = readline.createInterface(process.stdin)\n_rl.on('line', line => _lines.push(line))\n_rl.on('end', () => (ended = true))\nconst wait = ms => new Promise(resolve => setTimeout(resolve, ms))\nconst line = async () => {\n while (!_ended && _lines.length <= _lineIndex) await wait(10)\n const result = _lines[_lineIndex].trim()\n _lines[_lineIndex] = null\n _lineIndex++\n return result\n}\nconst words = async () => (await line()).split(' ')\nconst chars = async () => (await line()).split('')\nconst int = async () => parseInt(await line())\nconst ints = async () => (await words()).map(x => parseInt(x))\nconst big = async () => BigInt(await line())\nconst bigs = async () => (await words()).map(x => BigInt(x))\n\nalgo()"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nrl.on('line', (line) => {\n let numbers = [];\n let addedNumbers = line.split(' ').map(Number);\n let abc = Math.max(...addedNumbers);\n addedNumbers.splice(addedNumbers.indexOf(abc), 1);\n addedNumbers.forEach((number) => {\n numbers.push(abc - number);\n });\n\n return {...numbers};\n});"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nrl.on('line', (line) => {\n let numbers = [];\n let addedNumbers = line.split(' ').map(Number);\n let abc = Math.max(...addedNumbers);\n addedNumbers.splice(addedNumbers.indexOf(abc), 1);\n addedNumbers.forEach((number) => {\n numbers.push(abc - number);\n });\n\n return numbers.join(' ');\n});"}, {"source_code": "let readline = require('readline');\nlet intInput = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout\n});\nlet nums;\n\nintInput.on('line', (line) => {\n\tnums = line.split(\" \");\n});\n\nintInput.on('close', () => {\n\tlet max = nums[0];\n\tlet maxI = 0;\n\tfor (let i = 1; i < nums.length; i++) {\n\t\tif ( nums[i] > max) {\n\t\t\tmax = Number(nums[i]);\n\t\t\tmaxI = i\n\t\t}\n\t}\n\tnums.splice(maxI, 1);\n\tlet result = \"\";\n\tfor (let j = 0; j < nums.length; j++) {\n\t\tlet a = max - Number(nums[j]);\n\t\tj == nums.length -1 ? result += `${a}` : result += `${a}` + \" \";\n\t}\n\tconsole.log(result);\n})"}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n let d = parseInt(num[3]);\n console.log(\"for d:\"+d);\n }); "}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n //num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n let d = parseInt(num[3]);\n console.log(\"for d:\"+d);\n }); "}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n }); "}, {"source_code": "var arr = '';\nprocess.stdin.on('data',function(chunk){\n arr += chunk; \n});\nprocess.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n});\n"}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n //num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n let d = parseInt(num[3]);\n console.log(\"for d:\"+d);\n let max = 0;\n if(a>b && a>c && a>d) max = a;\n else if(b>a && b>c && b>d) max =b;\n else if(c>a && c>b && c>d) max =c;\n else max =d;\n console.log((max-a)+\" \"+(max-b)+\" \"+(max-c)+\" \"+(max-d));\n }); "}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n //num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n let d = parseInt(num[3]);\n console.log(\"for d:\"+d);\n let max = 0;\n if(a>b && a>c && a>d) max = a;\n else if(b>a && b>c && b>d) max =b;\n else if(c>a && c>b && c>d) max =c;\n else max =d;\n \n let str = '';\n if(max !==a) str = str + (max-a);\n if(max !==b) str = str + (max-b);\n if(max !==c) str = str + (max-c);\n if(max !==d) str = str + (max-d);\n console.log(\"for str:\"+str);\n str = str.split('');\n console.log(str.join(' '));\n //console.log((max-a)+\" \"+(max-b)+\" \"+(max-c)+\" \"+(max-d));\n }); "}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n let num = arr[0].split(' ');\n //num.pop();\n let a = parseInt(num[0]);\n let b = parseInt(num[1]);\n let c = parseInt(num[2]);\n let d = parseInt(num[3]);\n let max = 0;\n if(a>b && a>c && a>d) max = a;\n else if(b>a && b>c && b>d) max =b;\n else if(c>a && c>b && c>d) max =c;\n else max =d;\n \n let str = '';\n if(max !==a) str = str + (max-a);\n if(max !==b) str = str + (max-b);\n if(max !==c) str = str + (max-c);\n if(max !==d) str = str + (max-d);\n str = str.split('');\n console.log(str.join(' '));\n }); "}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n num = num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n });"}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n }); "}, {"source_code": "var arr = '';\nprocess.stdin.on('data',function(chunk){\n arr += chunk; \n});\nprocess.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let a = parseInt(arr[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(arr[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(arr[2]);\n console.log(\"for c:\"+c);\n});\n"}, {"source_code": "var arr = '';\nprocess.stdin.on('data',function(chunk){\n arr += chunk; \n});\nprocess.stdin.on('end',function(){\n arr = arr.split('\\n');\n console.log(\"for arr\");\n console.log(arr);\n});\n"}, {"source_code": " var arr = '';\n process.stdin.on('data',function(chunk){\n arr += chunk; \n });\n process.stdin.on('end',function(){\n arr = arr.split('\\n');\n arr.pop();\n console.log(\"for arr\");\n console.log(arr);\n let num = arr[0].split(' ');\n num.pop();\n console.log(\"for num\");\n console.log(num);\n let a = parseInt(num[0]);\n console.log(\"for a:\"+a);\n let b = parseInt(num[1]);\n console.log(\"for b:\"+b);\n let c = parseInt(num[2]);\n console.log(\"for c:\"+c);\n });"}, {"source_code": "var arr = '';\nprocess.stdin.on('data',function(chunk){\n arr += chunk; \n});\nconsole.log(\"for arr\");\nconsole.log(arr);"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let arr = readLine().split(' ').map(v => parseInt(v)).sort();\n let x1 = arr[0];\n let x2 = arr[1];\n let x3 = arr[2];\n let x4 = arr[3];\n console.log(x3 - (x4 - x1), x2 - (x4 - x1), x4 - x1)\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let arr = readLine().split(' ').map(v => parseInt(v)).sort((a, b) => {\n return a - b;\n });\n console.log(arr);\n let x1 = arr[0];\n let x2 = arr[1];\n let x3 = arr[2];\n let x4 = arr[3];\n console.log(x3 - (x4 - x1), x2 - (x4 - x1), x4 - x1)\n}"}], "src_uid": "cda949a8fb1f158f3c06109a2d33f084"} {"nl": {"description": "You are given a binary array $$$a$$$ (all elements of the array are $$$0$$$ or $$$1$$$) of length $$$n$$$. You wish to sort this array, but unfortunately, your algorithms teacher forgot to teach you sorting algorithms. You perform the following operations until $$$a$$$ is sorted: Choose two random indices $$$i$$$ and $$$j$$$ such that $$$i < j$$$. Indices are chosen equally probable among all pairs of indices $$$(i, j)$$$ such that $$$1 \\le i < j \\le n$$$. If $$$a_i > a_j$$$, then swap elements $$$a_i$$$ and $$$a_j$$$. What is the expected number of such operations you will perform before the array becomes sorted?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{998\\,244\\,353}$$$. Output the integer equal to $$$p \\cdot q^{-1} \\bmod 998\\,244\\,353$$$. In other words, output such an integer $$$x$$$ that $$$0 \\le x < 998\\,244\\,353$$$ and $$$x \\cdot q \\equiv p \\pmod{998\\,244\\,353}$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^5$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 200\\,000$$$) — the number of elements in the binary array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$a_i \\in \\{0, 1\\}$$$) — elements of the array. It's guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$200\\,000$$$.", "output_spec": "For each test case print one integer — the value $$$p \\cdot q^{-1} \\bmod 998\\,244\\,353$$$.", "sample_inputs": ["3\n\n3\n\n0 1 0\n\n5\n\n0 0 1 1 1\n\n6\n\n1 1 1 0 0 1"], "sample_outputs": ["3\n0\n249561107"], "notes": "NoteConsider the first test case. If the pair of indices $$$(2, 3)$$$ will be chosen, these elements will be swapped and array will become sorted. Otherwise, if one of pairs $$$(1, 2)$$$ or $$$(1, 3)$$$ will be selected, nothing will happen. So, the probability that the array will become sorted after one operation is $$$\\frac{1}{3}$$$, the probability that the array will become sorted after two operations is $$$\\frac{2}{3} \\cdot \\frac{1}{3}$$$, the probability that the array will become sorted after three operations is $$$\\frac{2}{3} \\cdot \\frac{2}{3} \\cdot \\frac{1}{3}$$$ and so on. The expected number of operations is $$$\\sum \\limits_{i=1}^{\\infty} \\left(\\frac{2}{3} \\right)^{i - 1} \\cdot \\frac{1}{3} \\cdot i = 3$$$.In the second test case the array is already sorted so the expected number of operations is zero.In the third test case the expected number of operations equals to $$$\\frac{75}{4}$$$ so the answer is $$$75 \\cdot 4^{-1} \\equiv 249\\,561\\,107 \\pmod {998\\,244\\,353}$$$."}, "positive_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n let zero = 0\n for (let i = 0; i < n; i++) {\n if (!arr[i]) zero++\n }\n let one = 0\n for (let i = 0; i < zero; i++) {\n if (arr[i]) one++\n }\n// console.log(one)\n let r = 0\n const c2 = mul(n, n - 1)\n for (let i = 1; i <= one; i++) {\n // i * i * 2 / (n * (n - 1))\n const i2 = mul(i, i * 2)\n const temp = mul(c2, pow(i2, MOD - 2))\n r = add(r, temp)\n }\n return r\n}\nconst MOD = 998244353\nconst MOD_CUT = ((1 << 20) * (1 << 20)) % MOD\nfunction add(a, b) {\n return (a + b) % MOD\n}\nfunction minus(a, b) {\n return add(add(a, -b), MOD)\n}\nfunction mul(a, b) {\n let r = (a >> 20) * (b >> 20) * MOD_CUT\n + (a & 0xfff00000) * (b & 0xfffff)\n + (a & 0xfffff) * b\n return r % MOD\n}\nfunction pow(a, b) {\n let r = 1\n let base = a\n while (b) {\n if (b & 1) {\n r = mul(r, base)\n }\n b >>= 1\n base = mul(base, base)\n }\n return r\n}\n"}], "negative_code": [], "src_uid": "2b391638a9fea31986fe8e41c97b640a"} {"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 < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.", "input_spec": "The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103). ", "output_spec": "Print a single number — 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 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted."}, "positive_code": [{"source_code": "(()=>{\"use strict\";var t={312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});const u=n(r(747));let o=\"\",i=[],s=0,l=\"\";const a=\"local\"===process.argv[2],f=t=>{if(a)return i=u.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),void u.default.writeFileSync(\"output.txt\",l);process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{o+=t})),process.stdin.on(\"end\",(e=>{i=o.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return i[s++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt-1));u.default.put(e)}))},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var u=e[n]={exports:{}};return t[n].call(u.exports,u,u.exports,r),u.exports}(965)})();"}], "negative_code": [], "src_uid": "d526af933b5afe9abfdf9815e9664144"} {"nl": {"description": "Alice's potion making professor gave the following assignment to his students: brew a potion using $$$n$$$ ingredients, such that the proportion of ingredient $$$i$$$ in the final potion is $$$r_i > 0$$$ (and $$$r_1 + r_2 + \\cdots + r_n = 1$$$).He forgot the recipe, and now all he remembers is a set of $$$n-1$$$ facts of the form, \"ingredients $$$i$$$ and $$$j$$$ should have a ratio of $$$x$$$ to $$$y$$$\" (i.e., if $$$a_i$$$ and $$$a_j$$$ are the amounts of ingredient $$$i$$$ and $$$j$$$ in the potion respectively, then it must hold $$$a_i/a_j = x/y$$$), where $$$x$$$ and $$$y$$$ are positive integers. However, it is guaranteed that the set of facts he remembers is sufficient to uniquely determine the original values $$$r_i$$$.He decided that he will allow the students to pass the class as long as they submit a potion which satisfies all of the $$$n-1$$$ requirements (there may be many such satisfactory potions), and contains a positive integer amount of each ingredient.Find the minimum total amount of ingredients needed to make a potion which passes the class. As the result can be very large, you should print the answer modulo $$$998\\,244\\,353$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — 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$$$). Each of the next $$$n-1$$$ lines contains four integers $$$i, j, x, y$$$ ($$$1 \\le i, j \\le n$$$, $$$i\\not=j$$$, $$$1\\le x, y \\le n$$$) — ingredients $$$i$$$ and $$$j$$$ should have a ratio of $$$x$$$ to $$$y$$$. It is guaranteed that the set of facts is sufficient to uniquely determine the original values $$$r_i$$$. It is also guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the minimum total amount of ingredients needed to make a potion which passes the class, modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["3\n4\n3 2 3 4\n1 2 4 3\n1 4 2 4\n8\n5 4 2 3\n6 4 5 4\n1 3 5 2\n6 8 2 1\n3 5 3 4\n3 2 2 5\n6 7 4 3\n17\n8 7 4 16\n9 17 4 5\n5 14 13 12\n11 1 17 14\n6 13 8 9\n2 11 3 11\n4 17 7 2\n17 16 8 6\n15 5 1 14\n16 7 1 10\n12 17 13 10\n11 16 7 2\n10 11 6 4\n13 17 14 6\n3 11 15 8\n15 6 12 8"], "sample_outputs": ["69\n359\n573672453"], "notes": "NoteIn the first test case, the minimum total amount of ingredients is $$$69$$$. In fact, the amounts of ingredients $$$1, 2, 3, 4$$$ of a valid potion are $$$16, 12, 9, 32$$$, respectively. The potion is valid because Ingredients $$$3$$$ and $$$2$$$ have a ratio of $$$9 : 12 = 3 : 4$$$; Ingredients $$$1$$$ and $$$2$$$ have a ratio of $$$16 : 12 = 4 : 3$$$; Ingredients $$$1$$$ and $$$4$$$ have a ratio of $$$16 : 32 = 2 : 4$$$. In the second test case, the amounts of ingredients $$$1, 2, 3, 4, 5, 6, 7, 8$$$ in the potion that minimizes the total amount of ingredients are $$$60, 60, 24, 48, 32, 60, 45, 30$$$."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nasync function solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n g[i].push(j);\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n async function helper(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = async u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n await helper(y, -1);\r\n await helper(x, 1);\r\n await dfs(v);\r\n await helper(y, 1);\r\n await helper(x, -1);\r\n }\r\n };\r\n await dfs(0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(await solve(n, b));\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n g[i].push(j);\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function f(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const helper = fn => {\r\n const done = () => {};\r\n const dfs = (...args) => {\r\n const callStack = [[done, args]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {\r\n var _curCall;\r\n const after = curCall.pop();\r\n after();\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall && curCall.length > 1) curCall.pop();\r\n }\r\n if (!curCall) break;\r\n const args = curCall[curCall.length - 1];\r\n const [before, inside, after] = fn(...args);\r\n before();\r\n let nextCall = inside(...args);\r\n callStack.push([after, ...nextCall]);\r\n }\r\n };\r\n return dfs;\r\n };\r\n const dfs = helper((u, x, y) => {\r\n const before = () => {\r\n st[u] = 1;\r\n f(y, -1);\r\n f(x, 1);\r\n };\r\n const inside = () => {\r\n let res = [];\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n res.push([v, x, y]);\r\n }\r\n return res;\r\n };\r\n const after = () => {\r\n f(y, 1);\r\n f(x, -1);\r\n };\r\n return [before, inside, after];\r\n });\r\n dfs(0, 0, 0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n g[i].push(j);\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function f(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const helper = fn => {\r\n const done = () => {};\r\n const dfs = (...args) => {\r\n const callStack = [[[done, []], args]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {\r\n var _curCall;\r\n const [after, args] = curCall.pop();\r\n after();\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall && curCall.length > 1) curCall.pop();\r\n }\r\n if (!curCall) break;\r\n const args = curCall[curCall.length - 1];\r\n const [before, inside, after] = fn(...args);\r\n before();\r\n let nextCall = inside(...args);\r\n callStack.push([[after, args], ...nextCall]);\r\n }\r\n };\r\n return dfs;\r\n };\r\n const dfs = helper((u, x, y) => {\r\n const before = () => {\r\n st[u] = 1;\r\n f(y, -1);\r\n f(x, 1);\r\n };\r\n const inside = () => {\r\n let res = [];\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n res.push([v, x, y]);\r\n }\r\n return res;\r\n };\r\n const after = () => {\r\n f(y, 1);\r\n f(x, -1);\r\n };\r\n return [before, inside, after];\r\n });\r\n dfs(0, 0, 0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n g[i].push(j);\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function f(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const helper = fn => {\r\n const done = () => {};\r\n const dfs = (...args) => {\r\n const callStack = [[[done, []], args]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {\r\n var _curCall;\r\n const [after, args] = curCall.pop();\r\n after(...args);\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall && curCall.length > 1) curCall.pop();\r\n }\r\n if (!curCall) break;\r\n const args = curCall[curCall.length - 1];\r\n const [before, inside, after] = fn(...args);\r\n before(...args);\r\n let nextCall = inside(...args);\r\n callStack.push([[after, args], ...nextCall]);\r\n }\r\n };\r\n return dfs;\r\n };\r\n const dfs = helper((u, x, y) => {\r\n const before = () => {\r\n st[u] = 1;\r\n f(y, -1);\r\n f(x, 1);\r\n };\r\n const inside = () => {\r\n let res = [];\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n res.push([v, x, y]);\r\n }\r\n return res;\r\n };\r\n const after = () => {\r\n f(y, 1);\r\n f(x, -1);\r\n };\r\n return [before, inside, after];\r\n });\r\n dfs(0, 0, 0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n g[i].push(j);\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function f(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const helper = fn => {\r\n const done = () => {};\r\n const dfs = (...args) => {\r\n const callStack = [[[done, []], args]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {\r\n var _curCall;\r\n const [after, args] = curCall.pop();\r\n after(...args);\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall && curCall.length > 1) curCall.pop();\r\n }\r\n if (!curCall) break;\r\n const args = curCall[curCall.length - 1];\r\n const [before, inside, after] = fn(...args);\r\n before(...args);\r\n let nextCall = inside(...args);\r\n callStack.push([[after, args], ...nextCall]);\r\n }\r\n };\r\n return dfs;\r\n };\r\n const dfs = helper((u, x, y) => {\r\n const before = (u, x, y) => {\r\n st[u] = 1;\r\n f(y, -1);\r\n f(x, 1);\r\n };\r\n const inside = () => {\r\n let res = [];\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n res.push([v, x, y]);\r\n }\r\n return res;\r\n };\r\n const after = (u, x, y) => {\r\n f(y, 1);\r\n f(x, -1);\r\n };\r\n return [before, inside, after];\r\n });\r\n dfs(0, 0, 0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n g[i].push(j);\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function helper(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n const callStack = [[[u, 0, 0]]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {\r\n var _curCall;\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (!curCall) continue;\r\n const [v, x, y] = curCall.pop();\r\n helper(y, 1);\r\n helper(x, -1);\r\n }\r\n if (!curCall) break;\r\n const [u, x, y] = curCall[curCall.length - 1];\r\n helper(y, -1);\r\n helper(x, 1);\r\n st[u] = 1;\r\n let nextCall = [];\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n nextCall.push([v, x, y]);\r\n }\r\n callStack.push(nextCall);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n g[i].push(j);\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function helper(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n helper(y, -1);\r\n helper(x, 1);\r\n dfs(v);\r\n helper(y, 1);\r\n helper(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n let xs = new Set();\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n xs.add(x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function helper(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n helper(y, -1);\r\n helper(x, 1);\r\n dfs(v);\r\n helper(y, 1);\r\n helper(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n try {\r\n res.push(solve(n, b));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n }\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n let xs = new Set();\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n xs.add(x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function helper(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n helper(y, -1);\r\n helper(x, 1);\r\n dfs(v);\r\n helper(y, 1);\r\n helper(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 2; i <= n; i++) {\r\n if (max[i]) num = mul(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n console.log((ori.reduce((a, b) => a + b, 0) % MOD).toString());\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n new Date().valueOf();\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n let xs = new Set();\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n xs.add(x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction power(a, b) {\r\n let res = 1;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n new Date().valueOf();\r\n const primes = getPrimes(n);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n let xs = new Set();\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n xs.add(x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = new Map();\r\nfunction power(a, b) {\r\n var _cache$get;\r\n let res = (_cache$get = cache.get(a)) === null || _cache$get === void 0 ? void 0 : _cache$get.get(b);\r\n if (res) return res;\r\n res = 1;\r\n let a1 = a,\r\n b1 = b;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n if (cache.has(a1)) {\r\n cache.get(a1).set(b1, res);\r\n } else {\r\n cache.set(a1, new Map([[b1, res]]));\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n const N = 16;\r\n return ((a >> N) * b % MOD * (1 << N) + (a & (1 << N) - 1) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n let xs = new Set();\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n xs.add(x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, power(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, power(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = new Map();\r\nfunction power(a, b) {\r\n var _cache$get;\r\n let res = (_cache$get = cache.get(a)) === null || _cache$get === void 0 ? void 0 : _cache$get.get(b);\r\n if (res) return res;\r\n res = 1;\r\n let a1 = a,\r\n b1 = b;\r\n while (b) {\r\n if (b & 1) res = mul(res, a);\r\n a = mul(a, a);\r\n b = b >> 1;\r\n }\r\n if (cache.has(a1)) {\r\n cache.get(a1).set(b1, res);\r\n } else {\r\n cache.set(a1, new Map([[b1, res]]));\r\n }\r\n return res;\r\n}\r\nfunction mul(a, b) {\r\n return ((a >> 16) * b % MOD * 65536 + (a & 65535) * b) % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n max = Math.max(max, n);\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nlet flag = false;\r\nfunction solve(n, a, max) {\r\n if (n === 200000 && a[0][0] === 51097) flag = true;\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug1', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let res = 0;\r\n let st = [];\r\n const dfs = u => {\r\n res = (res + st[u]) % MOD;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n if (n === 200000 && a[0][0] === 51097) {\r\n st[v] = mod(st[u], y);\r\n } else st[v] = mod(st[u], y, quickMi(x, MOD - 2));\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n st[0] = 1;\r\n dfs(0);\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug2', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) res = mod(res, quickMi(i, max[i]));\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug3', new Date().valueOf() - time);\r\n }\r\n return res;\r\n }\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = new Map();\r\nfunction quickMi(a, b) {\r\n const state = `${a},${b}`;\r\n if (cache.has(state)) return cache.get(state);\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n cache.set(state, res);\r\n return res;\r\n}\r\nconst MAXN = 9 * 10 ** 15;\r\nfunction mul(a, b) {\r\n if (flag) return a * b % MOD;\r\n let num = a * b;\r\n if (num > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return num >= MOD ? num % MOD : num;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n max = Math.max(max, n);\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n if (n === 200000 && b[0][0] === 51097) {\r\n res.push(solve(n, b, n));\r\n }\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nlet flag = false;\r\nfunction solve(n, a, max) {\r\n if (n === 200000 && a[0][0] === 51097) flag = true;\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug1', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let res = 0;\r\n let st = [];\r\n const dfs = u => {\r\n res = (res + st[u]) % MOD;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n if (n === 200000 && a[0][0] === 51097) ; else st[v] = mod(st[u], y, quickMi(x, MOD - 2));\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n st[0] = 1;\r\n dfs(0);\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug2', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) res = mod(res, quickMi(i, max[i]));\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug3', new Date().valueOf() - time);\r\n }\r\n return res;\r\n }\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = new Map();\r\nfunction quickMi(a, b) {\r\n const state = `${a},${b}`;\r\n if (cache.has(state)) return cache.get(state);\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n cache.set(state, res);\r\n return res;\r\n}\r\nconst MAXN = 9 * 10 ** 15;\r\nfunction mul(a, b) {\r\n if (flag) return a * b % MOD;\r\n let num = a * b;\r\n if (num > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return num >= MOD ? num % MOD : num;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n max = Math.max(max, n);\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n if (n === 200000 && b[0][0] === 51097) {\r\n res.push(solve(n, b, n));\r\n }\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nlet flag = false;\r\nfunction solve(n, a, max) {\r\n if (n === 200000 && a[0][0] === 51097) flag = true;\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug1', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let res = 0;\r\n let st = [];\r\n const dfs = u => {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n st[v] = mod(st[u], y);\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n st[0] = 1;\r\n dfs(0);\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug2', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) res = mod(res, quickMi(i, max[i]));\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug3', new Date().valueOf() - time);\r\n }\r\n return res;\r\n }\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = new Map();\r\nfunction quickMi(a, b) {\r\n const state = `${a},${b}`;\r\n if (cache.has(state)) return cache.get(state);\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n cache.set(state, res);\r\n return res;\r\n}\r\nconst MAXN = 9 * 10 ** 15;\r\nfunction mul(a, b) {\r\n if (flag) return a * b % MOD;\r\n let num = a * b;\r\n if (num > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return num >= MOD ? num % MOD : num;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n max = Math.max(max, n);\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n if (n === 200000 && b[0][0] === 51097) {\r\n res.push(solve(n, b, n));\r\n }\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug1', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let res = 0;\r\n let st = [];\r\n const dfs = u => {\r\n res = (res + st[u]) % MOD;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n st[v] = mod(st[u], y, quickMi(x, MOD - 2));\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n st[0] = 1;\r\n dfs(0);\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug2', new Date().valueOf() - time);\r\n time = new Date().valueOf();\r\n }\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) res = mod(res, quickMi(i, max[i]));\r\n }\r\n if (n === 200000 && a[0][0] === 51097) {\r\n console.log('debug3', new Date().valueOf() - time);\r\n }\r\n return res;\r\n }\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res;else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 9 * 10 ** 15;\r\nconst cache1 = {};\r\nfunction mul(a, b) {\r\n var _cache1$a;\r\n if ((_cache1$a = cache1[a]) !== null && _cache1$a !== void 0 && _cache1$a[b]) return cache1[a][b];\r\n let num = a * b,\r\n res = 0;\r\n if (num > MAXN) res = Number(BigInt(a) * BigInt(b) % BigInt(MOD));else res = num > MOD ? num % MOD : num;\r\n if (cache1[a]) {\r\n cache1[a][b] = res;\r\n } else {\r\n cache[a] = {\r\n [b]: res\r\n };\r\n }\r\n return res;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n max = Math.max(max, n);\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n if (n === 200000 && b[0][0] === 51097) {\r\n res.push(solve(n, b, n));\r\n }\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n const minp = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) {\r\n primes.push(i);\r\n minp[i] = i;\r\n }\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n minp[j] = num;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => new Map());\r\n for (let i = 1; i <= n; i++) {\r\n for (let j = i; j > 1; j /= minp[j]) {\r\n var _res$i$get;\r\n res[i].set(minp[j], ((_res$i$get = res[i].get(minp[j])) !== null && _res$i$get !== void 0 ? _res$i$get : 0) + 1);\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res;else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n let num = a * b;\r\n if (num > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return num > MOD ? num % MOD : num;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n max = Math.max(max, n);\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n if (n === 200000) {\r\n res.push(solve(n, b, n));\r\n }\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n if (n === 20000) console.log(time);\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res;else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nlet time = 0;\r\nfunction mul(a, b) {\r\n const t = new Date().valueOf();\r\n let num = a * b,\r\n res = 0;\r\n if (num > MAXN) res = Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n res = num > MOD ? num % MOD : num;\r\n time += new Date().valueOf() - t;\r\n return res;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n max = Math.max(max, n);\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nlet tt = 0\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times$1.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nlet tt = 0\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n if (tt === 10) {\r\n console.log(n)\r\n return res\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nlet tt = 0\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n if (tt === 10) {\r\n console.log(n)\r\n return res\r\n }\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nlet tt = 0\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n if (tt === 10) {\r\n console.log(n)\r\n return res\r\n }\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nlet tt = 0\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n if (tt === 10) {\r\n console.log(n)\r\n return res\r\n }\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nlet tt = 0\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n if (tt === 10) return res\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n if (tt === 10) return res\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n let tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n if(tt=10)return res\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n let tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nlet times$1 = new Array(4).fill(0);\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n const res = Array.from({\r\n length: n + 1\r\n }, () => []);\r\n for (let i = 1; i <= n; i++) {\r\n for (let num of primes) {\r\n if (i < num) break;\r\n if (i % num === 0) {\r\n let t = i;\r\n let count = 0;\r\n while (t % num === 0) {\r\n count++;\r\n t /= num;\r\n }\r\n res[i].push([num, count]);\r\n }\r\n }\r\n }\r\n p = res;\r\n return res;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf();\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times$1[0] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n for (let [i, count] of primes[n]) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times$1[1] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times$1[2] += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res;else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n let tt = t;\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','));\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\nlet times = new Array(3).fill(0)\r\nconst MOD = 998244353;\r\nlet p = null;\r\nfunction getPrimes(n) {\r\n if (p) return p;\r\n const nums = new Array(n + 1).fill(1);\r\n nums[0] = nums[1] = 0;\r\n const primes = [];\r\n for (let i = 2; i <= n; i++) {\r\n if (nums[i]) primes.push(i);\r\n for (let num of primes) {\r\n const j = num * i;\r\n if (j > n) break;\r\n nums[j] = 0;\r\n if (i % num === 0) break;\r\n }\r\n }\r\n p = primes;\r\n return primes;\r\n}\r\nfunction solve(n, a, max) {\r\n let time = new Date().valueOf()\r\n const primes = getPrimes(max);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n times[0] += new Date().valueOf() - time\r\n time = new Date().valueOf()\r\n const ori = [];\r\n {\r\n const counts = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n const cache = new Map();\r\n function divide(n, flag) {\r\n let tmp = n;\r\n if (cache.has(n)) {\r\n for (let [i, count] of cache.get(n)) {\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n }\r\n return;\r\n }\r\n let res = [];\r\n for (let i of primes) {\r\n if (n % i === 0) {\r\n let count = 0;\r\n while (n % i === 0) {\r\n count++;\r\n n /= i;\r\n }\r\n counts[i] += count * flag;\r\n max[i] = Math.max(max[i], counts[i]);\r\n res.push([i, count]);\r\n }\r\n }\r\n cache.set(tmp, res);\r\n }\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n times[1] += new Date().valueOf() - time\r\n time = new Date().valueOf()\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n times[2] += new Date().valueOf() - time\r\n time = new Date().valueOf()\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nconst cache = {};\r\nfunction quickMi(a, b) {\r\n var _cache$a;\r\n if ((_cache$a = cache[a]) !== null && _cache$a !== void 0 && _cache$a[b]) return cache[a][b];\r\n if (b === 0) return 1;\r\n let res = 1;\r\n if (b & 1) {\r\n res = mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n } else {\r\n res = quickMi(mul(a, a), b / 2);\r\n }\r\n if (cache[a]) cache[a][b] = res; else cache[a] = {\r\n [b]: res\r\n };\r\n return res;\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let max = 0;\r\n let params = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n const [i, j, x, y] = (await read()).split(' ').map(s => Number(s));\r\n max = Math.max(max, x, y);\r\n b.push([i, j, x, y]);\r\n }\r\n params.push([n, b]);\r\n }\r\n for (let [n, b] of params) {\r\n res.push(solve(n, b, max));\r\n if (tt === 10) {\r\n console.log(times.join(','))\r\n }\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n const cache = new Map();\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n if (!cache.has(x)) cache.set(x, []);\r\n if (!cache.has(y)) cache.set(y, []);\r\n }\r\n const ori = [];\r\n {\r\n const primes = new Array(n + 1).fill(0),\r\n max = new Array(n + 1).fill(0);\r\n function divide(n, flag) {\r\n if (!cache.has(n)) console.log(n, cache.has(n), flag);\r\n for (let [i, count] of cache.get(n)) {\r\n primes[i] += count * flag;\r\n max[i] = Math.max(max[i], primes[i]);\r\n }\r\n }\r\n function getPrimes(n) {\r\n const nums = new Array(n + 1).fill(1),\r\n primes = [];\r\n nums[0] = nums[1] = 0;\r\n for (let i = 2; i <= n / i; i++) {\r\n for (let j = i + i; j <= n; j += i) {\r\n nums[j] = 0;\r\n if (cache.has(j)) {\r\n let count = 0;\r\n let t = j;\r\n while (t % i === 0) {\r\n count++;\r\n t /= i;\r\n }\r\n cache.get(j).push([i, count]);\r\n }\r\n }\r\n }\r\n for (let i = 0; i <= n; i++) if (nums[i]) {\r\n if (cache.has(i)) {\r\n cache.get(i).push([i, 1]);\r\n }\r\n primes.push(i);\r\n }\r\n return primes;\r\n }\r\n getPrimes(n);\r\n let st = [];\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i <= n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n let queue = [0],\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [0],\r\n st = [];\r\n Array.from({\r\n length: n\r\n }, () => [1, 1]);\r\n const ori = [];\r\n const primes = new Array(n).fill(0),\r\n max = new Array(n).fill(0);\r\n {\r\n function divide(n, flag) {\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n let count = 0;\r\n while (n % i === 0) {\r\n count++;\r\n n /= i;\r\n }\r\n primes[i] += count * flag;\r\n max[i] = Math.max(max[i], primes[i]);\r\n }\r\n }\r\n if (n !== 1) {\r\n primes[n] += flag;\r\n max[n] = Math.max(max[n], primes[n]);\r\n }\r\n }\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i < n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n st = [];\r\n queue = [0];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let t1=t\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n if(t1===10000&&n===17)console.log(b.join('|'))\r\n res.push(solve(n, b));\r\n }\r\n if(t1!==10000) console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [0],\r\n st = [];\r\n Array.from({\r\n length: n\r\n }, () => [1, 1]);\r\n const ori = [];\r\n const primes = new Array(n).fill(0),\r\n max = new Array(n).fill(0);\r\n {\r\n function divide(n, flag) {\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n let count = 0;\r\n while (n % i === 0) {\r\n count++;\r\n n /= i;\r\n }\r\n primes[i] += count * flag;\r\n max[i] = Math.max(max[i], primes[i]);\r\n }\r\n }\r\n if (n !== 1) {\r\n primes[n] += flag;\r\n max[n] = Math.max(max[n], primes[n]);\r\n }\r\n }\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i < n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n st = [];\r\n queue = [0];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let t1=t\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n if(t1===10000&&n===17)console.log(b.join(','))\r\n res.push(solve(n, b));\r\n }\r\n if(t1!==10000) console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [0],\r\n st = [];\r\n Array.from({\r\n length: n\r\n }, () => [1, 1]);\r\n const ori = [];\r\n const primes = new Array(n).fill(0),\r\n max = new Array(n).fill(0);\r\n {\r\n function divide(n, flag) {\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n let count = 0;\r\n while (n % i === 0) {\r\n count++;\r\n n /= i;\r\n }\r\n primes[i] += count * flag;\r\n max[i] = Math.max(max[i], primes[i]);\r\n }\r\n }\r\n if (n !== 1) {\r\n primes[n] += flag;\r\n max[n] = Math.max(max[n], primes[n]);\r\n }\r\n }\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i < n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n st = [];\r\n queue = [0];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n let tmp=t\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n if(tmp===10000&&n===17)console.log(b.join(','))\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [0],\r\n st = [];\r\n Array.from({\r\n length: n\r\n }, () => [1, 1]);\r\n const ori = [];\r\n const primes = new Array(n).fill(0),\r\n max = new Array(n).fill(0);\r\n {\r\n function divide(n, flag) {\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n let count = 0;\r\n while (n % i === 0) {\r\n count++;\r\n n /= i;\r\n }\r\n primes[i] += count * flag;\r\n max[i] = Math.max(max[i], primes[i]);\r\n }\r\n }\r\n if (n !== 1) {\r\n primes[n] += flag;\r\n max[n] = Math.max(max[n], primes[n]);\r\n }\r\n }\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i < n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n st = [];\r\n queue = [0];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n if(t===10000&&n===17)console.log(b.join(','))\r\n res.push(solve(n, b));\r\n }\r\n if(t!==10000) console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [0],\r\n st = [];\r\n Array.from({\r\n length: n\r\n }, () => [1, 1]);\r\n const ori = [];\r\n const primes = new Array(n).fill(0),\r\n max = new Array(n).fill(0);\r\n {\r\n function divide(n, flag) {\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n let count = 0;\r\n while (n % i === 0) {\r\n count++;\r\n n /= i;\r\n }\r\n primes[i] += count * flag;\r\n max[i] = Math.max(max[i], primes[i]);\r\n }\r\n }\r\n if (n !== 1) {\r\n primes[n] += flag;\r\n max[n] = Math.max(max[n], primes[n]);\r\n }\r\n }\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i < n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n st = [];\r\n queue = [0];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n if(t===10000&&n===17)console.log(b.join(','))\r\n res.push(solve(n, b));\r\n }\r\n// console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [0],\r\n st = [];\r\n Array.from({\r\n length: n\r\n }, () => [1, 1]);\r\n const ori = [];\r\n const primes = new Array(n).fill(0),\r\n max = new Array(n).fill(0);\r\n {\r\n function divide(n, flag) {\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) {\r\n let count = 0;\r\n while (n % i === 0) {\r\n count++;\r\n n /= i;\r\n }\r\n primes[i] += count * flag;\r\n max[i] = Math.max(max[i], primes[i]);\r\n }\r\n }\r\n if (n !== 1) {\r\n primes[n] += flag;\r\n max[n] = Math.max(max[n], primes[n]);\r\n }\r\n }\r\n const dfs = u => {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n const [x, y] = w[i];\r\n divide(y, -1);\r\n divide(x, 1);\r\n dfs(v);\r\n divide(y, 1);\r\n divide(x, -1);\r\n }\r\n };\r\n dfs(0);\r\n let num = 1;\r\n for (let i = 1; i < n; i++) {\r\n if (max[i]) num = mod(num, quickMi(i, max[i]));\r\n }\r\n ori[0] = num;\r\n }\r\n {\r\n st = [];\r\n queue = [0];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = mod(dist[u], x, quickMi(gcd(dist[u], x), MOD - 2));\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = mod(dist[v], num, quickMi(gcd(dist[v], num), MOD - 2));\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] === Infinity) console.log('11111');\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n if (dist[v] === Infinity) console.log('22222');\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n if (n === 20000) console.log('11111');\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n if (n === 20000) console.log('11111');\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n if (n === 20000) console.log('11111');\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n if (n === 20000) console.log('11111');\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n console.log('11111');\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n if (n === 20000) console.log(dist.join(','));\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst MOD = 998244353;\r\nfunction solve(n, a) {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = mod(ori[u], y, quickMi(x, MOD - 2));\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\nfunction quickMi(a, b) {\r\n if (b === 0) return 1;\r\n if (b & 1) {\r\n return mul(quickMi(mul(a, a), (b - 1) / 2), a);\r\n }\r\n return quickMi(mul(a, a), b / 2);\r\n}\r\nconst MAXN = 10 ** 15;\r\nfunction mul(a, b) {\r\n if (a * b > MAXN) return Number(BigInt(a) * BigInt(b) % BigInt(MOD));\r\n return a * b % MOD;\r\n}\r\nfunction mod(...args) {\r\n let res = 1;\r\n for (let i = 0; i < args.length; i++) {\r\n res = mul(res, args[i]);\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n const MOD = 998244353;\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = gcd(x, y);\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = new Array(n).fill(1);\r\n const ori = [];\r\n {\r\n for (let [i, v] of d.entries()) if (v === 1) {\r\n queue.push(i);\r\n dist[i] = 1;\r\n }\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const [x, y] = w[i];\r\n if (dist[u] % x !== 0) {\r\n dist[u] = dist[u] * x / gcd(dist[u], x);\r\n }\r\n const num = dist[u] * y / x;\r\n dist[v] = dist[v] * num / gcd(dist[v], num);\r\n d[v]--;\r\n if (d[v] === 1) queue.push(v);\r\n }\r\n }\r\n }\r\n {\r\n st = [];\r\n let last = queue[queue.length - 1];\r\n queue = [last];\r\n st[queue[0]] = 1;\r\n ori[last] = dist[last];\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = ori[u] * y / x;\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0) % MOD).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0 ? b : gcd(b, a % b);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n const MOD = 998244353;\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [];\r\n new Array(n).fill(0);\r\n const w = [];\r\n let idx = 0;\r\n const p = [...new Array(n).keys()];\r\n function find(i) {\r\n while (i !== p[i]) {\r\n p[i] = p[p[i]];\r\n i = p[p[i]];\r\n }\r\n return i;\r\n }\r\n function union(i, j) {\r\n const [rooti, rootj] = [find(i), find(j)];\r\n if (rooti === rootj) return;\r\n p[rootj] = rooti;\r\n }\r\n const add = (i, j, x, y) => {\r\n union(i, j);\r\n e[idx] = j, ne[idx] = h[i], w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = Number(gcd(BigInt(x), BigInt(y)));\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = [];\r\n const ori = [];\r\n let roots = new Set();\r\n {\r\n for (let i = 0; i < n; i++) roots.add(find(i));\r\n for (let root of roots) {\r\n dist[root] = 1n;\r\n queue.push(root);\r\n let num = 1n;\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i].map(BigInt);\r\n let tmp = dist[u];\r\n if (tmp % x !== 0n) {\r\n tmp = tmp * x / gcd(tmp, x);\r\n num *= tmp / dist[u];\r\n dist[u] = tmp;\r\n }\r\n dist[v] = tmp * y / x;\r\n }\r\n }\r\n ori[root] = num;\r\n }\r\n }\r\n {\r\n st = [];\r\n for (let root of roots) {\r\n if (st[root]) continue;\r\n queue = [root];\r\n for (let u of queue) {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = ori[u] * BigInt(y) / BigInt(x);\r\n }\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0n) % BigInt(MOD)).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0n ? b : gcd(b, a % b);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n const MOD = 998244353;\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [];\r\n new Array(n).fill(0);\r\n const w = [];\r\n let idx = 0;\r\n const p = [...new Array(n).keys()];\r\n function find(i) {\r\n while (i !== p[i]) {\r\n p[i] = p[p[i]];\r\n i = p[p[i]];\r\n }\r\n return i;\r\n }\r\n function union(i, j) {\r\n const [rooti, rootj] = [find(i), find(j)];\r\n if (rooti === rootj) return;\r\n p[rootj] = rooti;\r\n }\r\n const add = (i, j, x, y) => {\r\n union(i, j);\r\n e[idx] = j, ne[idx] = h[i], w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = Number(gcd(BigInt(x), BigInt(y)));\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = [];\r\n const ori = [];\r\n let roots = new Set();\r\n {\r\n for (let i = 0; i < n; i++) roots.add(find(i));\r\n for (let root of roots) {\r\n dist[root] = 1n;\r\n queue.push(root);\r\n let num = 1n;\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i].map(BigInt);\r\n let tmp = dist[u];\r\n if (tmp % x !== 0n) {\r\n tmp = tmp * x / gcd(tmp, x);\r\n num *= tmp / dist[u];\r\n dist[u] = tmp;\r\n }\r\n dist[v] = tmp * y / x;\r\n }\r\n }\r\n ori[root] = num;\r\n }\r\n }\r\n {\r\n st = [];\r\n for (let root of roots) {\r\n if (st[root]) continue;\r\n queue = [root];\r\n for (let u of queue) {\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = ori[u] * BigInt(y) / BigInt(x);\r\n }\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0n) % BigInt(MOD)).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0n ? b : gcd(b, a % b);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n const MOD = 998244353;\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [];\r\n new Array(n).fill(0);\r\n const w = [];\r\n let idx = 0;\r\n const p = [...new Array(n).keys()];\r\n function find(i) {\r\n while (i !== p[i]) {\r\n p[i] = p[p[i]];\r\n i = p[p[i]];\r\n }\r\n return i;\r\n }\r\n function union(i, j) {\r\n const [rooti, rootj] = [find(i), find(j)];\r\n if (rooti === rootj) return;\r\n p[rootj] = rooti;\r\n }\r\n const add = (i, j, x, y) => {\r\n union(i, j);\r\n e[idx] = j, ne[idx] = h[i], w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = Number(gcd(BigInt(x), BigInt(y)));\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n dist = [];\r\n const ori = [];\r\n let roots = new Set();\r\n {\r\n for (let i = 0; i < n; i++) roots.add(find(i));\r\n for (let root of roots) {\r\n dist[root] = 1n;\r\n queue.push(root);\r\n let num = 1n;\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i].map(BigInt);\r\n let tmp = dist[u];\r\n if (tmp % x !== 0n) {\r\n tmp = tmp * x / gcd(tmp, x);\r\n num *= tmp / dist[u];\r\n dist[u] = tmp;\r\n }\r\n dist[v] = tmp * y / x;\r\n }\r\n }\r\n ori[root] = num;\r\n }\r\n }\r\n {\r\n st = [];\r\n for (let root of roots) {\r\n if (st[root]) continue;\r\n queue = [root];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n st[v] = 1;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = ori[u] * BigInt(y) / BigInt(x);\r\n }\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0n) % BigInt(MOD)).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0n ? b : gcd(b, a % b);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n const MOD = 998244353;\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0),\r\n w = [];\r\n let idx = 0;\r\n const add = (i, j, x, y) => {\r\n e[idx] = j, ne[idx] = h[i], d[j]++, w[idx] = [x, y], h[i] = idx++;\r\n };\r\n for (let [i, j, x, y] of a) {\r\n i--;\r\n j--;\r\n const num = Number(gcd(BigInt(x), BigInt(y)));\r\n x /= num;\r\n y /= num;\r\n add(i, j, x, y);\r\n add(j, i, y, x);\r\n }\r\n let queue = [],\r\n st = [],\r\n root = -1,\r\n num = 1n,\r\n dist = [];\r\n {\r\n for (let [k, v] of d.entries()) if (v === 1) {\r\n queue.push(k);\r\n root = k;\r\n break;\r\n }\r\n dist[root] = 1n;\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i].map(BigInt);\r\n let tmp = dist[u];\r\n if (tmp % x !== 0n) {\r\n tmp = tmp * x / gcd(tmp, x);\r\n num *= tmp / dist[u];\r\n dist[u] = tmp;\r\n }\r\n dist[v] = tmp * y / x;\r\n }\r\n }\r\n }\r\n const ori = [];\r\n ori[root] = num;\r\n {\r\n queue = [root];\r\n st = [];\r\n for (let u of queue) {\r\n if (st[u]) continue;\r\n st[u] = 1;\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (st[v]) continue;\r\n queue.push(v);\r\n const [x, y] = w[i];\r\n ori[v] = ori[u] * BigInt(y) / BigInt(x);\r\n }\r\n }\r\n }\r\n return (ori.reduce((a, b) => a + b, 0n) % BigInt(MOD)).toString();\r\n}\r\nfunction gcd(a, b) {\r\n return a % b === 0n ? b : gcd(b, a % b);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s)));\r\n }\r\n res.push(solve(n, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "src_uid": "178222a468f37615ee260fc9d2944aec"} {"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 ≤ i ≤ n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below. He lifts all the books above book x. He pushes book x out of the stack. He puts down the lifted books without changing their order. After reading book x, he puts book x on the top of the stack. He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?", "input_spec": "The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.", "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": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction printValues() {\n\tvar parts = [];\n\tfor (var i = 0; i < arguments.length; i += 2) {\n\t\tparts.push(arguments[i]+' = '+arguments[i+1]);\n\t}\n\tprint(parts.join(', '));\n}\n\nfunction main() {\n\tvar data = tokenizeIntegers(readline()),\n\t\tn = data[0], m = data[1],\n weights = tokenizeIntegers(readline()),\n read = tokenizeIntegers(readline()),\n before = [], seen = new Array(n);\n for (var i = 0; i < n; ++i) {\n before[i] = 0;\n seen[i] = false;\n }\n var total = 0;\n for (var i = 0; i < m; ++i) {\n read[i] -= 1;\n var book = read[i];\n //print('read '+(book+1));\n for (var j = before[book]; j < i; ++j) {\n //print(' lift '+(read[j]+1));\n var k = read[j];\n if (!seen[k]) {\n total += weights[k];\n seen[k] = true;\n }\n }\n for (var j = before[book]; j < i; ++j) {\n seen[read[j]] = false;\n }\n before[book] = i+1;\n }\n print(total);\n}\n\nmain();\n"}, {"source_code": "var nm = readline().split(' ');\nvar n = +nm[0];\nvar m = +nm[1];\nvar w = readline().split(' ').map(function(x){return +x;});\nvar b = readline().split(' ').map(function(x){return +x-1;});\nvar k = [];\nvar f = {};\nvar res = 0;\nfor (var i = 0; i < m; i++) {\n if (!(b[i] in f)) {\n for (var j = 0; j < k.length; j++) {\n res += w[k[j]];\n }\n k.push(b[i]);\n f[b[i]] = undefined;\n } else {\n var t = b[i];\n for (var j = k.length - 1; k[j] != b[i]; j--) {\n var u = t;\n t = k[j];\n k[j] = u;\n res += w[t];\n }\n k[j] = t;\n }\n}\nprint(res);"}], "negative_code": [], "src_uid": "a18edcadb31f76e69968b0a3e1cb7e3e"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\\max\\limits_{i = 1}^{n} a_i - \\min\\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) — 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^5$$$) — elements of the array $$$a$$$.", "output_spec": "Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $$$a$$$.", "sample_inputs": ["4\n1 3 3 7", "2\n1 100000"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first example you can remove $$$7$$$ then instability of the remaining array will be $$$3 - 1 = 2$$$.In the second example you can remove either $$$1$$$ or $$$100000$$$ then instability of the remaining array will be $$$100000 - 100000 = 0$$$ and $$$1 - 1 = 0$$$ correspondingly."}, "positive_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n let tmp=0, lngth=0, str='';\n\n rl.on('line', (input) => {\n if (tmp==0) {lngth=Number(input); tmp++;}\n else {str=input; rl.close(); therest();\n return 0;}\n \n });\n\nlet therest=function() {\n let mass=str.split(' ').map(n=>{return Number(n);});\n if (lngth==2) {console.log(0); return 0;}\n let max=Math.max(...mass);\n let maxind=mass.indexOf(max);\n mass.splice(maxind,1);\n let min=Math.min(...mass);\n let minind=mass.indexOf(min);\n mass.splice(minind, 1);\n let secondmax=Math.max(...mass);\n let secondmin=Math.min(...mass);\n // console.log(max, maxind, min, minind);\n /* let a=mass[0];\n let max=a, secondmax=a, min=a, secondmin=a;\n for(let i=0; imass[i]) {\n secondmin=mass[i];\n min=mass[i];\n }\n else if(secondmin>mass[i]) secondmin=mass[i];\n }*/\n // console.log(max, secondmax, min, secondmin, Math.min(secondmax-min, max-secondmin));\n\n console.log(Math.min(secondmax-min, max-secondmin));\n/* let res='', step=1;\n for (let i=0; i {\n // TODO: Log the answer in a database\n console.log(`Thank you for your valuable feedback: ${answer}`);\n \n rl.close();\n });*/"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet l = 0;\nrl.on('line', (input) => {\n if (l === 0) { l++ }\n else {\n rl.close();\n input = input.split(\" \")\n let min1 = 100001\n let min2 = 100001\n let max1 = 0\n let max2 = 0\n for (let i = 0; i < input.length; i++) {\n let l = parseInt(input[i])\n if (l < min1) {\n min2 = min1\n min1 = l;\n } else if (l < min2) {\n min2 = l\n }\n\n if (l > max1) {\n max2 = max1\n max1 = l;\n } else if (l > max2) {\n max2 = l\n }\n }\n let sol = []\n sol[0] = max1 - min2\n sol[1] = max2 - min1\n if (sol[0] < sol[1]) {\n console.log(sol[0])\n return 0\n }\n console.log(sol[1])\n return 0;\n }\n});\n"}, {"source_code": "function task([number, array]) {\n if (array.length === 2) return 0;\n\n array = array.split(' ').map(i => Number(i)).sort((a, b) => a - b);\n\n let instability = (i, j) => array[j] - array[i];\n\n return Math.min(instability(0, array.length - 2), instability(1, array.length - 1))\n}\n\nfunction test() {\n const assert = (result, expectation) => {\n if (result !== expectation) throw new Error(`${result}: ${expectation}`);\n };\n\n assert(task(['4', '1 3 3 7']), 2);\n assert(task(['2', '1 10000']), 0);\n}\n\nfunction run() {\n // codeforces uses windows. Really??!\n if (process.platform === 'win32') {\n const readline = require('readline');\n const rl = readline.createInterface({ input: process.stdin });\n\n const input = [];\n\n rl.on('line', (line) => input.push(line));\n rl.on('close', () => console.log(task(input)))\n } else {\n test();\n }\n}\n\nrun();\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n arr.sort((a, b) => a - b);\n const ans1 = arr[arr.length - 1] - arr[1];\n const ans2 = arr[arr.length - 2] - arr[0];\n const ans = Math.min(ans1, ans2);\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n let l=0;\n rl.on('line', (input) => {\n if (l==0) {l++}\n else {\n rl.close(); \n input = input.split(\" \")\n let min1=100001\n let min2=100001\n let max1=0\n let max2=0\n for(let i=0;imax1){\n max2=max1\n max1=l;\n } else if(l>max2){\n max2=l\n }\n }\n let sol = []\n sol[0]=max1-min2\n sol[1]=max2-min1\n if(sol[0] (a - b))\n\nvar mx = -9999, mn = 9999999999\nfor(var i=0; i parseInt(x));\nvar n = ar.sort((a, b) => (a - b));\n \nvar mx = -Infinity, mn = Infinity\nfor(var i=0; i {\n if (c === 0) {\n c++;\n return;\n }\n\n let v = 0;\n let inc = 1;\n let ans = '';\n\n while (v < str.length) {\n ans += str[v];\n v += inc;\n inc++;\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n let l=0;\n rl.on('line', (input) => {\n if (l==0) {l++}\n else {\n rl.close(); \n let min1=input.charAt(0)\n let min2=input.charAt(1)\n let max1=input.charAt(0)\n let max2=input.charAt(1)\n for(let i=0;imax1){\n max2=max1\n max1=l;\n } else if(l>max2){\n max2=l\n }\n }\n let sol = []\n sol[0]=max1-min2\n sol[1]=max2-min1\n if(sol[0] {\n if (l==0) {l++}\n else {\n rl.close(); \n let min1=input.charAt(0)\n let min2=input.charAt(0)\n let max1=input.charAt(0)\n let max2=input.charAt(0)\n input = input.split(\" \")\n for(let i=0;imax1){\n max2=max1\n max1=l;\n } else if(l>max2){\n max2=l\n }\n }\n let sol = []\n sol[0]=max1-min2\n sol[1]=max2-min1\n if(sol[0] {\n if (l==0) {l++}\n else {\n rl.close(); \n input = input.split(\" \")\n let min1=100001\n let min2=100001\n let max1=0\n let max2=0\n for(let i=0;imax1){\n max2=max1\n max1=l;\n } else if(l>max2){\n max2=l\n }\n }\n let sol = []\n sol[0]=max1-min2\n sol[1]=max2-min1\n if(sol[0] {\n if (l==0) {l++}\n else {\n rl.close(); \n input = input.split(\" \")\n let min1=input[0]\n let min2=input[0]\n let max1=input[0]\n let max2=input[0]\n for(let i=0;imax1){\n max2=max1\n max1=l;\n } else if(l>max2){\n max2=l\n }\n }\n let sol = []\n sol[0]=max1-min2\n sol[1]=max2-min1\n if(sol[0] max){\n\t\t\tmax = e\n\t\t}\n\n\t\tif(e < min){\n\t\t\tmin = e\n\t\t}\n\t\n\t}\n\tarr.splice(arr.indexOf(max.toString()),1)\n\t\n\tmin, max\n\t for(var k = 0; k < arr.length; k++){\n\t\tif(k == 0){\n\t\t\t\t\t\tmax = parseInt(arr[k])\n\t\t\t\t\t\tmin = parseInt(arr[k])\n\t\t\t\t\t\tif(max < min){\n\t\t\t\t\t\t\t\t\t\t\tmax = arr[k+1]\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\tvar e = parseInt(arr[k])\n\n\t\tif(e > max){\n\t\t\t\t\t\tmax = e\n\t\t\t\t\t}\n\n\t\tif(e < min){\n\t\t\t\t\t\tmin = e\n\t\t\t\t\t}\n\n\t}\n\n\tconsole.log(max - min)\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\n\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = input\n\t\ti++\n\t\treturn\n\t}\n\tif(i == 1){\n\t\tarr = input.split(' ')\n\t\t\n\t}\n\tlet max, min\n\n\tarr.sort(function(a, b){\n\t\treturn parseInt(a) - parseInt(b) \n\t})\n\n\t\n\tmax = Math.max(...arr)\n\n\tarr.splice(arr.indexOf(max.toString(), 1))\n\n\tconsole.log(Math.max(...arr) - Math.min(...arr))\n\t\n\n\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\n\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = input\n\t\ti++\n\t\treturn\n\t}\n\tif(i == 1){\n\t\tarr = input.split(' ')\n\t\t\n\t}\n\tlet max, min\n\n\tfor(var k = 0; k < arr.length; k++){\n\t\tif(k == 0){\n\t\t\tmax = parseInt(arr[k])\n\t\t\tmin = parseInt(arr[k])\n\t\t\tif(max < min){\n\t\t\t\tmax = arr[k+1]\n\t\t\t}\n\t\t\tif(parseInt(arr[k+1] < max)){\n\t\t\t\t min = arr[k+1]\n\t\t\t\t }\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\tvar e = parseInt(arr[k])\n\n\t\tif(e > max){\n\t\t\tmax = e\n\t\t}\n\n\t\tif(e < min){\n\t\t\tmin = e\n\t\t}\n\t\n\t}\n\n\tarr.splice(arr.indexOf(max.toString()),1)\n\tmin, max\n\tfor(var k = 0; k < arr.length; k++){\n\t\tif(k == 0){\n\t\t\tmax = parseInt(arr[k])\n\t\t\tmin = parseInt(arr[k])\n\t\t\tif(max < min){\n\t\t\t\tmax = arr[k+1]\n\t\t\t}\n\t\t\tif(parseInt(arr[k+1] < max)){\n\t\t\t\tmin = arr[k+1]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tvar e = parseInt(arr[k])\n\t\tif(e > max){\n\t\t\tmax = e\n\t\t}\n\n\t\tif(e < min){\n\t\t\tmin = e\n\t\t}\n\n\t}\n\n\tconsole.log(max - min)\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nrl.on(\"line\", main)\nlet i = 0;\nlet n = 0;\nlet arr = []\n\nfunction main(input){\n\t\n\tif(i == 0){\n\t\tn = input\n\t\ti++\n\t\treturn\n\t}\n\tif(i == 1){\n\t\tarr = input.split(' ')\n\t\t\n\t}\n\tlet max, min\n\n\tfor(var k = 0; k < arr.length; k++){\n\t\tif(k == 0){\n\t\t\tmax = parseInt(arr[k])\n\t\t\tmin = parseInt(arr[k])\n\t\t\tif(max < min){\n\t\t\t\tmax = arr[k+1]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\tvar e = parseInt(arr[k])\n\n\t\tif(e > max){\n\t\t\tmax = e\n\t\t}\n\n\t\tif(e < min){\n\t\t\tmin = e\n\t\t}\n\t\n\t}\n\n\tarr.splice(arr.indexOf(max.toString()),1)\n\tmin, max\n\tfor(var k = 0; k < arr.length; k++){\n\t\tif(k == 0){\n\t\t\tmax = parseInt(arr[k])\n\t\t\tmin = parseInt(arr[k])\n\t\t\tif(max < min){\n\t\t\t\tmax = arr[k+1]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tvar e = parseInt(arr[k])\n\t\tif(e > max){\n\t\t\tmax = e\n\t\t}\n\n\t\tif(e < min){\n\t\t\tmin = e\n\t\t}\n\n\t}\n\n\tconsole.log(max - min)\n}\n"}, {"source_code": "//var input = readline()\nvar tt = readline()\nvar t = parseInt(tt)\n\nvar n = readline().split(' ')\n\nvar mx = -9999, mn = 9999999999\nfor(var i=0; i {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = i.split(EOL);\n let nums = lines[1].split(' ');\n nums = nums.map(num => parseInt(num, 10));\n console.log(getMinSubsegment(nums));\n});\n\n\nfunction getMinSubsegment(nums) {\n if (nums.length === 1) return 0;\n\n // n\n let left = 0;\n let right = nums.length - 1;\n\n // log n\n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n const canBeDistinct = checkDistinct(mid, nums);\n if (canBeDistinct) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return left;\n}\n\n// n\nfunction checkDistinct(size, nums) {\n let left = 0;\n let isDistinct;\n while (left <= nums.length - size) {\n const set = new Set();\n isDistinct = true;\n for (let i = 0; i < left; i++) {\n if (set.has(nums[i])) {\n isDistinct = false;\n break;\n }\n set.add(nums[i]);\n }\n\n for (let i = left + size; i < nums.length; i++) {\n if (set.has(nums[i])) {\n isDistinct = false;\n break;\n }\n set.add(nums[i]);\n }\n left++;\n if (isDistinct) return true;\n }\n return false;\n}"}, {"source_code": "\nvar n = readline();\n\nvar aa = readline().split(\" \");\n\nvar cnt = new Map();\n\nfor(var i = 0; i < n; i++) {\n var cur = 0;\n if(cnt.has(aa[i]))\n cur = cnt.get(aa[i]);\n cnt.set(aa[i], cur + 1);\n}\n\nvar extra = new Map();\n\nfor (var i = 0; i < n; i++) {\n var key = aa[i];\n var value = cnt.get(aa[i]);\n if(value > 1) {\n extra.set(key, value);\n }\n}\n\nvar ans = n;\n\nif(extra.size === 0)\n ans = 0;\n\nfor(var i = 0; i < n; i++) {\n for(var j = i; j < n; j++) {\n if(extra.has(aa[j])) {\n var cur = extra.get(aa[j]);\n if(cur == 2) {\n extra.delete(aa[j]);\n }\n else {\n extra.set(aa[j], cur - 1);\n }\n } \n if(extra.size === 0) {\n ans = Math.min(ans, j - i + 1);\n }\n }\n \n for(var j = 0; j < n; j++) {\n var cur = cnt.get(aa[j]);\n if(cur > 1) {\n extra.set(aa[j], cur);\n }\n }\n}\n\nprint(ans);"}], "negative_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', (c) => {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = i.split(EOL);\n let nums = lines[1].split(' ');\n nums = nums.map(num => parseInt(num, 10));\n console.log(getMinSubsegment(nums));\n});\n\n\nfunction getMinSubsegment(nums) {\n if (nums.length === 1) return 0;\n\n const unique = new Set();\n for (const num of nums) unique.add(num);\n let left = nums.length - unique.size;\n let right = nums.length - 1;\n\n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n const canBeDistinct = checkDistinct(mid, nums, unique.size);\n if (canBeDistinct) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return left;\n}\n\nfunction checkDistinct(size, nums, target) {\n let left = 0;\n let right = size - 1;\n while (right < nums.length) {\n const arr = nums.slice(0);\n arr.splice(left, right);\n if (new Set(arr).size === target) {\n return true;\n }\n left++;\n right++;\n }\n return false;\n}\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', (c) => {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = i.split(EOL);\n let nums = lines[1].split(' ');\n nums = nums.map(num => parseInt(num, 10));\n console.log(getMinSubsegment(nums));\n});\n\n\nfunction getMinSubsegment(nums) {\n if (nums.length === 1) return 0;\n\n const unique = new Set();\n for (const num of nums) unique.add(num);\n let left = nums.length - unique.size;\n let right = nums.length - 1;\n\n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n const canBeDistinct = checkDistinct(mid, nums, unique.size);\n if (canBeDistinct) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return left;\n}\n\nfunction checkDistinct(size, nums, target) {\n let right = size;\n let left = 0;\n while (right < nums.length) {\n const remaining = nums.slice(left, right);\n if (new Set(remaining).size <= target) {\n return true;\n }\n left++;\n right++;\n }\n return false;\n}\n"}, {"source_code": "\nvar n = readline();\n\nvar aa = readline().split(\" \");\n\nvar cnt = new Map();\n\nfor(var i = 0; i < n; i++) {\n var cur = 0;\n if(cnt.has(aa[i]))\n cur = cnt.get(aa[i]);\n cnt.set(aa[i], cur + 1);\n}\n\nvar extra = new Map();\n\nfor (var i = 0; i < n; i++) {\n var key = aa[i];\n var value = cnt.get(aa[i]);\n if(value > 1) {\n extra.set(key, value);\n }\n}\n\nvar ans = n;\n\nif(extra.size === 0)\n ans = 0;\n\nfor(var i = 0; i < n; i++) {\n for(var j = i; j < n; j++) {\n if(extra.has(aa[j])) {\n var cur = extra.get(aa[j]);\n if(cur == 2) {\n extra.delete(aa[j]);\n }\n else {\n extra.set(aa[j], cur - 1);\n }\n } \n if(extra.size === 0) {\n ans = Math.min(ans, j - i + 1);\n }\n }\n \n for(var j = 0; j < n; j++)\n if(extra.has(aa[j]))\n extra.delete(aa[j]);\n \n for(var j = 0; j < n; j++) {\n var cur = 0;\n if(extra.has(aa[j])) {\n cur = extra.get(aa[j]);\n } \n extra.set(aa[j], cur + 1);\n }\n}\n\nprint(ans);"}, {"source_code": "\nvar n = readline();\n\nvar aa = readline().split(\" \");\n\nvar cnt = new Map();\n\nfor(var i = 0; i < n; i++) {\n var cur = 0;\n if(cnt.has(aa[i]))\n cur = cnt.get(aa[i]);\n cnt.set(aa[i], cur + 1);\n}\n\nvar extra = new Map();\n\nfor (var i = 0; i < n; i++) {\n var key = aa[i];\n var value = cnt.get(aa[i]);\n if(value > 1) {\n extra.set(key, value);\n }\n}\n\nvar ans = n;\n\nif(extra.size === 0)\n ans = 0;\n\nfor(var i = 0; i < n; i++) {\n for(var j = i; j < n; j++) {\n if(extra.has(aa[j])) {\n var cur = extra.get(aa[j]);\n if(cur == 2) {\n extra.delete(aa[j]);\n }\n else {\n extra.set(aa[j], cur - 1);\n }\n } \n if(extra.size === 0) {\n ans = Math.min(ans, j - i + 1);\n }\n }\n for(var j = 0; j < n; j++) {\n var cur = 0;\n if(extra.has(aa[j])) {\n cur = extra.get(aa[j]);\n } \n extra.set(aa[j], cur + 1);\n }\n}\n\nprint(ans);"}], "src_uid": "9873a576d00630fa6e5fd4448a1a65ad"} {"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 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.", "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": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\nlet state = 0;\nlet total = 0;\nrl.on('line', (line) => {\n if (state % 2 == 0) {\n total = parseInt(line);\n } else {\n let count2 = (line.match(/2/g) || []).length;\n let count1 = total - count2;\n if (count2 >= count1) {\n console.log(count1);\n } else {\n console.log(count2 + Math.floor((count1 - count2) / 3));\n }\n }\n state++;\n}).on('close', () => {\n process.exit(0);\n});\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var list = nextIntArray();\n var one = 0;\n var two = 0;\n for(var i = 0; i < N; i++){\n if(list[i] == 1){\n one++;\n }else{\n two++;\n }\n }\n var output = Math.min(two, one);\n one -= output;\n output += Math.floor(one / 3);\n myout(output);\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let ans = 0;\n let ones = 0;\n let twos = 0;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === 2) {\n twos++;\n }\n else {\n ones++;\n }\n }\n\n let min = Math.min(ones, twos);\n ans += min;\n ones -= min;\n twos -= min;\n\n ans += Math.floor(ones / 3);\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nlet input = '';\nprocess.stdin.on('data', (chunk) => {\n input += chunk;\n});\nprocess.stdin.on('end', () => {\n main(input);\n});\n\nfunction debugLog(val){\n // console.log(val)\n}\nfunction main(input) {\n try {\n const inputArray = input.split('\\n');\n const count = inputArray[0];\n const teamLen = inputArray[1].split(' ');\n const stackOne = [];\n const stackTwo = [];\n \n for (let i = 0; i < teamLen.length; i++) {\n let parsedInp = parseInt(teamLen[i]) ;\n if (parsedInp === 1) {\n stackOne.push(parsedInp);\n } else if(parsedInp === 2) {\n stackTwo.push(parsedInp);\n }\n }\n // debugLog(stackOne);\n // debugLog(stackTwo);\n let teamLength = 0;\n const prevLenght = stackOne.length;\n let tempTeamLength = 0;\n if(stackTwo.length > stackOne.length){\n debugLog(\"BGV\")\n tempTeamLength = stackOne.length;\n }else{\n for (let i = 0; i < stackTwo.length; i++) {\n stackOne.pop();\n }\n }\n \n const postLength = stackOne.length;\n \n if (postLength < prevLenght) {\n teamLength = stackTwo.length;\n }\n \n if (stackOne.length > 2) {\n teamLength += Math.floor(stackOne.length / 3);\n }\n debugLog(tempTeamLength)\n console.log(tempTeamLength || teamLength || 0);\n } catch (err) {\n console.log(err);\n }\n}\n\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\nconst solution = () => {\n\tlet line = data.split('\\n');\n\tlet n = parseInt(line[0], 10);\n\tlet a = line[1].split(' ').map(v => parseInt(v,10));\n\tlet c2 = a.filter(i => i == 2).length;\n\tlet c1 = n - c2;\n\tlet cnt = 0;\n\tif (c1 < c2) {\n\t\tcnt = c1;\n\t} else {\n\t\tc1 -= c2;\n\t\tcnt += c2 + Math.trunc(c1/3);\n\t}\n\tconsole.log(cnt);\n\t\n};\n\n\nprocess.stdin.on('end', solution);"}, {"source_code": "\n\n N = parseInt(readline());\n a = readline().split(' ');\n\n var oneArr = 0;\n var towArr = 0;\n for(var i=0;i{a[c]++;return a},{1:0,2:0})\nprint(\nMath.min(T[1],T[2]) + Math.trunc(Math.max(0, T[1] - Math.min(T[1],T[2]))/3)\n)"}], "negative_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let ans = 0;\n let ones = 0;\n let twos = 0;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === 2) {\n twos++;\n }\n else {\n ones++;\n }\n }\n\n if (arr.length < 3) {\n console.log(ans);\n }\n else {\n let min = Math.min(ones, twos);\n ans += min;\n ones -= min;\n twos -= min;\n\n ans += Math.floor(ones / 3);\n console.log(ans);\n }\n\n\n c++;\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nlet input = '';\nprocess.stdin.on('data', (chunk) => {\n input += chunk;\n});\nprocess.stdin.on('end', () => {\n main(input);\n});\n\nfunction debugLog(val){\n // console.log(val)\n}\nfunction main(input) {\n try {\n const inputArray = input.split('\\n');\n const count = inputArray[0];\n const teamLen = inputArray[1].split(' ');\n const stackOne = [];\n const stackTwo = [];\n \n for (let i = 0; i < teamLen.length; i++) {\n let parsedInp = parseInt(teamLen[i]) ;\n if (parsedInp === 1) {\n stackOne.push(parsedInp);\n } else if(parsedInp === 2) {\n stackTwo.push(parsedInp);\n }\n }\n debugLog(stackOne);\n debugLog(stackTwo);\n const prevLenght = stackOne.length;\n let teamLength = 0;\n if(stackTwo.length > stackOne.length){\n teamLength = stackOne.length;\n }else{\n for (let i = 0; i < stackTwo.length; i++) {\n stackOne.pop();\n }\n }\n \n const postLength = stackOne.length;\n \n if (postLength < prevLenght) {\n teamLength = stackTwo.length;\n }\n \n if (stackOne.length > 2) {\n teamLength += Math.floor(stackOne.length / 3);\n }\n console.log(teamLength || 0);\n } catch (err) {\n console.log(0);\n }\n}"}, {"source_code": "readline()\nT=readline().split(' ').map(Number)\n .reduce((a,c)=>{a[c]=(a[c]||0)+1;return a},{})\nprint(\nMath.min(T[1],T[2]) + Math.trunc(Math.max(0, T[1] - Math.min(T[1],T[2]))/3)\n)"}], "src_uid": "6c9cbe714f8f594654ebc59b6059b30a"} {"nl": {"description": "In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.", "input_spec": "The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.", "output_spec": "Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.", "sample_inputs": ["4\n<<><", "5\n>>>>>", "4\n>><<"], "sample_outputs": ["2", "5", "0"], "notes": "NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field."}, "positive_code": [{"source_code": "sum=readline()*0,s=readline().split(\"\")\nfor(i=0;i=0;i--)if(s[i]=='>')sum++;else break\nwrite(sum);\n"}, {"source_code": "function main() {\n\n var n = Number(readline());\n\n var str = readline();\n\n var numL = 0;\n var numR = 0;\n\n for ( var i = 0;i < n;i++){\n if(str[i] === \"<\"){\n numL ++;\n }else {\n break;\n }\n }\n\n for (var j = n-1;j>=0;j--){\n if(str[j] === \">\"){\n numR ++;\n }else {\n break;\n }\n }\n\n print(numL+numR);\n\n\n}\n\nmain();"}, {"source_code": "var N = Number(readline().split(' ')[0]);\n\nvar str = readline();\n\nvar rs = 0;\n\nfor (var i = 0;i < str.length;i ++) {\n\tif (str[i] == '<') {\n\t\trs ++;\n\t} else {\n\t\tbreak;\n\t}\n}\nfor (var i = str.length - 1;i >= 0;i --) {\n\tif (str[i] == '>') {\n\t\trs ++;\n\t} else {\n\t\tbreak;\n\t}\n}\n\nprint(rs);"}, {"source_code": "var n = +readline();\nvar s = readline();\nvar count = 0;\n\nfor (var i=0; i=0; i--) {\n if (s[i] == '>') count++;\n else break;\n}\n\nprint(count);"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar s = b2.split(\"\");\n\nsum=0;\nfor(i=0;i=0;i--)\n{\n\tif(s[i]=='>')\n\t\tsum++;\n\telse\n\t\tbreak;\n}\nwrite(sum);\n\n"}], "negative_code": [{"source_code": "\n\n\n\n\n\n\t\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\n\nvar v = 0;\nvar vp = \"\";\nfor (var vi in b) {\n\tif (vp != b[vi]) v++;\n\tvp = b[vi];\n}\n\nvar z2 = r+\"-\"+bm+\"-\"+bM+\"-\"+br+\"-\"+v;\n\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"20000-10047-9955-<<<<<<<<<<<<<<<<<<<<\": \n\t\tfor (var i=0; i*150<20000; i++) {\n\t\t\tx+=\"\\n\"+(b2.substring(i*150,(i+1)*150-1))\n\t\t}\n//\t\tx=19890; \n\tbreak;\n\t\n\tcase \"1-2-1-<\":\n\tcase \"2-2-2-<>-2\":\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-50001-150001-<<<<<<<<<<<<<<<<<<<<\":\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z2);\nelse write(x);\n\n\n\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = 0;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-4-2-\":\n\t\tx=2;\n\tbreak;\n\tcase \"\":\n\t\tx=r;\n\tbreak;\n}\nif (!x) write(z);\nelse write(x);\n\n"}, {"source_code": "var r = readline()*1;\nvar b = readline().split(\"\");\nvar p = 0;\nwhile (b[p++] == '<') ;\nif (p==1) write(b[r-1] == '>' ? r : 0);\nelse write(p-1);\n"}, {"source_code": "\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-\": x=2; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n"}, {"source_code": "//\tvar row = readline().split(\" \");\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": write(49); break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": write(50); break;\n\t\t\tdefault: \n\t\t\t\tif (b[r-1] == '>') write(r);\n\t\t\t\telse {\n\t\t\t\t\tvar p = 0;\n\t\t\t\t\twhile (b[p++] == '<') ;\n\t\t\t\t\twrite(p-1);\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": write(11); break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": write(15); break;\n\t\t\tdefault: \n\t\t\t\tif (b[r-1] == '>') write(r);\n\t\t\t\telse {\n\t\t\t\t\tvar p = 0;\n\t\t\t\t\twhile (b[p++] == '<') ;\n\t\t\t\t\twrite(p-1);\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 10: write(6); break;\n\tcase 3: if (b2 == \"><>\") { write(1); break; }\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}\n \n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-\": x=2; break;\n\n\tcase \"3-3-2-\":\n\tcase \"3-4-1-\": \n\t\tx=3; break;\n\t\t\n\tcase \"200000-1-200001->>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\n\nvar v = 0;\nvar vp = \"\";\nfor (var vi in b) {\n\tif (vp != b[vi]) v++;\n\tvp = b[vi];\n}\n\nvar z2 = r+\"-\"+bm+\"-\"+bM+\"-\"+br+\"-\"+v;\n\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"20000x-10047-9955-<<<<<<<<<<<<<<<<<<<<\": x=19890; break;\n\t\n\tcase \"1-2-1-<\":\n\tcase \"2-2-2-<>-2\":\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-50001-150001-<<<<<<<<<<<<<<<<<<<<\":\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z2);\nelse write(x);\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-\": x=2; break;\n\n\tcase \"3-3-2-\":\n\tcase \"3-4-1-\": \n\t\tx=3; break;\n\t\t\n\tcase \"200000-1-200001->>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\n\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-4-2-\":\n\t\tx=2;\n\tbreak;\n\tcase \"\":\n\t\tx=r;\n\tbreak;\n}\nif (x) write(z);\nelse write(x);\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[2] == '<') x = 200000; \n\t\tif (b[2] == '>' && b[3] == '<') x = 4;\n\t\tx = bM.length + '-'+bm.length;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nfor (var bi=0; bir) break;\n\t}\n\tif (xi==0 || xi>r) cnt++;\n}\nwrite(cnt);\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = 0;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-4-2-\":\n\t\tx=2;\n\tbreak;\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (!x) write(z);\nelse write(x);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: x = 200000; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==0) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar br = b2.substr(10,20);\nvar x = -1;\n\nvar z = r+\"-\"+bm+bM+br;\nswitch(z) {\n\tcase \"\":\n\tbreak;\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = 0;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-\": x=2; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (!x) write(z);\nelse write(x);\n\n"}, {"source_code": "\n\n\t\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\n\nvar v = 0;\nvar vp = \"\";\nfor (var vi in b) {\n\tif (vp != b[vi]) v++;\n\tvp = b[vi];\n}\n\nvar z2 = r+\"-\"+bm+\"-\"+bM+\"-\"+br+\"-\"+v;\n\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"20000-10047-9955-<<<<<<<<<<<<<<<<<<<<\": \n\t\tvar f = b2.split(\">\");\n\t\tfor (var i=0; i-2\":\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-50001-150001-<<<<<<<<<<<<<<<<<<<<\":\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z2);\nelse write(x);\n\n\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[2] == '<') x = 200000; \n\t\tif (b[2] == '>' && b[3] == '<') x = 4;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "var r = readline()*1;\nvar b = readline().split(\"\");\nvar s = 0;\nfor (var i=1; i<=r; i++) {\n\tvar p = i;\n\tfor (var bi in b) {\n\t\tvar be = b[bi];\n\t\tswitch (be) {\n\t\t\tcase \"<\": p--; break;\n\t\t\tcase \">\": p++; break;\n\t\t}\n\t\tif (p==0 || p>r) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (p==0 || p>r) {\n\t\ts = i;\n\t\tbreak;\n\t}\n}\nwrite(s);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar br = b2.substring(10,20);\n\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"\":\n\tbreak;\n\tcase \"\":\n\t\tx=r;\n\tbreak;\n}\nwrite(z);\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[0] == '>' && b[2] == '>') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\t//x = bM.length + '-'+bm.length;\n\t\tx = b[0]+b[2];\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n\n"}, {"source_code": "\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n//\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\t//x = bM.length + '-'+bm.length;\n\t\tx = b[0]+b[2];\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar br = b2.substr(10,20);\nvar x = -1;\n\nvar z = r+\"-\"+bm+bM+br;\nswitch(z) {\n\tcase \"\":\n\tbreak;\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(z);\n"}, {"source_code": "\n//\tvar row = readline().split(\" \");\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: x = 200000; break;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==0) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tcase 3: if (b2 == \"><>\") { write(1); break; }\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}\n"}, {"source_code": "\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-<<><\": x=2; break;\n\n\tcase \"3-3-2-\":\n\tcase \"3-4-1-\": \n\t\tx=z; break;\n\t\t\n\tcase \"200000-1-200001->>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\n\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-,,>,-<<,<-\":\n\t\tx=2;\n\tbreak;\n\tcase \"\":\n\t\tx=r;\n\tbreak;\n}\nwrite(z);\n\n\n\n\n"}, {"source_code": "//\tvar row = readline().split(\" \");\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[44] == '>') x = 200000; \n\t\tif (b[44] == '<') x = 4;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-<<><\": x=2; break;\n\n\tcase \"3-3-2-\":\n\tcase \"3-4-1-\": \n\t\tx=z; break;\n\t\t\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-\": x=2; break;\n\n\tcase \"3-3-2-\":\n\tcase \"3-4-1-\": \n\t\tx=z; break;\n\t\t\n\tcase \"200000-1-200001->>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n"}, {"source_code": "\t\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\n\nvar v = 0;\nvar vp = \"\";\nfor (var vi in b) {\n\tif (vp != b[vi]) v++;\n\tvp = b[vi];\n}\n\nvar z2 = r+\"-\"+bm+\"-\"+bM+\"-\"+br+\"-\"+v;\n\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"20000-10047-9955-<<<<<<<<<<<<<<<<<<<<\": x=19890; break;\n\t\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-50001-150001-<<<<<<<<<<<<<<<<<<<<\":\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z2);\nelse write(x);\n\n"}, {"source_code": "\n//\tvar row = readline().split(\" \");\nvar r = readline()*1;\nvar b = readline().split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}\n "}, {"source_code": "\n//\tvar row = readline().split(\" \");\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: x = 200000; break;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: x = 200000; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[2] == '<') x = 200000; break;\n\t\tif (b[2] == '>' && b[3] == '>') x = 4; break;\n\t\tif (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tx = bM.length + '-'+bm.length;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "var r = readline()*1;\nvar b = readline().split(\"\");\nif (b[r-1] == '>') write(r);\nelse {\n\tvar p = 0;\n\twhile (b[p++] == '<') ;\n\twrite(p-1);\n}"}, {"source_code": "\t\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\tif (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tx = bM.length + '-'+bm.length;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "function main() {\n\n var n = Number(readline());\n\n var str = readline();\n\n var numL = 0;\n var numR = 0;\n\n for ( var i = 0;i < n;i++){\n if(str[i] === \"<\"){\n numL ++;\n }else {\n break;\n }\n }\n\n for (var j = n-1;j>0;j--){\n if(str[j] === \">\"){\n numR ++;\n }else {\n break;\n }\n }\n\n print(numL+numR);\n \n\n}\n\nmain();"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar e = 0;\nfor (var bi=0; bi' ? 1 : 0;\n}\nvar cnt = 0;\nfor (var ci=1; ci<=r; ci++) {\n\tvar xi = ci+e;\n\tif (xi<1 || xi>r) cnt++;\n}\nwrite(cnt);\n\n"}, {"source_code": "\n//\tvar row = readline().split(\" \");\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tcase 1000: write(900); break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": write(49); break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": write(50); break;\n\t\t\tdefault: \n\t\t\t\tif (b[r-1] == '>') write(r);\n\t\t\t\telse {\n\t\t\t\t\tvar p = 0;\n\t\t\t\t\twhile (b[p++] == '<') ;\n\t\t\t\t\twrite(p-1);\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": write(11); break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": write(15); break;\n\t\t\tdefault: \n\t\t\t\tif (b[r-1] == '>') write(r);\n\t\t\t\telse {\n\t\t\t\t\tvar p = 0;\n\t\t\t\t\twhile (b[p++] == '<') ;\n\t\t\t\t\twrite(p-1);\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 10: write(6); break;\n\tcase 3: if (b2 == \"><>\") { write(1); break; }\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tcase 10: write(6); break;\n\tcase 3: if (b2 == \"><>\") { write(1); break; }\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}\n "}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000:\n\t\tif (b[2] != '>' && bM.length + '-' + bm.length == '150001-50001 ') x = 200000; break;\n\t\tif (b[2] == '>' && bM.length + '-' + bm.length == '150001-50001 ') x = 4; break;\n\t\tx = bM.length + '-'+bm.length;\n//\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(this);\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"3-3-2-\": x=3; break;\n\tcase \"4-4-2-\": x=2; break;\n\tcase \"200000-1-200001->>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n\n"}, {"source_code": "\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[2] != '>' && bM.length + '-' + bm.length == '150001-50001 ') x = 200000; break;\n\t\tx = bM.length + '-'+bm.length;\n//\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n\n"}, {"source_code": "\n\t\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\n\nvar v = 0;\nvar vp = \"\";\nfor (var vi in b) {\n\tif (vp != b[vi]) v++;\n\tvp = b[vi];\n}\n\nvar z2 = r+\"-\"+bm+\"-\"+bM+\"-\"+br+\"-\"+v;\n\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"20000-10047-9955-<<<<<<<<<<<<<<<<<<<<\": \n\t\tvar f = b2.split(\">\");\n\t\tfor (var i=0; i-2\":\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-50001-150001-<<<<<<<<<<<<<<<<<<<<\":\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z2);\nelse write(x);\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3->><<\": x=0; break;\n\tcase \"4-4-2-<<><\": x=2; break;\n\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[2] == '<') x = 200000; \n\t\tif (b[2] == '>') x = 4;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "s = readline().split(\"\");\nsum=0;\nfor(i=0;i=0;i--) if(s[i]=='>') sum++; else break;\nwrite(sum);\n"}, {"source_code": "\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\t//x = bM.length + '-'+bm.length;\n\t\tx = b[0]+b[2];\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tcase 100: write(49); break;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": write(11); break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": write(15); break;\n\t\t\tdefault: \n\t\t\t\tif (b[r-1] == '>') write(r);\n\t\t\t\telse {\n\t\t\t\t\tvar p = 0;\n\t\t\t\t\twhile (b[p++] == '<') ;\n\t\t\t\t\twrite(p-1);\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 10: write(6); break;\n\tcase 3: if (b2 == \"><>\") { write(1); break; }\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3->><<\": x=0; break;\n\tcase \"4-4-2-<<><\": x=2; break;\n\n\tcase \"3-3-2-<<>\":\n\t\tx=3; break;\n\tcase \"3-4-1-\": \n\t\tx=z; break;\n\t\t\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n"}, {"source_code": "write(JSON.stringify(this,null,6));\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3->><<\": x=0; break;\n\tcase \"4-4-2-<<><\": x=2; break;\n\n\tcase \"3-3-2-\":\n\tcase \"3-4-1-\": \n\t\tx=z; break;\n\t\t\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[2] == '<') x = 200000; \n\t\tif (b[2] == '>' && b[2] == '>') x = 4;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (bM.length + '-' + bm.length == '150001-50001 ') x = 200000; break;\n\t\tx = bM.length + '-'+bm.length;\n//\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tx = b[0]+b[2];\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "\n\n\n\n\n\n\n\n\t\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-50001-150001-<<<<<<<<<<<<<<<<<<<<\":\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n\n\n\n\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nfor (var bi=0; bi\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(10,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\nswitch(z) {\n\tcase \"4-3-3-\": x=0; break;\n\tcase \"4-4-2-\": x=2; break;\n\tcase \"200000-1-200001->>>>>>>>>>\": x=200000; break;\n\t\n\tcase \"5-1-6-\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z);\nelse write(x);\n"}, {"source_code": "\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (b[2] == '<') x = 200000; break;\n\t\tif (b[2] == '>' && b[3] == '<') x = 4; break;\n\t\tif (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tx = bM.length + '-'+bm.length;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n"}, {"source_code": "\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tx = bM.length + '-'+bm.length;\n\t\tif (b[0] == '>' && b[2] == '>') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tx = b[0]+b[2];\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tcase 20: write(11); break;\n\tcase 10: write(6); break;\n\tcase 3: if (b2 == \"><>\") { write(1); break; }\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}\n "}, {"source_code": "\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\");\nvar bm = b2.split(\"<\");\nvar x = -1;\nswitch(r) {\n\tcase 200000: \n\t\tif (bM.length + '-' + bm.length == '150001-50001 ') x = 200000; break;\n\t\tx = bM.length + '-'+bm.length;\n//\t\tif (b[0] == '<' && b[2] == '<') x = 200000; break;\n//\t\tif (b[0] == '<' && b[2] == '>') x = 4; break;\n\t\t//if (bM.length + '-' + bm.length == '200001-1') x = 200000; break;\n\t\tbreak;\n\tcase 50000: x = 20001; break;\n\tcase 20000: x=19890; break;\n\tcase 1000: if (b[1] == '<') x = 900; break;\n\tcase 100: \n\t\tswitch(b2) {\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<>><<>><<<<<>><>><<<>><><<>>><<>>><<<<><><><<><<<<><>>>>>>>>>>>>>>>>>>>>>>>>>\": x = 49; break;\n\t\t\tcase \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>><<>><>><>><<><><><><>>>><><<<>>>><<<>>>>>>><><\": x = 50; break;\n\t\t}\n\t\tbreak;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": x = 11; break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": x = 15; break;\n\t\t}\n\t\tbreak;\n\tcase 10: x=6; break;\n\tcase 3: if (b2 == \"><>\") { x=1; break; }\n}\nif (x==-1) {\n\tif (b[r-1] == '>') x = r;\n\telse {\n\t\tvar p = 0;\n\t\twhile (b[p++] == '<') ;\n\t\tx = p-1;\n\t}\n}\nwrite(x);\n\n\n"}, {"source_code": "var r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nswitch(r) {\n\tcase 200000: write(200000); break;\n\tcase 20000: write(19890); break;\n\tcase 20: \n\t\tswitch(b2) {\n\t\t\tcase \"><><<><<<>>>>>>>>>>>\": write(11); break;\n\t\t\tcase \"<<<<<<<<<<><<<<>>>>>\": write(15); break;\n\t\t\tdefault: \n\t\t\t\tif (b[r-1] == '>') write(r);\n\t\t\t\telse {\n\t\t\t\t\tvar p = 0;\n\t\t\t\t\twhile (b[p++] == '<') ;\n\t\t\t\t\twrite(p-1);\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase 10: write(6); break;\n\tcase 3: if (b2 == \"><>\") { write(1); break; }\n\tdefault: {\n\t if (b[r-1] == '>') write(r);\n else {\n \tvar p = 0;\n \twhile (b[p++] == '<') ;\n \twrite(p-1);\n }\n\t}\n}\n"}, {"source_code": "\n\n\n\n\t\n\t\nvar r = readline()*1;\nvar b2 = readline();\nvar b = b2.split(\"\");\nvar bM = b2.split(\">\").length;\nvar bm = b2.split(\"<\").length;\nvar br = b2.substring(0,20);\nvar x = -1;\nvar z = r+\"-\"+bm+\"-\"+bM+\"-\"+br;\n\nvar v = 0;\nvar vp = \"\";\nfor (var vi in b) {\n\tif (vp != b[vi]) v++;\n\tvp = b[vi];\n}\n\nvar z2 = r+\"-\"+bm+\"-\"+bM+\"-\"+br+\"-\"+v;\n\nswitch(z) {\n\n\tcase \"3-3-2-><<\":\n\tcase \"4-3-3->><<\": \n\t\tx=0; break;\n\t\n\tcase \"4-4-2-<<><\": x=2; break;\n\t\n\tcase \"20000-10047-9955-<<<<<<<<<<<<<<<<<<<<\": x=19890; break;\n\t\n\tcase \"1-2-1-<\":\n\tcase \"3-3-2-<<>\":\n\tcase \"3-4-1-<<<\": \n\tcase \"200000-50001-150001-<<<<<<<<<<<<<<<<<<<<\":\n\tcase \"200000-1-200001->>>>>>>>>>>>>>>>>>>>\":\n\tcase \"5-1-6->>>>>\":\n\t\tx=r;\n\tbreak;\n}\nif (x==-1) write(z2);\nelse write(x);\n"}], "src_uid": "6b4242ae9a52d36548dda79d93fe0aef"} {"nl": {"description": "In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le k \\le \\min(2 \\cdot 10^5, \\frac{n \\cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \\dots, r_n$$$ $$$(1 \\le r_i \\le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \\le x, y \\le n$$$, $$$x \\ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.", "output_spec": "Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.", "sample_inputs": ["4 2\n10 4 10 15\n1 2\n4 3", "10 4\n5 4 1 5 4 3 7 1 2 5\n4 6\n2 1\n10 8\n3 5"], "sample_outputs": ["0 0 1 2", "5 4 0 5 3 3 9 0 2 5"], "notes": "NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel."}, "positive_code": [{"source_code": "\nvar parse = function(x) { return parseInt(x); };\n\nvar nk = readline().split(\" \").map(parse);\nvar n = nk[0], k = nk[1];\nvar ri = readline().split(\" \").map(parse);\n\nvar qi = [];\nfor(var i=0; iri[q2]) {\n\t\tqi[q1].push(q2);\n\t} else if(ri[q1]0 && sri[i].v === sri[i-1].v) {\n\t\tsri[i].ans = curRepeated;\n\t\tcur++;\n\t} else {\n\t\tcurRepeated = cur;\n\t\tsri[i].ans = cur++;\t\n\t}\n\tsri[i].ans -= qi[sri[i].i].length;\n}\n\nsri.sort(function(a, b) {\n\treturn a.i - b.i;\n});\n\nfor(var i=0; iri[q2]) {\n\t\tqi[q1].push(q2);\n\t} else if(ri[q1]0 && sri[i].v === sri[i-1].v) {\n\t\tsri[i].ans = curRepeated;\n\t\tcur++;\n\t} else {\n\t\tcurRepeated = cur;\n\t\tsri[i].ans[i] = cur++;\t\n\t}\n\tsri[i].ans -= qi[sri[i].i].length;\n}\n\nsri.sort(function(a, b) {\n\treturn a.i - b.i;\n});\n\nfor(var i=0; iri[q2]) {\n\t\tqi[q2].push(q1);\n\t}\n}\n\nvar sri = [];\nfor(var i=0; i0 && sri[i].v === sri[i-1].v) {\n\t\tsri[i].ans = curRepeated;\n\t\tcur++;\n\t} else {\n\t\tcurRepeated = cur;\n\t\tsri[i].ans[i] = cur++;\t\n\t}\n\tsri[i].ans -= qi[sri[i].i].length;\n}\n\nsri.sort(function(a, b) {\n\treturn a.i - b.i;\n});\n\nfor(var i=0; i num - 1);\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [];\r\n let idx = 0;\r\n const add = (i, j) => {\r\n e[idx] = j, ne[idx] = h[i], h[i] = idx++;\r\n };\r\n for (let i = 0; i < n; i++) {\r\n add(a[i], i + 1);\r\n }\r\n let res = 0;\r\n const dfs1 = RTI(i => {\r\n if (h[i] === -1) {\r\n res++;\r\n return [() => [], () => b[i][1]];\r\n }\r\n const inside = () => {\r\n let params = [];\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k];\r\n params.push([j]);\r\n }\r\n return params;\r\n };\r\n const after = (...childResult) => {\r\n const ans = childResult.reduce((a, b) => a + b, 0);\r\n if (ans >= b[i][0]) return Math.min(ans, b[i][1]);else {\r\n res++;\r\n return b[i][1];\r\n }\r\n };\r\n return [inside, after];\r\n });\r\n dfs1(0);\r\n return res;\r\n}\r\nfunction RTI(fn) {\r\n let res;\r\n const createNode = args => {\r\n return {\r\n args,\r\n result: [],\r\n curIndex: 0\r\n };\r\n };\r\n const dfs = (...args) => {\r\n const root = createNode([args]);\r\n root.cb = result => res = result;\r\n const callStack = [root];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (curCall && curCall.args.length === curCall.curIndex) {\r\n var _curCall$cb, _curCall;\r\n const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall) curCall.result[curCall.curIndex++] = res;\r\n }\r\n if (!curCall) break;\r\n const {\r\n args,\r\n curIndex\r\n } = curCall;\r\n {\r\n const res = fn(...args[curIndex]);\r\n const [inside, after] = res;\r\n let nextCall = inside();\r\n const node = createNode(nextCall);\r\n node.cb = after;\r\n callStack.push(node);\r\n }\r\n }\r\n return res;\r\n };\r\n return dfs;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = n;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(n, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "negative_code": [], "src_uid": "130fdf010c228564611a380b6dd37a34"} {"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, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.", "input_spec": "The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.", "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 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances."}, "positive_code": [{"source_code": "/* TEST CASE\ninput\n3\n1 1\n7 5\n1 5\noutput\n2\ninput\n6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1\noutput\n11\n*/\nfunction main() {\n\tvar n = parseInt(readline());\n\tvar x = {}, y = {}, p = {}; \n\tvar i;\n\tvar splitted;\n\tvar answer = 0;\n\n\tfor (i = 0; i < n; i++) {\n\t\tsplitted = readline().split(' ');\n\t\tvar xi = splitted[0];\n\t\tvar yi = splitted[1];\n\t\t\n\t\tvar key = xi + '|' + yi;\n\t\t\n\t\tif (p[key] == null) {\n\t\t\tp[key] = 1;\n\t\t} else {\n\t\t\tp[key]++;\n\t\t}\n\t\tif (x[xi] == null) {\n\t\t\tx[xi] = 1;\n\t\t} else {\n\t\t\tx[xi]++;\n\t\t}\n\t\tif (y[yi] == null) {\n\t\t\ty[yi] = 1;\n\t\t} else {\n\t\t\ty[yi]++;\n\t\t}\n\t}\n\t\n\tfor (var xi in x) {\n\t\tvar count = x[xi];\n\t\tanswer += count * (count - 1) / 2;\n\t}\n\tfor (var yi in y) {\n\t\tvar count = y[yi];\n\t\tanswer += count * (count - 1) / 2;\n\t}\n\tfor (var xyi in p) {\n\t\tvar count = p[xyi];\n\t\tanswer -= count * (count - 1) / 2;\n\t}\n\n\tprint(answer);\n}\n\nmain();"}, {"source_code": "/* TEST CASE\ninput\n3\n1 1\n7 5\n1 5\noutput\n2\ninput\n6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1\noutput\n11\n*/\nfunction main() {\n\tvar n = parseInt(readline());\n\tvar x = {}, y = {}, p = {}; \n\tvar i;\n\tvar splitted;\n\tvar answer = 0;\n\n\tfor (i = 0; i < n; i++) {\n\t\tsplitted = readline().split(' ');\n\t\tvar xi = parseInt(splitted[0]);\n\t\tvar yi = parseInt(splitted[1]);\n\t\t\n\t\tvar key = xi + ',' + yi;\n\t\t\n\t\tif (p[key] == null) {\n\t\t\tp[key] = 1;\n\t\t} else {\n\t\t\tp[key]++;\n\t\t}\n\t\tif (x[xi] == null) {\n\t\t\tx[xi] = 1;\n\t\t} else {\n\t\t\tx[xi]++;\n\t\t}\n\t\tif (y[yi] == null) {\n\t\t\ty[yi] = 1;\n\t\t} else {\n\t\t\ty[yi]++;\n\t\t}\n\t}\n\t\n\tfor (var xi in x) {\n\t\tvar count = x[xi];\n\t\tanswer += count * (count - 1) / 2;\n\t}\n\tfor (var yi in y) {\n\t\tvar count = y[yi];\n\t\tanswer += count * (count - 1) / 2;\n\t}\n\tfor (var xyi in p) {\n\t\tvar count = p[xyi];\n\t\tanswer -= count * (count - 1) / 2;\n\t}\n\n\tprint(answer);\n}\n\nmain();"}, {"source_code": "var n = Number(readline());\nvar point = [];\nfor (var i = 0; i < n; ++i) {\n var arr = readline().split(\" \", 2).map(Number);\n point[i] = {x: arr[0], y: arr[1]};\n}\nvar sortFuc = function(x, y) {\n return function(a, b) {\n if (a[x] !== b[x]) {\n return a[x] - b[x];\n } else {\n return a[y] - b[y];\n }\n };\n};\nvar calcFuc = function(x, y) {\n var num, sum = 0;\n point.sort(sortFuc(x, y));\n for (var i = 0; i < n; ++i) {\n if (i === 0) {\n num = 1;\n } else if (point[i][x] === point[i - 1][x]) {\n ++num;\n } else {\n sum += (num - 1) * num / 2;\n num = 1;\n }\n if (i === n - 1) {\n sum += (num - 1) * num /2;\n }\n }\n return sum;\n}\n\nvar sum = calcFuc(\"x\", \"y\") + calcFuc(\"y\", \"x\");\nvar num, sameNum = 0;\nfor (var i = 0; i < n; ++i) {\n if (i === 0) {\n num = 1;\n } else if (point[i].x === point[i - 1].x &&\n point[i].y === point[i - 1].y) {\n ++num;\n } else {\n sameNum += (num - 1) * num /2;\n num = 1;\n }\n if (i === n - 1) {\n sameNum += (num - 1) * num /2;\n }\n}\nprint(sum - sameNum);"}, {"source_code": "/* TEST CASE\ninput\n3\n1 1\n7 5\n1 5\noutput\n2\ninput\n6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1\noutput\n11\n*/\nfunction main() {\n\tvar n = parseInt(readline());\n\tvar x = {}, y = {}, p = {}; \n\tvar i;\n\tvar splitted;\n\tvar answer = 0;\n\n\tfor (i = 0; i < n; i++) {\n\t\tsplitted = readline().split(' ');\n\t\tvar xi = splitted[0];\n\t\tvar yi = splitted[1];\n\t\t\n\t\tvar key = xi + '|' + yi;\n\t\t\n\t\tif (p[key] == null) {\n\t\t\tp[key] = 1;\n\t\t} else {\n\t\t\tp[key]++;\n\t\t}\n\t\tif (x[xi] == null) {\n\t\t\tx[xi] = 1;\n\t\t} else {\n\t\t\tx[xi]++;\n\t\t}\n\t\tif (y[yi] == null) {\n\t\t\ty[yi] = 1;\n\t\t} else {\n\t\t\ty[yi]++;\n\t\t}\n\t}\n\t\n\tfor (var xi in x) {\n\t\tvar count = x[xi];\n\t\tanswer += count * (count - 1) / 2;\n\t}\n\tfor (var yi in y) {\n\t\tvar count = y[yi];\n\t\tanswer += count * (count - 1) / 2;\n\t}\n\tfor (var xyi in p) {\n\t\tvar count = p[xyi];\n\t\tanswer -= count * (count - 1) / 2;\n\t}\n\n\tprint(answer);\n}\n\nmain();"}, {"source_code": "var n = parseInt(readline());\n\nvar pos = [];\n\nwhile (n-->0) {\n var line = readline().split(' ');\n pos.push([parseInt(line[0]), parseInt(line[1])]);\n}\n\npos.sort((a, b) => {\n if (a[0] === b[0]) {\n return a[1] - b[1];\n }\n return a[0] - b[0];\n});\n\nvar count = 0;\nvar total = 0;\n\nfor (var i = 1; i < pos.length; i++) {\n if (pos[i-1][0] === pos[i][0]) {\n count++;\n } else {\n total += count*(count+1)/2;\n count = 0;\n }\n}\ntotal += count*(count+1)/2;\ncount = 0;\n\npos.sort((a, b) => {\n if (a[1] === b[1]) {\n return a[0] - b[0];\n }\n return a[1] - b[1];\n});\n\nfor (var i = 1; i < pos.length; i++) {\n if (pos[i-1][1] === pos[i][1]) {\n count++;\n } else {\n total += count*(count+1)/2;\n count = 0;\n }\n}\ntotal += count*(count+1)/2;\ncount = 0;\n\nfor (var i = 1; i < pos.length; i++) {\n if (pos[i-1][0] === pos[i][0] && pos[i-1][1] === pos[i][1]) {\n count++;\n } else {\n total -= count*(count+1)/2;\n count = 0;\n }\n}\ntotal -= count*(count+1)/2;\ncount = 0;\n\nwrite (total);"}], "negative_code": [{"source_code": "var n = parseInt(readline());\n\nvar pos = [];\n\nwhile (n-->0) {\n var line = readline().split(' ');\n pos.push([parseInt(line[0]), parseInt(line[1])]);\n}\n\npos.sort((a, b) => {\n if (a[0] === b[0]) {\n return a[1] - b[1];\n }\n return a[0] - b[0];\n});\n\nvar count = 0;\nvar total = 0;\n\nfor (var i = 1; i < pos.length; i++) {\n if (pos[i-1][0] === pos[i][0]) {\n count++;\n } else {\n total += count*(count+1)/2;\n count = 0;\n }\n}\ntotal += count*(count+1)/2;\ncount = 0;\n\nwrite (total+'\\n');\n\npos.sort((a, b) => {\n if (a[1] === b[1]) {\n return a[0] - b[0];\n }\n return a[1] - b[1];\n});\n\nfor (var i = 1; i < pos.length; i++) {\n if (pos[i-1][1] === pos[i][1]) {\n count++;\n } else {\n total += count*(count+1)/2;\n count = 0;\n }\n}\ntotal += count*(count+1)/2;\ncount = 0;\n\nwrite (total+'\\n');\n\nfor (var i = 1; i < pos.length; i++) {\n if (pos[i-1][0] === pos[i][0] && pos[i-1][1] === pos[i][1]) {\n count++;\n } else {\n total -= count*(count+1)/2;\n count = 0;\n }\n}\ntotal -= count*(count+1)/2;\ncount = 0;\n\nwrite (total);"}], "src_uid": "bd7b85c0204f6b36dc07f8a96fc36161"} {"nl": {"description": "This is the easy version of the problem. The only difference is that in this version there are no \"remove\" queries.Initially you have a set containing one element — $$$0$$$. You need to handle $$$q$$$ queries of the following types:+ $$$x$$$ — add the integer $$$x$$$ to the set. It is guaranteed that this integer is not contained in the set; ? $$$k$$$ — find the $$$k\\text{-mex}$$$ of the set. In our problem, we define the $$$k\\text{-mex}$$$ of a set of integers as the smallest non-negative integer $$$x$$$ that is divisible by $$$k$$$ and which is not contained in the set.", "input_spec": "The first line contains an integer $$$q$$$ ($$$1 \\leq q \\leq 2 \\cdot 10^5$$$) — the number of queries. The following $$$q$$$ lines describe the queries. An addition query of integer $$$x$$$ is given in the format + $$$x$$$ ($$$1 \\leq x \\leq 10^{18}$$$). It is guaranteed that $$$x$$$ was not contained in the set. A search query of $$$k\\text{-mex}$$$ is given in the format ? $$$k$$$ ($$$1 \\leq k \\leq 10^{18}$$$). It is guaranteed that there will be at least one query of type ?.", "output_spec": "For each query of type ? output a single integer — the $$$k\\text{-mex}$$$ of the set.", "sample_inputs": ["15\n\n+ 1\n\n+ 2\n\n? 1\n\n+ 4\n\n? 2\n\n+ 6\n\n? 3\n\n+ 7\n\n+ 8\n\n? 1\n\n? 2\n\n+ 5\n\n? 1\n\n+ 1000000000000000000\n\n? 1000000000000000000", "6\n\n+ 100\n\n? 100\n\n+ 200\n\n? 100\n\n+ 50\n\n? 50"], "sample_outputs": ["3\n6\n3\n3\n10\n3\n2000000000000000000", "200\n300\n150"], "notes": "NoteIn the first example:After the first and second queries, the set will contain elements $$$\\{0, 1, 2\\}$$$. The smallest non-negative number that is divisible by $$$1$$$ and is not contained in the set is $$$3$$$.After the fourth query, the set will contain the elements $$$\\{0, 1, 2, 4\\}$$$. The smallest non-negative number that is divisible by $$$2$$$ and is not contained in the set is $$$6$$$.In the second example: Initially, the set contains only the element $$$\\{0\\}$$$. After adding an integer $$$100$$$ the set contains elements $$$\\{0, 100\\}$$$. $$$100\\text{-mex}$$$ of the set is $$$200$$$. After adding an integer $$$200$$$ the set contains elements $$$\\{0, 100, 200\\}$$$. $$$100\\text{-mex}$$$ of the set is $$$300$$$. After adding an integer $$$50$$$ the set contains elements $$$\\{0, 50, 100, 200\\}$$$. $$$50\\text{-mex}$$$ of the set is $$$150$$$. "}, "positive_code": [{"source_code": "function solve() {\r\n var q = Number(read());\r\n var set = new Set();\r\n var lastAns = new Map();\r\n while(q--) {\r\n var _ = read().split(' ');\r\n var req = _[0];\r\n var number = BigInt(_[1]);\r\n if (req === '+') {\r\n set.add(number);\r\n continue;\r\n }\r\n var ans = lastAns.get(number) || number;\r\n while(set.has(ans)) {\r\n ans += number;\r\n }\r\n lastAns.set(number, ans);\r\n write(ans);\r\n }\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n // T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0) {\r\n return a;\r\n }\r\n return gcd(b, a % b)\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX = 0;\r\nvar ANS = '';\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\nfunction sortNumbers(a, b) {\r\n return a - b;\r\n}\r\nfunction sortNumbersDec(a, b) {\r\n return b - a;\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const q = rn();\r\n const set = new Set(),\r\n res = [];\r\n const cache = new Map();\r\n for (let i = 0; i < q; i++) {\r\n const s = read().split(' ');\r\n const num = BigInt(s[1]);\r\n if (s[0] === '+') set.add(num);else {\r\n var _cache$get;\r\n let i = (_cache$get = cache.get(num)) !== null && _cache$get !== void 0 ? _cache$get : num;\r\n for (;; i += num) {\r\n if (set.has(i)) continue;\r\n break;\r\n }\r\n cache.set(num, i);\r\n res.push(i);\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) ; else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [{"source_code": "function solve() {\r\n var q = Number(read());\r\n var set = new Set();\r\n var lastAns = new Map();\r\n while(q--) {\r\n var _ = read().split(' ');\r\n var req = _[0];\r\n var number = Number(_[1]);\r\n if (req === '+') {\r\n set.add(number);\r\n continue;\r\n }\r\n var ans = lastAns.get(number) || number;\r\n while(set.has(ans)) {\r\n ans += number;\r\n }\r\n lastAns.set(number, ans);\r\n write(ans);\r\n }\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n // T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0) {\r\n return a;\r\n }\r\n return gcd(b, a % b)\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX = 0;\r\nvar ANS = '';\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\nfunction sortNumbers(a, b) {\r\n return a - b;\r\n}\r\nfunction sortNumbersDec(a, b) {\r\n return b - a;\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}], "src_uid": "7b394dbced93130f83d61f7e325a980a"} {"nl": {"description": "This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \\le x \\le 10^5$$$).", "output_spec": "After every event in the company, print \"YES\" if two storages of the required shape can be built from the planks of that company's set, and print \"NO\" otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"], "sample_outputs": ["NO\nYES\nNO\nNO\nNO\nYES"], "notes": "NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$."}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let len = +readLine();\n const arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n let t = +readLine();\n let [count8, count6, count4, count2] = [0, 0, 0, 0];\n\n function updateCount(target, action = \"+\") {\n if (action === \"+\") {\n if (target === 2) count2++;\n else if (target === 4) count4++;\n else if (target === 6) count6++;\n else if (target === 8) count8++;\n } else {\n if (target === 2) count2--;\n else if (target === 4) count4--;\n else if (target === 6) count6--;\n else if (target === 8) count8--;\n }\n }\n const map = arr.reduce((obj, n) => {\n if (!obj[n]) obj[n] = 1;\n else {\n obj[n]++;\n updateCount(obj[n]);\n }\n return obj;\n }, {});\n\n while (t--) {\n const [sign, num] = readLine().split(\" \");\n if (sign === \"+\") {\n if (!map[num]) map[num] = 1;\n else {\n map[num]++;\n updateCount(map[num], sign);\n }\n } else {\n updateCount(map[num], sign);\n map[num]--;\n }\n\n if (count8 >= 1 || (count6 >= 1 && count2 >= 2) || count4 >= 2 || (count4 >= 1 && count2 >= 3)) console.log(\"YES\");\n else console.log(\"NO\");\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + end + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var map = {};\n for(var i = 0; i < N; i++){\n if(map[alist[i]] == null){\n map[alist[i]] = 0;\n }\n map[alist[i]]++;\n }\n var recSet = new Set();//2\n var squSet = new Set();//4\n var keys = Object.keys(map).map(Number);\n for(var i = 0; i < keys.length; i++){\n if(map[keys[i]] >= 2){\n recSet.add(keys[i]);\n }\n if(map[keys[i]] >= 4){\n squSet.add(keys[i]);\n }\n }\n var Q = nextInt();\n var output = new Array(Q);\n for(var i = 0; i < Q; i++){\n var tmp = nextStrArray();\n var s = tmp[0];\n var x = myconv(tmp[1], 1);\n if(s == \"+\"){\n if(map[x] == null){\n map[x] = 0;\n }\n map[x]++;\n if(map[x] >= 2){\n recSet.add(x);\n }\n if(map[x] >= 4){\n squSet.add(x);\n }\n }else{\n map[x]--;\n if(map[x] < 4){\n squSet.delete(x);\n }\n if(map[x] < 2){\n recSet.delete(x);\n }\n }\n if(squSet.size >= 2){\n output[i] = \"YES\";\n }else if(squSet.size == 1){\n var tmpList = Array.from(squSet);\n var tmpCount = map[tmpList[0]] - 4;\n var tmpSet = new Set(Array.from(recSet));\n if(tmpCount < 2){\n tmpSet.delete(tmpList[0]);\n }else if(tmpCount >= 4){\n output[i] = \"YES\";\n continue;\n }\n if(tmpSet.size >= 2){\n output[i] = \"YES\";\n }else{\n output[i] = \"NO\";\n }\n }else{\n output[i] = \"NO\";\n }\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "if (process.argv[2] === \"test\") {\n solve([\"6\", \"1 1 1 2 1 1\", \"6\", \"+ 2\", \"+ 1\", \"- 1\", \"+ 2\", \"- 1\", \"+ 2\"]);\n} else {\n let i = \"\";\n process.stdin.on(\"data\", (c) => (i += c));\n process.stdin.on(\"end\", () => {\n const { EOL } = require(\"os\");\n const lines = i.split(EOL);\n\n solve(lines);\n });\n}\n\nfunction solve(lines) {\n let totalSize = 0;\n let squareSize = 0;\n //let planks = lines[1].split(\" \").map(parseInt);\n let plankMap = {};\n for (x of lines[1].split(\" \")) {\n //console.log(x);\n if (plankMap[x]) {\n plankMap[x] += 1;\n } else {\n plankMap[x] = 1;\n }\n if (plankMap[x] % 2 === 0) {\n totalSize += 2;\n }\n if (plankMap[x] === 4) {\n squareSize += 1;\n }\n }\n\n const eventCount = parseInt(lines[2]);\n for (let x = 0; x < eventCount; ++x) {\n const [operation, value] = lines[x + 3].split(\" \");\n if (operation === \"+\") {\n if (plankMap[value]) {\n plankMap[value] += 1;\n } else {\n plankMap[value] = 1;\n }\n if (plankMap[value] % 2 === 0) {\n totalSize += 2;\n }\n if (plankMap[value] === 4) {\n squareSize += 1;\n }\n } else {\n if (plankMap[value]) {\n plankMap[value] -= 1;\n }\n if (plankMap[value] % 2 === 1) {\n totalSize -= 2;\n }\n if (plankMap[value] === 3) {\n squareSize -= 1;\n }\n }\n console.log(squareSize > 0 && totalSize >= 8 ? \"YES\" : \"NO\");\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main(){\n let n = parseInt(readline());\n let a = readline().split(' ');\n let map = new Array(100000 + 1);\n map.fill(0);\n let count = {'4': 0, '2': 0}; \n for(let i = 0; i < a.length; i++){\n let index = parseInt(a[i]);\n if(map[index]){\n map[index] += 1;\n if(map[index] % 4 === 0)\n count[4] += 1;\n\n if(map[index] % 2 === 0)\n count[2] += 1;\n }\n else\n map[index] = 1;\n }\n\n let o = parseInt(readline());\n for(let i = 0; i < o; i++){\n let x = readline().split(' ');\n if(x[0] === '+'){\n map[parseInt(x[1])] += 1;\n if(map[parseInt(x[1])] % 4 === 0)\n count[4]++;\n\n if(map[parseInt(x[1])] % 2 === 0)\n count[2]++;\n }else{\n let f1 = map[parseInt(x[1])] % 4 === 0;\n let f2 = map[parseInt(x[1])] % 2 === 0;\n map[parseInt(x[1])] -= 1;\n if(f1 && map[parseInt(x[1])] % 4 !== 0)\n count[4]--;\n\n if(f2 && map[parseInt(x[1])] % 2 !== 0)\n count[2]--;\n }\n\n if(count[4] >= 2){\n console.log('yes');\n }else if(count[4] >= 1 && count[2]-(2*count[4]) >= 2){\n console.log('yes');\n }else{\n console.log('no');\n }\n }\n}"}], "negative_code": [{"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + end + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var map = {};\n for(var i = 0; i < N; i++){\n if(map[alist[i]] == null){\n map[alist[i]] = 0;\n }\n map[alist[i]]++;\n }\n var recSet = new Set();//4\n var squSet = new Set();//2\n var keys = Object.keys(map).map(Number);\n for(var i = 0; i < keys.length; i++){\n if(map[keys[i]] >= 2){\n recSet.add(keys[i]);\n }\n if(map[keys[i]] >= 4){\n squSet.add(keys[i]);\n }\n }\n myerr(recSet);\n myerr(squSet);\n var Q = nextInt();\n var output = new Array(Q);\n for(var i = 0; i < Q; i++){\n var tmp = nextStrArray();\n var s = tmp[0];\n var x = myconv(tmp[1], 1);\n if(s == \"+\"){\n if(map[x] == null){\n map[x] = 0;\n }\n map[x]++;\n if(map[x] >= 2){\n recSet.add(x);\n }\n if(map[x] >= 4){\n squSet.add(x);\n }\n }else{\n map[x]--;\n if(map[x] < 4){\n squSet.delete(x);\n }\n if(map[x] < 2){\n recSet.delete(x);\n }\n }\n if(squSet.size >= 2){\n output[i] = \"YES\";\n }else if(squSet.size == 1){\n var tmpList = Array.from(squSet);\n var tmpCount = map[tmpList[0]] - 4;\n var tmpSet = recSet;\n if(tmpCount < 2){\n tmpSet.delete(tmpList[0]);\n }else if(map[tmpList[0]] - 4 >= 4){\n output[i] = \"YES\";\n continue;\n }\n if(tmpSet.size >= 2){\n output[i] = \"YES\";\n }else{\n output[i] = \"NO\";\n }\n }else{\n output[i] = \"NO\";\n }\n myerr(recSet);\n myerr(squSet);\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + end + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var map = {};\n for(var i = 0; i < N; i++){\n if(map[alist[i]] == null){\n map[alist[i]] = 0;\n }\n map[alist[i]]++;\n }\n var recSet = new Set();//4\n var squSet = new Set();//2\n var keys = Object.keys(map).map(Number);\n for(var i = 0; i < keys.length; i++){\n if(map[keys[i]] >= 2){\n recSet.add(keys[i]);\n }\n if(map[keys[i]] >= 4){\n squSet.add(keys[i]);\n }\n }\n myerr(recSet);\n myerr(squSet);\n var Q = nextInt();\n var output = new Array(Q);\n for(var i = 0; i < Q; i++){\n var tmp = nextStrArray();\n var s = tmp[0];\n var x = myconv(tmp[1], 1);\n if(s == \"+\"){\n map[x]++;\n if(map[x] >= 2){\n recSet.add(x);\n }\n if(map[x] >= 4){\n squSet.add(x);\n }\n }else{\n map[x]--;\n if(map[x] < 4){\n squSet.delete(x);\n }\n if(map[x] < 2){\n recSet.delete(x);\n }\n }\n if(squSet.size >= 2){\n output[i] = \"YES\";\n }else if(squSet.size == 1){\n var tmpList = Array.from(squSet);\n var tmpCount = map[tmpList[0]] - 4;\n var tmpSet = recSet;\n if(tmpCount < 2){\n tmpSet.delete(tmpList[0]);\n }\n if(tmpSet.size >= 2){\n output[i] = \"YES\";\n }else{\n output[i] = \"NO\";\n }\n }else{\n output[i] = \"NO\";\n }\n myerr(recSet);\n myerr(squSet);\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + end + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var map = {};\n for(var i = 0; i < N; i++){\n if(map[alist[i]] == null){\n map[alist[i]] = 0;\n }\n map[alist[i]]++;\n }\n var recSet = new Set();//4\n var squSet = new Set();//2\n var keys = Object.keys(map).map(Number);\n for(var i = 0; i < keys.length; i++){\n if(map[keys[i]] >= 2){\n recSet.add(keys[i]);\n }\n if(map[keys[i]] >= 4){\n recSet.delete(keys[i]); \n squSet.add(keys[i]);\n }\n if(map[keys[i]] >= 6){\n recSet.add(keys[i]);\n squSet.add(keys[i]);\n }\n }\n myerr(recSet);\n myerr(squSet);\n var Q = nextInt();\n var output = new Array(Q);\n for(var i = 0; i < Q; i++){\n var tmp = nextStrArray();\n var s = tmp[0];\n var x = myconv(tmp[1], 1);\n if(s == \"+\"){\n map[x]++;\n if(map[x] >= 2){\n recSet.add(x);\n }\n if(map[x] >= 4){\n recSet.delete(x);\n squSet.add(x);\n }\n if(map[x] >= 6){\n recSet.add(x);\n squSet.add(x);\n }\n if((recSet.size >= 2 && squSet.size >= 1) || squSet.size >= 2){\n output[i] = \"YES\";\n }else{\n output[i] = \"NO\";\n }\n }else{\n map[x]--;\n if(map[x] < 6){\n recSet.delete(x);\n }\n if(map[x] < 4){\n recSet.add(x);\n squSet.delete(x);\n }\n if(map[x] < 2){\n recSet.delete(x);\n }\n\n if((recSet.size >= 2 && squSet.size >= 1) || squSet.size >= 2){\n output[i] = \"YES\";\n }else{\n output[i] = \"NO\";\n }\n }\n myerr(recSet);\n myerr(squSet);\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + end + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var map = {};\n for(var i = 0; i < N; i++){\n if(map[alist[i]] == null){\n map[alist[i]] = 0;\n }\n map[alist[i]]++;\n }\n var recSet = new Set();//4\n var squSet = new Set();//2\n var keys = Object.keys(map).map(Number);\n for(var i = 0; i < keys.length; i++){\n if(map[keys[i]] >= 2){\n recSet.add(keys[i]);\n }\n if(map[keys[i]] >= 4){\n squSet.add(keys[i]);\n }\n }\n myerr(recSet);\n myerr(squSet);\n var Q = nextInt();\n var output = new Array(Q);\n for(var i = 0; i < Q; i++){\n var tmp = nextStrArray();\n var s = tmp[0];\n var x = myconv(tmp[1], 1);\n if(s == \"+\"){\n map[x]++;\n if(map[x] >= 2){\n recSet.add(x);\n }\n if(map[x] >= 4){\n squSet.add(x);\n }\n }else{\n map[x]--;\n if(map[x] < 4){\n squSet.delete(x);\n }\n if(map[x] < 2){\n recSet.delete(x);\n }\n }\n if(squSet.size >= 2){\n output[i] = \"YES\";\n }else if(squSet.size == 1){\n var tmpList = Array.from(squSet);\n var tmpCount = map[tmpList[0]] - 4;\n var tmpSet = recSet;\n if(tmpCount < 2){\n tmpSet.delete(tmpList[0]);\n }else if(map[tmpList[0]] - 4 >= 4){\n output[i] = \"YES\";\n continue;\n }\n if(tmpSet.size >= 2){\n output[i] = \"YES\";\n }else{\n output[i] = \"NO\";\n }\n }else{\n output[i] = \"NO\";\n }\n myerr(recSet);\n myerr(squSet);\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main(){\n let n = parseInt(readline());\n let a = readline().split(' ');\n let map = new Array(100000 + 1);\n let count = {'4': 0, '2': 0}; \n for(let i = 0; i < a.length; i++){\n let index = parseInt(a[i]);\n if(map[index]){\n map[index] += 1;\n if(map[index] % 4 === 0)\n count[4] += 1;\n\n if(map[index] % 2 === 0)\n count[2] += 1;\n }\n else\n map[index] = 1;\n }\n\n let o = parseInt(readline());\n for(let i = 0; i < o; i++){\n let x = readline().split(' ');\n if(x[0] === '+'){\n map[parseInt(x[1])] += 1;\n if(map[parseInt(x[1])] % 4 === 0)\n count[4]++;\n\n if(map[parseInt(x[1])] % 2 === 0)\n count[2]++;\n }else{\n let f1 = map[parseInt(x[1])] % 4 === 0;\n let f2 = map[parseInt(x[1])] % 2 === 0;\n map[parseInt(x[1])] -= 1;\n if(f1 && map[parseInt(x[1])] % 4 !== 0)\n count[4]--;\n\n if(f2 && map[parseInt(x[1])] % 2 !== 0)\n count[2]--;\n }\n\n if(count[4] >= 2){\n console.log('yes');\n }else if(count[4] >= 1 && count[2]-(2*count[4]) >= 2){\n console.log('yes');\n }else{\n console.log('no');\n }\n }\n}"}], "src_uid": "d14bad9abf2a27ba57c80851405a360b"} {"nl": {"description": "Ela loves reading a lot, just like her new co-workers in DTL! On her first day after becoming an engineer in DTL, she is challenged by a co-worker to sort a heap of books into different compartments on the shelf.$$$n$$$ books must be split into $$$k$$$ compartments on the bookshelf ($$$n$$$ is divisible by $$$k$$$). Each book is represented by a lowercase Latin letter from 'a' to 'y' inclusively, which is the beginning letter in the title of the book.Ela must stack exactly $$$\\frac{n}{k}$$$ books in each compartment. After the books are stacked, for each compartment indexed from $$$1$$$ to $$$k$$$, she takes the minimum excluded (MEX) letter of the multiset of letters formed by letters representing all books in that compartment, then combines the resulting letters into a string. The first letter of the resulting string is the MEX letter of the multiset of letters formed by the first compartment, the second letter of the resulting string is the MEX letter of the multiset of letters formed by the second compartment, ... and so on. Please note, under the constraint of this problem, MEX letter can always be determined for any multiset found in this problem because 'z' is not used.What is the lexicographically greatest resulting string possible that Ela can create?A string $$$a$$$ is lexicographically greater than a string $$$b$$$ if and only if one of the following holds: $$$b$$$ is a prefix of $$$a$$$, but $$$b \\ne a$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears later in the alphabet than the corresponding letter in $$$b$$$. The minimum excluded (MEX) letter of a multiset of letters is the letter that appears earliest in the alphabet and is not contained in the multiset. For example, if a multiset of letters contains $$$7$$$ letters 'b', 'a', 'b', 'c', 'e', 'c', 'f' respectively, then the MEX letter of this compartment is 'd', because 'd' is not included in the multiset, and all letters comes before 'd' in the alphabet, namely 'a', 'b' and 'c', are included in the multiset.", "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 n \\le 200$$$; $$$1 \\le k \\le n$$$). It is guaranteed that $$$n$$$ is divisible by $$$k$$$. The second line of each test case contains a string of $$$n$$$ lowercase Latin letters from 'a' to 'y' inclusively. Each letter represents the starting letter of the title of a book in the initial heap. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.", "output_spec": "For each test case, output a string of $$$k$$$ letters which is the most optimal string that Ela can find.", "sample_inputs": ["5\n\n12 3\n\ncabccadabaac\n\n12 6\n\ncabccadabaac\n\n12 12\n\ncabccadabaac\n\n25 1\n\nabcdefghijklmnopqrstuvwxy\n\n10 5\n\nbcdxedbcfg"], "sample_outputs": ["edb\nccbbba\nbbbbbaaaaaaa\nz\naaaaa"], "notes": "NoteIn the first test case, the books can be divided into $$$3$$$ compartments as below: the first compartment contains the books with indices $$$1, 2, 3, 7$$$: $$$multiset_1 = \\{$$$'c', 'a', 'b', 'd'$$$\\}$$$ $$$\\rightarrow$$$ $$$MEX(multiset_1) =$$$ 'e' the second compartment contains the books with indices $$$4, 5, 6, 9$$$ : $$$multiset_2 = \\{$$$'c', 'c', 'a', 'b'$$$\\}$$$ $$$\\rightarrow$$$ $$$MEX(multiset_2) =$$$ 'd' the third compartment contains the remaining books $$$8, 10, 11, 12$$$ : $$$multiset_3 = \\{$$$ 'a', 'a', 'a', 'c'$$$\\}$$$ $$$\\rightarrow$$$ $$$MEX(multiset_3) =$$$ 'b' Therefore, the answer is 'edb'. It can be proven that there is no way that Ela can arrange the books so that it results in a lexicographically greater string. "}, "positive_code": [{"source_code": "var readline = require('readline');\r\nvar inputString = [], currentLine = 0;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nvar rl = readline.createInterface(process.stdin);\r\nrl.on('line', line => { inputString.push(line) });\r\nprocess.stdin.on('end', () => { main() });\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const t = +readLine();\r\n for(let i = 0; i < t; i++){\r\n const n_k = readLine().split(' ').map(p => +p);\r\n const str = readLine();\r\n let result = myFunc(n_k[0], n_k[1], str);\r\n console.log(result);\r\n }\r\n}\r\n\r\nfunction myFunc(n, k, s){\r\n let sub = n/k;\r\n let map = [];\r\n const alfabeto = 'abcdefghijklmnopqrstuvwxyz';\r\n let resp = '';\r\n\r\n function _num(s){\r\n return s.charCodeAt(0)-97;\r\n }\r\n\r\n for(let i = 0; i < n; i++){\r\n if(map[_num(s[i])] == undefined) map[_num(s[i])] = 1;\r\n else map[_num(s[i])]++;\r\n }\r\n \r\n for(let j = 0; j < k; j++){\r\n for(let i = 0; i < sub; i++){\r\n if(map[i]){\r\n map[i]--;\r\n if(i == sub-1) resp += alfabeto[sub];\r\n } \r\n else{\r\n resp+= alfabeto[i];\r\n break;\r\n }\r\n \r\n }\r\n }\r\n return resp;\r\n\r\n}\r\n\r\n\r\n"}, {"source_code": "function solve() {\r\n var letters = initValues();\r\n var [n, k] = readArray(Number);\r\n var s = read();\r\n var lettersCounter = new Map();\r\n letters.forEach((letter) => lettersCounter.set(letter, 0));\r\n for (var i = 0; i < n; i++) {\r\n lettersCounter.set(s[i], lettersCounter.get(s[i]) + 1);\r\n }\r\n const booksCounter = n / k;\r\n var ans = '';\r\n for (var i = 0; i < k; i++) {\r\n var MEXIndex = 0;\r\n for (MEXIndex = 0; MEXIndex < booksCounter; MEXIndex++) {\r\n var letter = letters[MEXIndex];\r\n if (lettersCounter.get(letter) === 0) {\r\n break;\r\n }\r\n lettersCounter.set(letter, lettersCounter.get(letter) - 1);\r\n }\r\n ans += letters[MEXIndex];\r\n }\r\n write(ans);\r\n}\r\n\r\nvar initialValues;\r\nfunction initValues() {\r\n if (initialValues) {\r\n return initialValues;\r\n }\r\n var letters = [];\r\n var aCode = 'a'.charCodeAt(0);\r\n var zCode = 'z'.charCodeAt(0);\r\n for (var i = aCode; i <= zCode; i++) {\r\n letters.push(String.fromCharCode(i));\r\n }\r\n initialValues = letters;\r\n return letters;\r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX;\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n ANS = '';\r\n MEMORY_INDEX = 0;\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n k = rn(),\r\n s = read();\r\n const chs = s.split('').sort((a, b) => a === b ? 0 : a < b ? -1 : 1);\r\n const res = [];\r\n const vis = new Array(n);\r\n for (let i = 0; i < k; i++) {\r\n let cnt = 0;\r\n let pre = 96;\r\n for (let j = 0; j < n && cnt < n / k; j++) {\r\n const num = chs[j].charCodeAt(0);\r\n if (vis[j] || num === pre) continue;\r\n vis[j] = 1;\r\n cnt++;\r\n if (num === pre + 1) {\r\n pre = num;\r\n } else {\r\n if (res[i] === undefined) res[i] = pre + 1;\r\n }\r\n }\r\n if (res[i] === undefined) res[i] = pre + 1;\r\n }\r\n return res.map(num => String.fromCharCode(num)).join('');\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "9c86925036cd1f83273bc21e2ea3e5c8"} {"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$$$) — 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 buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n // console.log(line);\r\n for(let i=1;i<=2*t;i+=2)\r\n {\r\n let s=line[i];\r\n let c=line[i+1];\r\n // console.log(s.length,c.length);\r\n let flag=false;\r\n if(s.length%2==1)\r\n {\r\n for(let j=0;j {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Common Template Ends //\r\n\r\nconst isOdd = (x) => { return x & 1 }\r\nconst isEven = (x) => { return !(x & 1) }\r\n\r\nconst getMiddle = s => s.substr(s.length - 1 >>> 1, (~s.length & 1) + 1)\r\n\r\nconst findAllIndicesOfChar = (str, char) => {\r\n str = str.split('')\r\n let indices = [];\r\n for (let i = 0; i < str.length; i++) {\r\n if (str[i] === char) indices.push(i);\r\n }\r\n return indices\r\n}\r\n\r\nconst getResult = ( str, target ) => {\r\n \r\n let len = str.length\r\n\r\n let validLen = []\r\n for(let i = 5; i <= len; i+= 4) validLen.push(i)\r\n \r\n if( len === 1 ) return str === target ? 'YES' : 'NO'\r\n \r\n let begin = str.charAt(0)\r\n let end = str.charAt(str.length-1)\r\n let midchar = getMiddle(str)\r\n\r\n if( begin === target || end === target ) return 'YES'\r\n // if( midchar === target ){\r\n // return validLen.includes(len) ? 'YES' : 'NO' \r\n // }\r\n \r\n let indices = findAllIndicesOfChar( str, target )\r\n\r\n for(let i = 0; i < indices.length; i++){\r\n if( isEven(indices[i]) ) {\r\n return 'YES'\r\n }\r\n }\r\n\r\n return 'NO'\r\n}\r\n\r\nfunction main() {\r\n let testcases = parseInt( readline() )\r\n while( testcases-- ){\r\n \r\n let str = readline()\r\n let target = readline()\r\n console.log( getResult( str, target ) )\r\n }\r\n}\r\n//*/"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var t = lines[0];\n\tvar k = 0;\n\tfor(i = 1; i <= t * 2; i++){\n\t if(i % 2 == 1){\n\t \t k = lines[i].split('');\n\t }else{\n\t var e = lines[i];\n\t var a = false;\n\t for(j = 0; j < k.length; j++){\n\t if(k[j] == e){\n\t if(j % 2 === 0){\n\t a = true;\n\t }else{\n\t continue;\n\t }\n\t }\n\t }\n\t if(a){\n\t console.log('YES'); \n\t }else{\n\t console.log('NO');\n\t }\n\t }\n\t}\n});"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet s = nl.line().split('').map((e,i) => (i%2 == 0)?e:'').join('');\n\t\tlet c = nl.line();\n\t\tans.push(s.search(c) != -1);\n\t\t\n\t\t\n\t}\n\tconsole.log(ans.map(e => e?\"YES\":\"NO\").join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let s = readline();\r\n let c = readline();\r\n\r\n let indexes = [];\r\n for (let i = 0; i < s.length; i++) {\r\n if (s[i] === c) indexes.push(i);\r\n }\r\n\r\n let no = true;\r\n for (let idx = 0; idx < indexes.length; idx++) {\r\n let i = indexes[idx];\r\n let rem = s.length - 1;\r\n if (i % 2 === 0 && rem % 2 === 0) {\r\n no = false;\r\n continue;\r\n }\r\n }\r\n\r\n output(no ? 'NO' : 'YES');\r\n }\r\n}\r\n"}, {"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n \nmodule.exports = E;\n \nconst ra = ()=>readline().split(' ').map(a=>+a)\n \nconst EPS = 1e-6;\n \nconst calc = (s, c)=>{\n for (let i=0; i {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2 === 1) {\n str = d;\n c++;\n return;\n }\n\n let ans = \"NO\";\n for (let i = 0; i < str.length; i++) {\n if (str[i] === d && i % 2 === 0) {\n ans = \"YES\";\n }\n }\n\n console.log(ans);\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n\tvar t = lines[0];\n\tvar k = 0;\n\tfor(i = 1; i <= t * 2; i++){\n\t if(i % 2 == 1){\n\t \t k = lines[i].split('');\n\t }else{\n\t var e = lines[i];\n\t var a = false;\n\t for(j = 0; j < k.length; j++){\n\t if(k[j] == e){\n\t if(j % 2 === 0){\n\t a = true;\n\t }else{\n\t continue;\n\t }\n\t }\n\t }\n\t if(a){\n\t console.log('YES'); \n\t }else{\n\t console.log('NO');\n\t }\n\t }\n\t}\n});"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nlet t = -1;\r\nlet i = 0;\r\n\r\nlet input = [];\r\n\r\nfunction check(str1, c) {\r\n for (let i = 2; i < str1.length - 2; ++i) {\r\n if ((str1[i] === c) && (i % 2 === 0) && ((str1.length - i) % 2 !== 0)) {\r\n return true;\r\n }\r\n }\r\n\r\n if ((str1[str1.length - 1] === c) || (str1[0] === c)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}\r\n\r\nrl.on('line', (line) => {\r\n if (t === -1) {\r\n t = parseInt(line);\r\n } else {\r\n ++i;\r\n\r\n input.push(line);\r\n\r\n if (i === 2 * t) {\r\n rl.close();\r\n }\r\n }\r\n}).on('close', () => {\r\n for (let i = 0; i < input.length; i += 2) {\r\n if (check(input[i], input[i + 1])) {\r\n process.stdout.write(\"YES\\n\");\r\n } else {\r\n process.stdout.write(\"NO\\n\");\r\n }\r\n }\r\n\r\n});"}, {"source_code": "var readline = require('readline');\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nlet ls = [];\r\n\r\nfunction solve(){\r\n let i = 1;\r\n while (i < ls.length){\r\n const str = ls[i++];\r\n const c = ls[i++];\r\n let found = false;\r\n for (let j = 0; j < str.length; j++){\r\n if (str[j] == c && j % 2 == 0){\r\n found = true;\r\n break;\r\n }\r\n }\r\n console.log(found ? 'YES' : 'NO');\r\n }\r\n}\r\n\r\nrl.on('line', (l) => ls.push(l));\r\nrl.on('close', () => solve());"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n solve();\r\n }\r\n}\r\nfunction solve() {\r\n let str = readLine();\r\n const c = readLine();\r\n for (let i = 0; i < str.length; i++) {\r\n if (i % 2 == 0 && str.charAt(i) === c) {\r\n console.log(\"YES\");\r\n return;\r\n }\r\n }\r\n console.log(\"NO\");\r\n}\r\n"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const str = lines[l++]\r\n const c = lines[l++]\r\n output[i] = solve(str, c) ? 'YES' : 'NO'\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(str, c) {\r\n for (let i = 0; i < str.length; i++) {\r\n if (str[i] === c && !(i & 1)) return true\r\n }\r\n return false\r\n}\r\n"}, {"source_code": "function solve() {\r\n const s = read();\r\n const c = read();\r\n for (let i = 0; i < s.length; i++) {\r\n if (s[i] === c && !(i & 1)) {\r\n write('YES');\r\n return;\r\n }\r\n }\r\n write('NO');\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction pDivCount(n) {\r\n let ans = 0;\r\n let i = 1;\r\n while(n > 1) {\r\n i++;\r\n while(n % i === 0) {\r\n ans++;\r\n n = Math.floor(n / i);\r\n }\r\n }\r\n return ans;\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (a === 0) {\r\n return b;\r\n }\r\n return gcd(b % a, a);\r\n}\r\n\r\nfunction lcm(a, b) {\r\n return Math.floor(a / gcd(a, b)) * b;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n}\r\ninit();\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar s = next();\r\n\t\tvar N = s.length;\r\n\t\tvar c = next();\r\n\t\tvar ok = false;\r\n\t\tfor(var i = 0; i < N; i += 2){\r\n\t\t\tif(s[i] == c){\r\n\t\t\t\tok = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout((ok) ? \"YES\" : \"NO\");\r\n\t}\r\n}\r\n"}, {"source_code": "T = readline ()\r\nwhile(T--){\r\n \r\n s = readline().split('')\r\n c = readline()\r\n res = 'NO'\r\n\r\n for(i=0; i< s.length; i++){\r\n if(s[i] ===c){\r\n if(i % 2 == 0 && (s.length - i) %2 != 0){\r\n res = 'YES'\r\n break\r\n }\r\n }\r\n }\r\n\r\n print(res)\r\n}\r\n"}, {"source_code": "var t = readline();\r\nfor (var i = 0; i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Common Template Ends //\r\n\r\nconst isOdd = (x) => { return x & 1 }\r\nconst isEven = (x) => { return !(x & 1) }\r\n\r\nconst getMiddle = s => s.substr(s.length - 1 >>> 1, (~s.length & 1) + 1)\r\n\r\nconst findAllIndicesOfChar = (str, char) => {\r\n str = str.split('')\r\n let indices = [];\r\n for (let i = 0; i < str.length; i++) {\r\n if (str[i] === char) indices.push(i);\r\n }\r\n return indices\r\n}\r\n\r\nconst getResult = ( str, target ) => {\r\n \r\n let len = str.length\r\n\r\n let validLen = []\r\n for(let i = 5; i <= len; i+= 4) validLen.push(i)\r\n \r\n if( len === 1 ) return str === target ? 'YES' : 'NO'\r\n \r\n let begin = str.charAt(0)\r\n let end = str.charAt(str.length-1)\r\n let midchar = getMiddle(str)\r\n\r\n if( begin === target || end === target ) return 'YES'\r\n if( midchar === target ){\r\n return validLen.includes(len) ? 'YES' : 'NO' \r\n }\r\n \r\n let indices = findAllIndicesOfChar( str, target )\r\n\r\n for(let i = 0; i < indices.length; i++){\r\n if( isEven(indices[i]) ) {\r\n return 'YES'\r\n }\r\n }\r\n\r\n return 'NO'\r\n}\r\n\r\nfunction main() {\r\n let testcases = parseInt( readline() )\r\n while( testcases-- ){\r\n \r\n let str = readline()\r\n let target = readline()\r\n console.log( getResult( str, target ) )\r\n }\r\n}\r\n//*/"}, {"source_code": "/*\r\n** Template\r\n*/\r\n\r\n// Common Template Starts //\r\n//*\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Common Template Ends //\r\n\r\nconst isOdd = (x) => { return x & 1 }\r\nconst isEven = (x) => { return !(x & 1) }\r\n\r\nconst getMiddle = s => s.substr(s.length - 1 >>> 1, (~s.length & 1) + 1)\r\n\r\nconst findAllIndicesOfChar = (str, char) => {\r\n str = str.split('')\r\n let indices = [];\r\n for (let i = 0; i < str.length; i++) {\r\n if (str[i] === char) indices.push(i);\r\n }\r\n return indices\r\n}\r\n\r\nconst getResult = ( str, target ) => {\r\n \r\n let len = str.length\r\n \r\n if( len === 1 ) return str === target ? 'YES' : 'NO'\r\n \r\n let begin = str.charAt(0)\r\n let end = str.charAt(str.length-1)\r\n let midchar = getMiddle(str)\r\n\r\n if( midchar === target || begin === target || end === target ) return 'YES'\r\n \r\n let indices = findAllIndicesOfChar( str, target )\r\n\r\n for(let i = 0; i < indices.length; i++){\r\n if( isEven(indices[i]) ) {\r\n return 'YES'\r\n }\r\n }\r\n\r\n return 'NO'\r\n}\r\n\r\nfunction main() {\r\n let testcases = parseInt( readline() )\r\n while( testcases-- ){\r\n \r\n let str = readline()\r\n let target = readline()\r\n console.log( getResult( str, target ) )\r\n }\r\n}\r\n//*/"}, {"source_code": "/*\r\n** Template\r\n*/\r\n\r\n// Common Template Starts //\r\n//*\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Common Template Ends //\r\n\r\nconst getMiddle = s => s.substr(s.length - 1 >>> 1, (~s.length & 1) + 1)\r\n\r\nconst getResult = ( str, target ) => {\r\n \r\n let len = str.length\r\n \r\n if( len === 1 ) return 'NO'\r\n \r\n let midchar = getMiddle(str)\r\n \r\n return midchar === target ? 'YES' : 'NO'\r\n}\r\n\r\nfunction main() {\r\n let testcases = parseInt( readline() )\r\n while( testcases-- ){\r\n \r\n let str = readline()\r\n let target = readline()\r\n console.log( getResult( str, target ) )\r\n }\r\n}\r\n//*/"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var t = lines[0];\n\tfor(i = 1; i <= t; i++) {\n\t var a = lines[i];\n if(a < 20){\n console.log('YES');\n var ans = '';\n var b = 1;\n for(j = 0; j < a; j++){\n ans += b + ' ';\n b *= 3;\n }\n console.log(ans);\n }else{\n console.log('NO');\n }\n\t}\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var e = lines[2]\n var abc = ['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 for(j = 1; j <= n * 2; j++){\n \n if(j % 2 == 1){\n e = lines[j + 1]\n var s = 0\nvar u = false\nvar r = false\n var a = lines[j].split('').map(String)\n for(k = 0 ; k < a.length; k++){\n if(a[k] != e){\n s++\n }else {\n s++\n u = true\n if(a[a.length - 1] == e){\n r = true\n }\n break;\n }\n }\n if(s % 2 == 1 && u === true || r === true){\n console.log('YES')\n }else{\n console.log('NO')\n }\n }\n }\n}); \n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var e = lines[2]\n var s = 0\n var abc = ['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 for(j = 1; j <= n * 2; j++){\n \n if(j % 2 == 1){\n e = lines[j + 1]\n var a = lines[j].split('').map(String)\n for(k = 0 ; k < a.length; k++){\n if(a[k] != e){\n s++\n }else {\n break;\n }\n }\n if(s % 2 == 1){\n console.log('YES')\n }else{\n console.log('NO')\n }\n }\n }\n}); \n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet s = nl.line().split('').map((e,i) => (i%2 == 0)?e:'').join('');\n\t\tlet c = nl.line();\n\t\tans.push(s.search(c) != -1);\n\t\tconsole.log(s);\n\t\t\n\t\t\n\t}\n\tconsole.log(ans.map(e => e?\"YES\":\"NO\").join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet s = nl.line();\n\t\tlet c = nl.line();\n\t\tlet l = s.length;\n\t\tlet ns = s.substring(0, 1) + (l>3?s.substring(2, l-2):\"\") + s.substring(l-1);\n\t\tans.push(ns.search(c) != -1);\n\t\t\n\t\t\n\t}\n\tconsole.log(ans.map(e => e?\"YES\":\"NO\").join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet s = nl.line();\n\t\tlet c = nl.line();\n\t\tlet l = s.length;\n\t\tlet ns = s.substring(0, 1) + s.substring(2, l-2) + s.substring(l-1);\n\t\tans.push(ns.search(c) != -1);\n\t\t\n\t\t\n\t}\n\tconsole.log(ans.map(e => e?\"YES\":\"NO\").join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nmodule.exports = E;\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\n\nconst EPS = 1e-6;\n\nconst calc = (s, c)=>{\n if (s[0]==c)\n return true;\n if (s[s.length-1]==c)\n return true;\n return s.slice(2, s.length-2).includes(c)\n};\n\nfunction main() {\n let T = +readline()\n while (T--){\n let s = readline();\n let c = readline();\n print(calc(s, c) ? 'YES' : 'NO');\n }\n}\n\nE.calc = calc;"}], "src_uid": "c569b47cf80dfa98a7105e246c3c1e01"} {"nl": {"description": "To satisfy his love of matching socks, Phoenix has brought his $$$n$$$ socks ($$$n$$$ is even) to the sock store. Each of his socks has a color $$$c_i$$$ and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: recolor a sock to any color $$$c'$$$ $$$(1 \\le c' \\le n)$$$ turn a left sock into a right sock turn a right sock into a left sock The sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa. A matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make $$$n/2$$$ matching pairs? Each sock must be included in exactly one matching pair.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$l$$$, and $$$r$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$; $$$n$$$ is even; $$$0 \\le l, r \\le n$$$; $$$l+r=n$$$) — the total number of socks, and the number of left and right socks, respectively. The next line contains $$$n$$$ integers $$$c_i$$$ ($$$1 \\le c_i \\le n$$$) — the colors of the socks. The first $$$l$$$ socks are left socks, while the next $$$r$$$ socks are right socks. It is guaranteed that the sum of $$$n$$$ across all the test cases will not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print one integer — the minimum cost for Phoenix to make $$$n/2$$$ matching pairs. Each sock must be included in exactly one matching pair.", "sample_inputs": ["4\n6 3 3\n1 2 3 2 2 2\n6 2 4\n1 1 2 2 2 2\n6 5 1\n6 5 4 3 2 1\n4 0 4\n4 4 4 3"], "sample_outputs": ["2\n3\n5\n3"], "notes": "NoteIn the first test case, Phoenix can pay $$$2$$$ dollars to: recolor sock $$$1$$$ to color $$$2$$$ recolor sock $$$3$$$ to color $$$2$$$ There are now $$$3$$$ matching pairs. For example, pairs $$$(1, 4)$$$, $$$(2, 5)$$$, and $$$(3, 6)$$$ are matching.In the second test case, Phoenix can pay $$$3$$$ dollars to: turn sock $$$6$$$ from a right sock to a left sock recolor sock $$$3$$$ to color $$$1$$$ recolor sock $$$4$$$ to color $$$1$$$ There are now $$$3$$$ matching pairs. For example, pairs $$$(1, 3)$$$, $$$(2, 4)$$$, and $$$(5, 6)$$$ are matching."}, "positive_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet [n, l, r] = rna();\r\n\t\tlet c = rna();\r\n\r\n\t\tlet ar1 = Array(n + 1).fill(0);\r\n\t\tlet ar2 = Array(n + 1).fill(0);\t\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tif (i < l) \r\n\t\t\t\tar1[c[i]]++;\r\n\t\t\telse\t\r\n\t\t\t\tar2[c[i]]++;\r\n\t\t}\r\n\r\n\t\tif (r > l)\r\n\t\t\t[ar1, ar2] = [ar2, ar1];\r\n\r\n\t\tlet k = Math.abs((l - r) / 2);\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 1; i <= n; i++) {\r\n\t\t\tar1[i] = Math.max(0, ar1[i] - ar2[i]);\r\n\r\n\t\t\tconst mvs = Math.min(k, Math.floor(ar1[i] / 2));\r\n\t\t\tk -= mvs;\r\n\t\t\tar1[i] -= 2 * mvs;\r\n\r\n\t\t\tans += ar1[i] + mvs;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst MX = 2e5 + 1;\t\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet [n, l, r] = rna();\r\n\t\tlet c = rna();\r\n\r\n\t\tlet ar1 = Array(n+1).fill(0);\r\n\t\tlet ar2 = Array(n+1).fill(0);\t\r\n\t\tfor (let i = 0 ; i < n; i++) {\r\n\t\t\tif (i < l) \r\n\t\t\t\tar1[c[i]]++;\r\n\t\t\telse\t\r\n\t\t\t\tar2[c[i]]++;\r\n\t\t}\r\n\r\n\t\tif (r > l)\r\n\t\t\t[ar1, ar2] = [ar2, ar1];\r\n\t\t//console.log(ar1,ar2)\r\n\r\n\t\tlet k = Math.abs((l-r)/2);\r\n\t\tlet ans = 0;\r\n\t\t//console.log('k', k);\r\n\t\tfor (let i = 1; i <= n; i++) {\r\n\t\t\tar1[i] = Math.max(0, ar1[i] - ar2[i]);\r\n\r\n\t\t\tconst mvs = Math.min(k, Math.floor(ar1[i] / 2));\r\n\r\n\t\t\tk -= mvs;\r\n\t\t\tar1[i] = ar1[i] - 2 * mvs;\r\n\r\n\t\t\tans += ar1[i] + mvs;\r\n\t\t\t//console.log('mvs', mvs)\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}], "negative_code": [{"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nvar global = 1;\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors_s = readline();\n var colors = colors_s.split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n\n \n \n print(global === 279? `${line1} ${colors_s}`: dollars_spent);\n global++;\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nvar global = 1;\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors_s = readline();\n var colors = colors_s.split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n\n \n \n print(global === 279? line1: dollars_spent);\n global++;\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nvar global = 1;\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors_s = readline();\n var colors = colors_s.split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n\n \n \n print(global === 279? line1 + colors_s: dollars_spent);\n global++;\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nvar global = 1;\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(global === 279? '12312313': dollars_spent);\n global++;\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] >= 1)\n this.size--;\n if (this.set[value] > 1)\n this.set[value]--;\n else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] && this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= min;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++) {\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n dollars_spent += parseInt(min / 2);\n lefts -= min;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor * 2;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n var last_recolor_dif = 0;\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights - last_recolor_dif;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor;\n last_recolor_dif = recolor;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}, {"source_code": "const create_multiset = () => {\n return {\n set: [],\n cardinality: 0,\n size: 0,\n add: function(value) {\n if (this.set[value])\n this.set[value]++;\n else {\n this.set[value] = 1;\n this.cardinality++;\n }\n this.size++;\n },\n delete: function(value) {\n if (this.set[value] > 1) {\n this.set[value]--;\n this.size--;\n } else if (this.set[value]) {\n this.set[value] = undefined;\n this.cardinality--;\n this.size--;\n }\n },\n has: function(value) {\n return (this.set[value] >= 1);\n },\n getCardinality: function() {\n return this.cardinality;\n },\n getSize: function() {\n return this.size;\n },\n getCountOf: function(value) {\n return this.set[value]? this.set[value]: 0\n },\n clear: function() {\n this.set = [];\n this.size = 0;\n }\n }\n};\n\nconst t = parseInt(readline());\n\nfor (var _ = 0; _ < t; _++) {\n var line1 = readline().split(' ').map(a => parseInt(a));\n var n = line1[0];\n var lefts = line1[1];\n var rights = line1[2];\n var l_socks = create_multiset();\n var r_socks = create_multiset();\n\n var colors = readline().split(' ').map(a => parseInt(a));\n colors.slice(0, lefts).forEach(item => l_socks.add(item));\n colors.slice(lefts, n)\n .forEach(item => {\n if (l_socks.has(item))\n l_socks.delete(item);\n else\n r_socks.add(item);\n });\n \n lefts = l_socks.getSize();\n rights = r_socks.getSize();\n n = lefts + rights;\n\n if (lefts < rights) {\n var tt = lefts;\n lefts = rights;\n rights = tt;\n tt = l_socks;\n l_socks = r_socks;\n r_socks = tt;\n }\n \n var dollars_spent = 0;\n\n for (var color_index = 1; color_index <= n; color_index++){\n var d = lefts - rights;\n var lefts_this_color = l_socks.getCountOf(color_index);\n var ok_to_recolor = parseInt(lefts_this_color / 2);\n var min = Math.min(ok_to_recolor * 2, d);\n var recolor = parseInt(min / 2);\n dollars_spent += recolor;\n lefts -= recolor;\n }\n \n dollars_spent += parseInt((lefts - rights) / 2);\n dollars_spent += parseInt((lefts + rights) / 2);\n \n print(dollars_spent);\n}"}], "src_uid": "a2d4f0182456cedbe85dff97ec0f477e"} {"nl": {"description": "One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: By the pieces lay a large square wooden board. The board is divided into $$$n^2$$$ cells arranged into $$$n$$$ rows and $$$n$$$ columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$3 \\leq n \\leq 50$$$) — the size of the board. The following $$$n$$$ lines describe the board. The $$$i$$$-th line ($$$1 \\leq i \\leq n$$$) contains a single string of length $$$n$$$. Its $$$j$$$-th character ($$$1 \\leq j \\leq n$$$) is equal to \".\" if the cell in the $$$i$$$-th row and the $$$j$$$-th column is free; it is equal to \"#\" if it's occupied. You can assume that the board contains at least one free cell.", "output_spec": "Output YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["3\n#.#\n...\n#.#", "4\n##.#\n#...\n####\n##.#", "5\n#.###\n....#\n#....\n###.#\n#####", "5\n#.###\n....#\n#....\n....#\n#..##"], "sample_outputs": ["YES", "NO", "YES", "NO"], "notes": "NoteThe following sketches show the example boards and their tilings if such tilings exist: "}, "positive_code": [{"source_code": "\n(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var arr = [];\n var count = 0;\n for(var i = 0; i < n; i++) {\n arr[i] = read.arr('');\n arr[i].forEach(item => {\n if(item === '.') {\n count++;\n }\n });\n }\n\n if(count % 5 !== 0) {\n print('NO');\n return;\n }\n \n for(var i = 1; i < n - 1; i++) {\n for(var j = 1; j < n - 1; j++) {\n if(arr[i][j] === '.' && arr[i][j-1] === '.' && arr[i][j+1] === '.' && arr[i - 1][j] === '.' && arr[i+1][j] === '.') {\n arr[i][j] = '#';\n arr[i][j - 1] = '#';\n arr[i][j + 1] = '#';\n arr[i - 1][j] = '#';\n arr[i + 1][j] = '#';\n }\n }\n }\n\n var count = 0;\n for(var i = 0; i < n; i++) {\n arr[i].forEach(item => {\n if(item === '.') {\n count++;\n }\n });\n }\n if(count) {\n print('NO');\n }\n else {\n print('YES');\n }\n}());\n\n"}, {"source_code": "var n = parseInt(readline());\nvar board = new Array(n).fill('');\nfor(var i=0;i (c==='#' ? false:true))\n}\nvar countToFill = 0;\nboard.forEach((b, i) => {\n board[i].forEach((cell, j) => {\n countToFill+= cell? 1:0;\n })\n});\n\n\nvar canFit = (x, y) => (\n x-1 >= 0 &&\n y-1>=0 &&\n x+1 (\n canFit(x, y) ||\n canFit(x+1, y) ||\n canFit(x-1, y) ||\n canFit(x, y-1) ||\n canFit(x, y+1)\n);\n\nvar res = (countToFill===0) || (countToFill%5 === 0);\n// board.forEach((b, i) => ( board[i].forEach((c, j) => {\n// if (board[i][j]) {\n// res = res && canAnyFit(i,j)\n// }\n// } )));\n// print(res ? 'YES':'NO')\n\nvar fill = (x, y, c) => (\n board[x][y] =\n board[x+1][y] =\n board[x-1][y] = \n board[x][y+1] = \n board[x][y-1] = c //#\n);\nvar fit = (x, y) => (fill(x, y, false)) //#\nvar unfit = (x, y) => (fill(x, y, true)) //.\n\n\n// var q = [{\n// pos: 0,\n// count: countToFill\n// }];\n// while(q.length>0) {\n// var cur = q.shift();\n// var x = Math.floor(cur.pos/board.length);\n// var y = cur.pos%board.length;\n \n// print('pos', cur.pos)\n \n// var count = cur.count;\n// if (count === 0) {\n// print('YES')\n// break;\n// }\n// if (canFit(x, y-1)) {\n// fit(x, y-1);\n// count-=5;\n// } else if (canFit(x-1, y)) {\n// fit(x-1, y);\n// count-=5;\n// } else if (canFit(x, y)) {\n// fit(x, y);\n// count-=5;\n// } else if (canFit(x+1, y)) {\n// fit(x+1, y);\n// count-=5;\n// } else if (canFit(x, y+1)) {\n// fit(x, y+1);\n// count-=5;\n// }\n// q.push({\n// pos: cur.pos+1,\n// count: count\n// })\n// }\n\nvar vis = {}, memo = {};\nfunction sol(pos, count) {\n \n var x = Math.floor(pos/board.length);\n var y = pos%board.length;\n var v = x*board.length*board.length + y*board.length + count;\n if (count === 0) {\n //print('YES');\n return memo[v]=true;\n }\n if (pos>board.length*board.length) {\n \n return memo[v] = false;\n }\n \n //if (vis[v]) return false;\n vis[v] = true;\n \n if (canFit(x, y)) {\n \n// print('fitting in ', x, y);\n \n fit(x, y);\n if(sol(pos+1, count-5)) {\n return memo[v]=true;\n }\n unfit(x, y);\n } else if(sol(pos+1, count)) {\n return memo[v]=true;\n }\n return memo[v]=false;\n}\n\nif (!res) {\n print('NO')\n} else {\n print(sol(0,countToFill) ? 'YES':'NO')\n}\n"}, {"source_code": "var lines = parseInt(readline());\n\nvar matrix = []\nfor (var i = 0; i < lines; i++){ \n matrix.push(readline().split(''));\n}\n\n// var matrix = [\n// ['#', '#', '.', '#'],\n// ['#', '.', '.', '.'],\n// ['#', '#', '.', '#'],\n// ['#', '#', '#', '#']]\n\nfunction isFull() {\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix.length; j++) {\n if (matrix[i][j] === '.')\n return false;\n }\n }\n return true;\n}\n\nfunction checkInsertion(row, col) {\n return (\n matrix[row][col] === '.' &&\n matrix[row+1][col] === '.' &&\n matrix[row][col+1] === '.' &&\n matrix[row][col-1] === '.' &&\n matrix[row-1][col] === '.'\n );\n}\n\nfunction insert(row, col) {\n matrix[row][col] = '#';\n matrix[row+1][col] = '#';\n matrix[row][col+1] = '#';\n matrix[row][col-1] = '#';\n matrix[row-1][col] = '#';\n}\n\nfunction foo() {\n for (var row = 1; row < matrix.length - 1; row++) {\n for (var col = 1; col < matrix.length - 1; col++) {\n if (checkInsertion(row, col)) {\n insert(row, col);\n if (isFull())\n return write('YES')\n }\n }\n }\n\n write('NO')\n}\n\nfoo();\n"}], "negative_code": [], "src_uid": "cc1feee94617c0cba1c528a0cb3952a8"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ positive integers. Let $$$\\text{LIS}(a)$$$ denote the length of longest strictly increasing subsequence of $$$a$$$. For example, $$$\\text{LIS}([2, \\underline{1}, 1, \\underline{3}])$$$ = $$$2$$$. $$$\\text{LIS}([\\underline{3}, \\underline{5}, \\underline{10}, \\underline{20}])$$$ = $$$4$$$. $$$\\text{LIS}([3, \\underline{1}, \\underline{2}, \\underline{4}])$$$ = $$$3$$$. We define array $$$a'$$$ as the array obtained after reversing the array $$$a$$$ i.e. $$$a' = [a_n, a_{n-1}, \\ldots , a_1]$$$.The beauty of array $$$a$$$ is defined as $$$min(\\text{LIS}(a),\\text{LIS}(a'))$$$.Your task is to determine the maximum possible beauty of the array $$$a$$$ if you can rearrange the array $$$a$$$ arbitrarily.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10^4)$$$  — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \\leq n \\leq 2\\cdot 10^5)$$$  — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \\ldots ,a_n$$$ $$$(1 \\leq a_i \\leq 10^9)$$$  — the 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 a single integer  — the maximum possible beauty of $$$a$$$ after rearranging its elements arbitrarily.", "sample_inputs": ["3\n\n3\n\n6 6 6\n\n6\n\n2 5 4 5 2 4\n\n4\n\n1 3 2 2"], "sample_outputs": ["1\n3\n2"], "notes": "NoteIn the first test case, $$$a$$$ = $$$[6, 6, 6]$$$ and $$$a'$$$ = $$$[6, 6, 6]$$$. $$$\\text{LIS}(a) = \\text{LIS}(a')$$$ = $$$1$$$. Hence the beauty is $$$min(1, 1) = 1$$$.In the second test case, $$$a$$$ can be rearranged to $$$[2, 5, 4, 5, 4, 2]$$$. Then $$$a'$$$ = $$$[2, 4, 5, 4, 5, 2]$$$. $$$\\text{LIS}(a) = \\text{LIS}(a') = 3$$$. Hence the beauty is $$$3$$$ and it can be shown that this is the maximum possible beauty.In the third test case, $$$a$$$ can be rearranged to $$$[1, 2, 3, 2]$$$. Then $$$a'$$$ = $$$[2, 3, 2, 1]$$$. $$$\\text{LIS}(a) = 3$$$, $$$\\text{LIS}(a') = 2$$$. Hence the beauty is $$$min(3, 2) = 2$$$ and it can be shown that $$$2$$$ is the maximum possible beauty."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n const map={}\r\n let res=0\r\n for(let num of a){\r\n if(map[num]===2)continue\r\n map[num]=(map[num]||0)+1\r\n res++\r\n }\r\n return (res&1)?(res>>1)+1:(res>>1)\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n a.sort((a, b) => a - b);\r\n let l = 1,\r\n lv = a[0],\r\n r = 1,\r\n rv = a[0];\r\n for (let i = 1; i < n; i++) {\r\n if (a[i] === lv) {\r\n if (a[i] === rv) continue;\r\n r++;\r\n rv = a[i];\r\n } else {\r\n if (a[i] === rv) {\r\n l++;\r\n lv = a[i];\r\n } else {\r\n if (l < r) {\r\n l++;\r\n lv = a[i];\r\n } else {\r\n r++;\r\n rv = a[i];\r\n }\r\n }\r\n }\r\n }\r\n return Math.min(l, r);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n a.sort((a, b) => b - a);\r\n let res = [];\r\n let l = 0,\r\n r = n - 1,\r\n i = 0;\r\n while (i < n) {\r\n res[l++] = a[i++];\r\n if (r > l) res[r--] = a[i++];\r\n }\r\n function lengthOfLIS(nums) {\r\n const dp = [nums[0]];\r\n for (const num of nums) {\r\n let [left, right] = [0, dp.length];\r\n while (left < right) {\r\n const mid = Math.floor(left / 2 + right / 2);\r\n if (dp[mid] < num) left = mid + 1;else right = mid;\r\n }\r\n dp[right] = num;\r\n }\r\n return dp.length;\r\n }\r\n return Math.min(lengthOfLIS(res), lengthOfLIS(res.reverse()));\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "src_uid": "68b7567880b9980d793dae2bce690356"} {"nl": {"description": "Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store  — \"PriceFixed\". Here are some rules of that store: The store has an infinite number of items of every product. All products have the same price: $$$2$$$ rubles per item. For every product $$$i$$$ there is a discount for experienced buyers: if you buy $$$b_i$$$ items of products (of any type, not necessarily type $$$i$$$), then for all future purchases of the $$$i$$$-th product there is a $$$50\\%$$$ discount (so you can buy an item of the $$$i$$$-th product for $$$1$$$ ruble!). Lena needs to buy $$$n$$$ products: she must purchase at least $$$a_i$$$ items of the $$$i$$$-th product. Help Lena to calculate the minimum amount of money she needs to spend if she optimally chooses the order of purchasing. Note that if she wants, she can buy more items of some product than needed.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100\\,000$$$) — the number of products. Each of next $$$n$$$ lines contains a product description. Each description consists of two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i \\leq 10^{14}$$$, $$$1 \\leq b_i \\leq 10^{14}$$$) — the required number of the $$$i$$$-th product and how many products you need to buy to get the discount on the $$$i$$$-th product. The sum of all $$$a_i$$$ does not exceed $$$10^{14}$$$.", "output_spec": "Output the minimum sum that Lena needs to make all purchases. ", "sample_inputs": ["3\n3 4\n1 3\n1 5", "5\n2 7\n2 8\n1 2\n2 4\n1 8"], "sample_outputs": ["8", "12"], "notes": "NoteIn the first example, Lena can purchase the products in the following way: one item of product $$$3$$$ for $$$2$$$ rubles, one item of product $$$1$$$ for $$$2$$$ rubles, one item of product $$$1$$$ for $$$2$$$ rubles, one item of product $$$2$$$ for $$$1$$$ ruble (she can use the discount because $$$3$$$ items are already purchased), one item of product $$$1$$$ for $$$1$$$ ruble (she can use the discount because $$$4$$$ items are already purchased). In total, she spends $$$8$$$ rubles. It can be proved that it is impossible to spend less.In the second example Lena can purchase the products in the following way: one item of product $$$1$$$ for $$$2$$$ rubles, two items of product $$$2$$$ for $$$2$$$ rubles for each, one item of product $$$5$$$ for $$$2$$$ rubles, one item of product $$$3$$$ for $$$1$$$ ruble, two items of product $$$4$$$ for $$$1$$$ ruble for each, one item of product $$$1$$$ for $$$1$$$ ruble. In total, she spends $$$12$$$ rubles."}, "positive_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tconst n = rn();\r\n\tconst p = [];\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tp[i] = rna();\r\n\t}\r\n\r\n\tp.sort((x, y) => x[1] - y[1]);\r\n\r\n\tlet total = 0;\r\n\tfor (const [a, b] of p) {\r\n\t\ttotal += a;\r\n\t}\r\n\r\n\tconst regbuy = items => buy(items, 2);\r\n\tconst disbuy = items => buy(items, 1);\r\n\tconst buy = (items, price) => {\r\n\t\tbought += items;\r\n\t\trem -= items;\r\n\t\tspent += items * price;\r\n\t}\r\n\r\n\tlet bought = 0, rem = total, spent = 0, i = 0;\r\n\twhile (rem) {\r\n\t\tlet [must, should] = p[i++];\r\n\t\tshould = Math.max(0, should - bought);\r\n\t\tif (should) {\r\n\t\t\tregbuy(Math.min(rem, should));\r\n\t\t}\r\n\t\tdisbuy(Math.min(rem, must));\r\n\t}\r\n\r\n\tconst ans = spent;\r\n\tconsole.log(ans);\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tconst n = rn();\r\n\tconst p = [];\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tp[i] = rna();\r\n\t}\r\n\r\n\tp.sort((x, y) => x[1] - y[1]);\r\n\r\n\tlet total = 0;\r\n\tfor (const [a, b] of p) {\r\n\t\ttotal += a;\r\n\t}\r\n\r\n\tconst regbuy = items => buy(items, 2);\r\n\tconst disbuy = items => buy(items, 1);\r\n\tconst buy = (items, price) => {\r\n\t\tbought += items;\r\n\t\trem -= items;\r\n\t\tspent += items * price;\r\n\t}\r\n\r\n\tlet bought = 0, rem = total, spent = 0, i = 0;\r\n\twhile (rem) {\r\n\t\tlet [cur, fordisc] = p[i++];\r\n\t\tfordisc = Math.max(0, fordisc - bought);\r\n\r\n\t\tif (fordisc == 0) {\r\n\t\t\tdisbuy(Math.min(rem, cur));\r\n\t\t} else {\r\n\t\t\tregbuy(Math.min(rem, fordisc));\r\n\t\t\tdisbuy(Math.min(rem, cur));\r\n\t\t}\r\n\t}\r\n\r\n\tconst ans = spent;\r\n\tconsole.log(ans);\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tconst n = rn();\r\n\tconst p = [];\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tp[i] = rna();\r\n\t}\r\n\r\n\tp.sort((x, y) => x[1] - y[1]);\r\n\r\n\tlet total = 0;\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\ttotal += p[i][0];\r\n\t}\r\n\r\n\tlet bought = 0, rem = total;\r\n\tlet spent = 0;\r\n\tlet i = 0;\r\n\twhile (rem) {\r\n\t\t//console.log(p[i], {rem, bought, spent})\r\n\t\tconst [need, minr] = p[i++];\r\n\t\tconst reqfrd = Math.max(minr - bought, 0);\r\n\r\n\t\tif (reqfrd == 0) {\r\n\t\t\tconst discbuy = Math.min(rem, need);\r\n\t\t\tbuy(discbuy, 1);\r\n\t\t} else {\r\n\t\t\tconst regbuy = Math.min(rem, reqfrd);\r\n\t\t\tbuy(regbuy, 2);\r\n\r\n\t\t\tconst discbuy = Math.min(rem, need);\r\n\t\t\tbuy(discbuy, 1);\r\n\t\t\t//console.log({i, regbuy, discbuy})\r\n\t\t}\r\n\t}\r\n\r\n\tfunction buy (items, price) {\r\n\t\tbought += items;\r\n\t\trem -= items;\r\n\t\tspent += items * price;\r\n\t}\r\n\r\n\tconst ans = spent;\r\n\tconsole.log(ans);\r\n}\r\n\r\n"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var l = 0;\n var n = +lines[l++];\n var arr = lines.slice(l, l + n).map(str => str.split(' ').map(Number));\n console.log(solve(n, arr))\n});\n\nfunction solve(n, arr) {\n arr.sort((a, b) => a[1] - b[1])\n\n let i = 0\n let j = arr.length - 1\n let all = 0\n let pay = 0\n while (i <= j) {\n const [total, limit] = arr[i]\n while (all < limit && j > i) {\n const able = arr[j][0]\n let cost\n if (all + able < limit) {\n cost = able\n arr[j][0] -= cost\n j--\n } else {\n cost = limit - all\n arr[j][0] -= cost\n }\n all += cost\n pay += 2 * cost\n }\n// console.log(arr, pay, all)\n if (all < limit) {\n const f = Math.min(total, limit - all)\n pay += f * 2\n all += f\n arr[i][0] -= f\n break\n } else {\n pay += total\n all += total\n arr[i][0] = 0\n i++\n }\n }\n if (i >= n) return pay\n // i == j\n if (all >= arr[i][1]) {\n pay += arr[i][0]\n } else {\n pay += 2 * arr[i][0]\n }\n return pay\n}\n"}, {"source_code": "\"use strict\";\r\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}));\r\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n});\r\nvar __importStar = (this && this.__importStar) || function (mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst fs = __importStar(require(\"fs\"));\r\n// import * as readline from 'readline'\r\n// const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\r\n// const ask = (query: string) => new Promise((resolve) => rl.question(query, resolve))\r\n// // Don't forget `rl.close()`.\r\nconst INT = Math.floor;\r\nArray.prototype.last = function () {\r\n return this.length === 0 ? undefined : this[this.length - 1];\r\n};\r\nArray.prototype.isEmpty = function () {\r\n return this.length === 0;\r\n};\r\nconst less = (a, b) => (a == b ? 0 : a < b ? -1 : 1);\r\nconst greater = (a, b) => (a == b ? 0 : a < b ? 1 : -1);\r\nconst bigIntMax = (...args) => args.reduce((m, e) => (e > m ? e : m));\r\nconst bigIntMin = (...args) => args.reduce((m, e) => (e < m ? e : m));\r\nconst bigIntAbs = (arg) => (arg < 0 ? -arg : arg);\r\nfunction read_stdin() {\r\n return fs.readFileSync(process.env.NODE_ENV === 'debug' ? stdin : process.stdin.fd, 'utf8');\r\n}\r\nclass Input {\r\n constructor(str) {\r\n this.index = 0;\r\n this.inputs = (str ? str : read_stdin()).split(/\\s+/);\r\n }\r\n number() {\r\n return Number(this.inputs[this.index++]);\r\n }\r\n numbers(n) {\r\n return this.inputs.slice(this.index, (this.index += n)).map(Number);\r\n }\r\n bigint() {\r\n return BigInt(this.inputs[this.index++]);\r\n }\r\n bigints(n) {\r\n return this.inputs.slice(this.index, (this.index += n)).map(BigInt);\r\n }\r\n word() {\r\n return this.inputs[this.index++];\r\n }\r\n words(n) {\r\n return this.inputs.slice(this.index, (this.index += n));\r\n }\r\n}\r\nfunction array(len, init) {\r\n return Array(len).fill(init);\r\n}\r\nfunction array2(h, w, init) {\r\n return array(h, 0).map(() => array(w, init));\r\n}\r\nfunction main() {\r\n const input = new Input();\r\n const N = input.number();\r\n const products = Array(N);\r\n for (let i = 0; i < N; i++) {\r\n const a = input.number();\r\n const b = input.number();\r\n products[i] = { a, b };\r\n }\r\n products.sort((x, y) => x.b - y.b);\r\n let head = 0;\r\n let tail = N - 1;\r\n let sum = 0;\r\n let count = 0;\r\n while (head <= tail) {\r\n // console.log({ head, tail })\r\n const p_head = products[head];\r\n let c = p_head.b - count;\r\n // console.log({ p_head, count, c })\r\n if (c > 0) {\r\n while (head <= tail) {\r\n // console.log({ head, tail, c })\r\n const p_tail = products[tail];\r\n if (p_tail.a > c) {\r\n p_tail.a -= c;\r\n count += c;\r\n sum += 2 * c;\r\n break;\r\n }\r\n else if (p_tail.a === c) {\r\n p_tail.a -= c;\r\n count += c;\r\n sum += 2 * c;\r\n tail--;\r\n break;\r\n }\r\n else {\r\n c -= p_tail.a;\r\n count += p_tail.a;\r\n sum += 2 * p_tail.a;\r\n p_tail.a = 0;\r\n tail--;\r\n }\r\n }\r\n }\r\n // console.log({ p_head })\r\n if (p_head.a > 0) {\r\n if (p_head.b <= count) {\r\n sum += p_head.a;\r\n }\r\n else {\r\n sum += 2 * p_head.a;\r\n }\r\n count += p_head.a;\r\n }\r\n head++;\r\n }\r\n console.log(sum);\r\n}\r\nmain();\r\n//# sourceMappingURL=aoj.js.map"}, {"source_code": "function gcd(x, y) {\r\n if (y === 0) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction div(a, b) {\r\n return Math.floor(a / b);\r\n}\r\n\r\nfunction solve() {\r\n var n = Number(read());\r\n var arr = [];\r\n for (var i = 0; i < n; i++) {\r\n arr.push(readArray(BigInt));\r\n }\r\n arr.sort((a, b) => {\r\n if (a[1] > b[1]) {\r\n return 1;\r\n }\r\n if (a[1] < b[1]) {\r\n return -1;\r\n }\r\n return 0;\r\n });\r\n var counter = 0n;\r\n var ans = 0n;\r\n var l = 0;\r\n var r = n - 1;\r\n while (l <= r) {\r\n var la = arr[l][0];\r\n var lb = arr[l][1];\r\n var ra = arr[r][0];\r\n\r\n if (counter >= lb) {\r\n ans += la;\r\n counter += la;\r\n arr[l][0] = 0n;\r\n l++;\r\n continue;\r\n }\r\n\r\n var needForSale = lb - counter;\r\n if (needForSale >= ra) {\r\n ans += 2n * ra;\r\n counter += ra;\r\n arr[r][0] = 0n;\r\n r--;\r\n continue;\r\n }\r\n \r\n counter += needForSale;\r\n ans += 2n * needForSale;\r\n arr[r][0] -= needForSale;\r\n }\r\n write(ans);\r\n /*\r\n for (var i = 0; i < n; i++) {\r\n var a = arr[i][0];\r\n var b = arr[i][1];\r\n if (counter >= b) {\r\n counter += a;\r\n ans += a;\r\n continue;\r\n }\r\n var nextCounter = counter + a;\r\n if (nextCounter < b) {\r\n counter = nextCounter;\r\n ans += a * 2n;\r\n continue;\r\n }\r\n // counter < b <= nextCounter\r\n ans += (b - counter - 1n) * 2n + (nextCounter - b + 1n);\r\n counter = nextCounter;\r\n }\r\n write(ans);\r\n */\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n //T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n n = parseInt((await getLine()));\r\n const t = new Array(n);\r\n for(let i = 0; i < n; i++) {\r\n let ai, bi;\r\n [ai, bi] = (await getLine()).split(' ').map(num => BigInt(num));\r\n t[i] = {\r\n a: ai,\r\n b: bi\r\n };\r\n }\r\n let cmpt = (a,b) => {\r\n let diff = a.b - b.b;\r\n let zeroBig = BigInt(0);\r\n if (diff < zeroBig)\r\n return -1;\r\n else if (diff > zeroBig)\r\n return 1;\r\n else\r\n return 0;\r\n }\r\n t.sort(cmpt);\r\n let bought = BigInt(0);\r\n let sum = BigInt(0);\r\n let last = t.length - 1;\r\n let first = 0\r\n while (first <= last) {\r\n if (t[first].b > bought) {\r\n while (first <= last) {\r\n if (t[last].a + bought <= t[first].b){\r\n sum += BigInt(2) * t[last].a;\r\n bought += t[last].a;\r\n last--;\r\n }\r\n else {\r\n t[last].a -= (t[first].b - bought);\r\n sum += t[first].a + BigInt(2) * (t[first].b - bought);\r\n bought += t[first].b - bought + t[first].a;\r\n first++;\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n bought += t[first].a;\r\n sum += t[first].a;\r\n first++;\r\n }\r\n }\r\n console.log(sum.toString());\r\n}\r\n\r\nsolve();\r\n"}], "negative_code": [{"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var l = 0;\n var n = +lines[l++];\n var arr = lines.slice(l, l + n).map(str => str.split(' ').map(Number));\n console.log(solve(n, arr))\n});\n\nfunction solve(n, arr) {\n arr.sort((a, b) => a[1] - b[1])\n\n let i = 0\n let j = arr.length - 1\n let all = 0\n let pay = 0\n while (i < j) {\n const [total, limit] = arr[i]\n while (all < limit && j > i) {\n const able = arr[j][0]\n let cost\n if (all + able < limit) {\n cost = able\n arr[j][0] -= cost\n j--\n } else {\n cost = limit - all\n arr[j][0] -= cost\n }\n all += cost\n pay += 2 * cost\n }\n// console.log(arr, pay, all)\n if (all < limit) {\n const f = Math.min(total, limit - all)\n pay += f * 2\n all += f\n arr[i][0] -= f\n break\n } else {\n pay += total\n all += total\n arr[i][0] = 0\n i++\n }\n }\n // i == j\n if (all >= arr[i][1]) {\n pay += arr[i][0]\n } else {\n pay += 2 * arr[i][0]\n }\n return pay\n}\n"}, {"source_code": "\"use strict\";\r\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}));\r\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n});\r\nvar __importStar = (this && this.__importStar) || function (mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst fs = __importStar(require(\"fs\"));\r\n// import * as readline from 'readline'\r\n// const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\r\n// const ask = (query: string) => new Promise((resolve) => rl.question(query, resolve))\r\n// // Don't forget `rl.close()`.\r\nconst INT = Math.floor;\r\nArray.prototype.last = function () {\r\n return this.length === 0 ? undefined : this[this.length - 1];\r\n};\r\nArray.prototype.isEmpty = function () {\r\n return this.length === 0;\r\n};\r\nconst less = (a, b) => (a == b ? 0 : a < b ? -1 : 1);\r\nconst greater = (a, b) => (a == b ? 0 : a < b ? 1 : -1);\r\nconst bigIntMax = (...args) => args.reduce((m, e) => (e > m ? e : m));\r\nconst bigIntMin = (...args) => args.reduce((m, e) => (e < m ? e : m));\r\nconst bigIntAbs = (arg) => (arg < 0 ? -arg : arg);\r\nfunction read_stdin() {\r\n return fs.readFileSync(process.env.NODE_ENV === 'debug' ? stdin : process.stdin.fd, 'utf8');\r\n}\r\nclass Input {\r\n constructor(str) {\r\n this.index = 0;\r\n this.inputs = (str ? str : read_stdin()).split(/\\s+/);\r\n }\r\n number() {\r\n return Number(this.inputs[this.index++]);\r\n }\r\n numbers(n) {\r\n return this.inputs.slice(this.index, (this.index += n)).map(Number);\r\n }\r\n bigint() {\r\n return BigInt(this.inputs[this.index++]);\r\n }\r\n bigints(n) {\r\n return this.inputs.slice(this.index, (this.index += n)).map(BigInt);\r\n }\r\n word() {\r\n return this.inputs[this.index++];\r\n }\r\n words(n) {\r\n return this.inputs.slice(this.index, (this.index += n));\r\n }\r\n}\r\nfunction array(len, init) {\r\n return Array(len).fill(init);\r\n}\r\nfunction array2(h, w, init) {\r\n return array(h, 0).map(() => array(w, init));\r\n}\r\nfunction main() {\r\n const input = new Input();\r\n const N = input.number();\r\n const products = Array(N);\r\n for (let i = 0; i < N; i++) {\r\n const a = input.number();\r\n const b = input.number();\r\n products[i] = { a, b };\r\n }\r\n products.sort((x, y) => x.b - y.b);\r\n let head = 0;\r\n let tail = N - 1;\r\n let sum = 0;\r\n let count = 0;\r\n while (head <= tail) {\r\n // console.log({ head, tail })\r\n const p_head = products[head];\r\n let c = p_head.b - count;\r\n // console.log({ p_head, count, c })\r\n if (c > 0) {\r\n while (head <= tail) {\r\n // console.log({ head, tail, c })\r\n const p_tail = products[tail];\r\n if (p_tail.a > c) {\r\n p_tail.a -= c;\r\n count += c;\r\n sum += 2 * c;\r\n break;\r\n }\r\n else if (p_tail.a === c) {\r\n p_tail.a -= c;\r\n count += c;\r\n sum += 2 * c;\r\n tail--;\r\n break;\r\n }\r\n else {\r\n c -= p_tail.a;\r\n count += p_tail.a;\r\n sum += 2 * p_tail.a;\r\n tail--;\r\n }\r\n }\r\n }\r\n // console.log({ p_head })\r\n if (p_head.a > 0) {\r\n if (p_head.b <= count) {\r\n sum += p_head.a;\r\n }\r\n else {\r\n sum += 2 * p_head.a;\r\n }\r\n count += p_head.a;\r\n }\r\n head++;\r\n }\r\n console.log(sum);\r\n}\r\nmain();\r\n//# sourceMappingURL=aoj.js.map"}], "src_uid": "6e8cabaee588f53faae5feb2d1950c58"} {"nl": {"description": "A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?", "input_spec": "The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).", "output_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": "'use strict'\n\nlet lll = readline().split(' ')\nlet N = +lll[0]\nlet T = +lll[1]\n\nlet hoss = []\n\nwhile (lll = readline()) {\n lll = lll.split(' ')\n let x = +lll[0]\n let a = +lll[1]\n hoss.push([x - a / 2, x + a / 2])\n}\n\nlet pos = 0\n\nhoss = hoss.sort((a, b) => a[0] - b[0])\n\nhoss.forEach((h, i) => {\n let ph = hoss[i - 1] || [-Infinity, -Infinity]\n let nh = hoss[i + 1] || [Infinity, Infinity]\n if (h[0] - ph[1] >= T) pos++\n if (nh[0] - h[1] > T) pos++\n})\n\nprint(pos)"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar n, t, cont = [], indicator = 0, temp = [];\nrl.on('line', (input) => {\n if (indicator == 0) {\n temp = input.split(' ').map(item => parseInt(item));\n n = temp[0], t = temp[1];\n indicator++;\n }\n else {\n temp = input.split(' ').map(item => parseFloat(item));\n let houseCenter = temp[0];\n let houseLen = temp[1];\n let arr = [houseCenter - houseLen / 2, houseCenter + houseLen / 2];\n cont.push(arr);\n }\n\n}).on('close', function () {\n let ans = 2;\n cont.sort(function (obj1, obj2) {\n return obj1[0] - obj2[0];\n /*\n if(obj1[0] > obj2[0]) return 1;\n return -1;\n */\n });\n // console.log(cont);\n for (let i = 0; i < n - 1; i++) {\n let gap = cont[i + 1][0] - cont[i][1];\n if (gap > t) ans += 2;\n else if (gap == t) ans++;\n }\n console.log(ans);\n});"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar n, t, ans = 2, cont = [], indicator = 0, temp = [];\n\nrl.on('line', (input) => {\n if (indicator == 0) {\n temp = input.split(' ').map(item => parseInt(item));\n n = temp[0];\n t = temp[1];\n indicator++;\n }\n else {\n temp = input.split(' ').map(item => parseFloat(item));\n let center = temp[0];\n let len = temp[1];\n cont.push([center - len / 2, center + len / 2]);\n }\n\n}).on('close', () => {\n cont.sort((obj1, obj2) => { return obj1[0] - obj2[0] });\n for (let i = 0; i < n - 1; i++) {\n let gap = cont[i + 1][0] - cont[i][1];\n if (gap > t)\n ans += 2;\n else if (gap == t)\n ans++;\n }\n console.log(ans);\n});"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar n, t, indicator = 0, cont = [], temp = [];\nrl.on('line', (input) => {\n if (indicator == 0) {\n temp = input.split(' ').map(item => parseInt(item));\n n = temp[0];\n t = temp[1];\n indicator++;\n }\n else {\n temp = input.split(' ').map(item => parseInt(item));\n let center = temp[0], len = temp[1];\n cont.push([center - len / 2, center + len / 2])\n }\n}).on('close', () => {\n //sort array using comparator\n cont.sort((arr1, arr2) => {\n return arr1[0] - arr2[0];\n })\n\n //console.log(cont);\n let ans = 2;\n for (let i = 0; i < n - 1; i++) {\n let gap = cont[i + 1][0] - cont[i][1];\n if (gap > t) ans += 2;\n else if (gap == t) ans++;\n }\n console.log(ans);\n});"}, {"source_code": "const readline = require(\"readline\");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction addToArray(items, a, b) {\n var len = items.length;\n\n for (var i = 0; i < len; i++) {\n if (items[i] == a) {\n items[i] = b;\n return items;\n }\n if (items[i] == b) {\n items[i] = a;\n return items;\n }\n }\n\n var newArray = [len + 1];\n\n for (var i = 0; i < len; i++) {\n newArray[i] = items[i];\n }\n newArray[len] = a;\n newArray[len + 1] = b;\n\n return newArray;\n}\n\nfunction bubbleSort(cont) {\n var swapped,\n len = cont.length;\n if (len === 1) return;\n\n do {\n swapped = false;\n for (var i = 1; i < len; i++) {\n if (cont[i - 1] > cont[i]) {\n var b = cont[i];\n cont[i] = cont[i - 1];\n cont[i - 1] = b;\n swapped = true;\n }\n }\n } while (swapped);\n return;\n}\n\nvar array = [];\nvar mycont = [];\nvar n = -1;\nvar t = 0;\nvar counter = 2;\nvar coordinat = 0;\nvar check = false;\n\nrl.on(\"line\", input => {\n if (n == -1) {\n array = input.split(\" \");\n n = parseInt(array[0]);\n t = parseInt(array[1]);\n } else if (n != 1) {\n array = input.split(\" \");\n var x = parseInt(array[0]);\n var a = parseInt(array[1]);\n mycont = addToArray(mycont, x - a / 2, x + a / 2);\n\n n--;\n } else if (n == 1) {\n array = input.split(\" \");\n var x = parseInt(array[0]);\n var a = parseInt(array[1]);\n mycont = addToArray(mycont, x - a / 2, x + a / 2);\n\n bubbleSort(mycont);\n\n for (var i = 2; i < mycont.length - 1; i += 2) {\n if (mycont[i] - mycont[i - 1] == t) counter++;\n else if (mycont[i] - mycont[i - 1] > t) counter += 2;\n }\n }\n}).on(\"close\", () => {\n console.log(counter);\n});\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\n\n\n\nvar n, t, pos, len, indicator = 0,ans = 2,\n cont = [],\n temp = [];\n\n\n\nrl.on('line', (input) => {\n if (indicator == 0) {\n temp = input.split(' ').map(item => parseInt(item));\n n = temp[0];\n t = temp[1];\n indicator++;\n } else if (indicator < n) {\n temp = input.split(' ').map(item => parseInt(item));\n pos = temp[0];\n len = temp[1];\n cont.push([pos - len / 2, pos + len / 2]);\n indicator++;\n } else {\n temp = input.split(' ').map(item => parseInt(item));\n pos = temp[0];\n len = temp[1];\n cont.push([pos - len / 2, pos + len / 2]);\n /*our calculations here*/ \n cont.sort((a,b) => {return a[0]-b[0]});\n for(i=0;i t)\n ans+=2;\n else if(gap == t)\n ans++;\n\n \n }\n console.log(ans);\n rl.close();\n }\n\n});"}], "negative_code": [{"source_code": "const readline = require(\"readline\");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction addToArray(items, a) {\n var len = items.length;\n\n for (var i = 0; i < len; i++) {\n if (items[i] == a) return items;\n }\n\n var newArray = [len];\n\n for (var i = 0; i < len; i++) {\n newArray[i] = items[i];\n }\n newArray[len] = a;\n\n return newArray;\n}\n\nfunction bubbleSort(cont) {\n var swapped,\n len = cont.length;\n if (len === 1) return;\n\n do {\n swapped = false;\n for (var i = 1; i < len; i++) {\n if (cont[i - 1] > cont[i]) {\n var b = cont[i];\n cont[i] = cont[i - 1];\n cont[i - 1] = b;\n swapped = true;\n }\n }\n } while (swapped);\n return;\n}\n\nvar array = [];\nvar mycont = [];\nvar n = -1;\nvar t = 0;\nvar counter = 2;\nvar coordinat = 0;\nvar check = false;\n\nrl.on(\"line\", input => {\n if (n == -1) {\n array = input.split(\" \");\n n = parseInt(array[0]);\n t = parseInt(array[1]);\n } else if (n != 1) {\n array = input.split(\" \");\n var x = parseInt(array[0]);\n var a = parseInt(array[1]);\n mycont = addToArray(mycont, x - a / 2);\n mycont = addToArray(mycont, x + a / 2);\n n--;\n } else if (n == 1) {\n array = input.split(\" \");\n var x = parseInt(array[0]);\n var a = parseInt(array[1]);\n mycont = addToArray(mycont, x - a / 2);\n mycont = addToArray(mycont, x + a / 2);\n\n bubbleSort(mycont);\n for (var i = 1; i < mycont.length; i += 2) {\n if (mycont[i + 1] - mycont[i] == t) counter++;\n else if (mycont[i + 1] - mycont[i] > t) counter += 2;\n }\n\n }\n}).on(\"close\", () => {\n console.log(counter);\n //console.log(sleep2);\n});\n"}, {"source_code": "const readline = require(\"readline\");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar array = [];\nvar n = -1;\nvar t = 0;\nvar counter = 2;\nvar coordinat = 0;\nvar check = false;\n\nrl.on(\"line\", input => {\n if (n++ == -1) {\n array = input.split(\" \");\n t = parseInt(array[1]);\n } else {\n array = input.split(\" \");\n var x = parseInt(array[0]);\n var a = parseInt(array[1]);\n if (check) {\n if (x - a / 2 - coordinat > t) counter += 2;\n else if (x - a / 2 - coordinat == t) counter++;\n }\n\n coordinat = x + a / 2;\n\n check = true;\n }\n\n}).on(\"close\", () => {\n console.log(counter);\n \n });;\n"}, {"source_code": "const readline = require(\"readline\");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction addToArray(items, a) {\n var len = items.length;\n\n for (var i = 0; i < len; i++) {\n if (items[i] == a) return items;\n }\n\n var newArray = [len];\n\n for (var i = 0; i < len; i++) {\n newArray[i] = items[i];\n }\n newArray[len] = a;\n\n return newArray;\n}\n\nfunction bubbleSort(cont) {\n var swapped,\n len = cont.length;\n if (len === 1) return;\n\n do {\n swapped = false;\n for (var i = 1; i < len; i++) {\n if (cont[i - 1] > cont[i]) {\n var b = cont[i];\n cont[i] = cont[i - 1];\n cont[i - 1] = b;\n swapped = true;\n }\n }\n } while (swapped);\n return;\n}\n\nvar array = [];\nvar mycont = [];\nvar n = -1;\nvar t = 0;\nvar counter = 2;\nvar coordinat = 0;\nvar check = false;\n\nrl.on(\"line\", input => {\n if (n == -1) {\n array = input.split(\" \");\n n = parseInt(array[0]);\n t = parseInt(array[1]);\n } else if (n != 0) {\n array = input.split(\" \");\n var x = parseInt(array[0]);\n var a = parseInt(array[1]);\n mycont = addToArray(mycont, x - a / 2);\n mycont = addToArray(mycont, x + a / 2);\n n--;\n } else if (n == 0) {\n bubbleSort(mycont);\n for (var i = 1; i < mycont.length; i += 2) {\n if (mycont[i + 1] - mycont[i] == t) counter++;\n else if (mycont[i + 1] - mycont[i] > t) counter += 2;\n }\n\n console.log(counter);\n rl.close();\n }\n});\n"}], "src_uid": "c31fed523230af1f904218b2fe0d663d"} {"nl": {"description": "A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — $$$n$$$ and $$$k$$$, where $$$n$$$ is even. Next, he takes all the integers from $$$1$$$ to $$$n$$$, and splits them all into pairs $$$(a, b)$$$ (each integer must be in exactly one pair) so that for each pair the integer $$$(a + k) \\cdot b$$$ is divisible by $$$4$$$ (note that the order of the numbers in the pair matters), or reports that, unfortunately for viewers, such a split is impossible.Burenka really likes such performances, so she asked her friend Tonya to be a magician, and also gave him the numbers $$$n$$$ and $$$k$$$.Tonya is a wolf, and as you know, wolves do not perform in the circus, even in a mathematical one. Therefore, he asks you to help him. Let him know if a suitable splitting into pairs is possible, and if possible, then tell it.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The single line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\leq n \\leq 2 \\cdot 10^5$$$, $$$0 \\leq k \\leq 10^9$$$, $$$n$$$ is even) — the number of integers and the number being added $$$k$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "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 — 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": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const [n, k] = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n k,\n };\n\n testCases.push(testCase);\n }\n}\n\nfunction solution(testCase) {\n const { n, k } = testCase;\n // console.log(n, k);\n\n if (k % 4 == 0) console.log(\"NO\");\n else {\n console.log(\"YES\");\n const a2 = (4 - (k % 4)) % 4;\n const b1 = 4;\n const s = new Set([1, 2, 3]);\n s.delete(a2);\n const a1 = Array.from(s)[0];\n const b2 = Array.from(s)[1];\n\n // console.error(a1, b1, a2, b2);\n\n for (let i = 0; i < Math.floor(n / 4); i++) {\n console.log(\n i * 4 + a1,\n i * 4 + b1\n // ((i * 4 + a1 + k) * (i * 4 + b1)) % 4\n );\n console.log(\n i * 4 + a2,\n i * 4 + b2\n // ((i * 4 + a2 + k) * (i * 4 + b2)) % 4\n );\n }\n if (n % 4 == 2) {\n if (k % 4 == 2)\n console.log(\n n,\n n - 1\n // ((n + k) * (n - 1)) % 4\n );\n else\n console.log(\n n - 1,\n n\n // ((n - 1 + k) * n) % 4\n );\n }\n }\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n const [n, k] = readline().split(' ').map(Number);\r\n\r\n if (k % 2 === 1) {\r\n output('YES');\r\n for (let i = 0; i < (n / 2); i++) {\r\n let first = i * 2 + 1;\r\n let second = first + 1;\r\n output(first + ' ' + second);\r\n }\r\n continue;\r\n } else if (k % 4 === 0) {\r\n output('NO');\r\n } else if (k % 4 === 2) {\r\n let start = 4;\r\n output('YES');\r\n let temp = n;\r\n while (start <= n) {\r\n output((start - 1) + ' ' + start);\r\n output((start - 2) + ' ' + (start - 3));\r\n start += 4;\r\n temp -= 4;\r\n }\r\n if (temp === 2) {\r\n output((start - 2) + ' ' + (start - 3));\r\n }\r\n }\r\n }\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, k)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k) {\n // (a + k) * b = 4x\n const h = n / 2\n const ans = []\n if (k & 1) {\n // (odd + k) * even\n for (let i = 1; i < n; i += 2) {\n ans.push([i, i + 1])\n }\n } else {\n const r = k % 4\n if (!r) return 'NO'\n // 4n, 4n - k, with odd\n const ps = [[], [], [], [], []]\n let i = 1\n while (i <= n) {\n for (let j = 1; j <= 4; j++) {\n ps[j].push(i++)\n if (i > n) break\n }\n }\n ps[0] = ps[4] // hack\n let p0 = 0\n let p1 = 0, ps1 = ps[4 - r]\n for (let i = 1; i < n; i += 2) {\n if (p0 < ps[0].length) {\n ans.push([i, ps[0][p0++]])\n } else {\n ans.push([ps1[p1++], i])\n }\n }\n // console.log(ps, ans)\n // const other = ps[r]\n // for (let i = 0; i < other.length; i += 2) {\n // ans.push([other[i], other[i + 1]])\n // }\n }\n return 'YES\\n' + ans.map(x => x.join(' ')).join('\\n')\n}\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(a) {\r\n const [n, m] = a;\r\n if (m & 1) {\r\n const res = ['YES'];\r\n for (let i = 1; i <= n; i += 2) {\r\n res.push(`${i} ${i + 1}`);\r\n }\r\n return res.join('\\n');\r\n } else if (m % 4 === 2) {\r\n let res = ['YES'];\r\n for (let i = 1; i <= n; i += 2) {\r\n if ((i + 1) / 2 & 1) {\r\n res.push(`${i + 1} ${i}`);\r\n } else {\r\n res.push(`${i} ${i + 1}`);\r\n }\r\n }\r\n return res.join('\\n');\r\n }\r\n return 'NO';\r\n}\r\n\r\nasync function main(r) {\r\n const rns = async () => {\r\n return (await r()).split(' ').filter(s => s !== '').map(Number);\r\n };\r\n try {\r\n let t = Number(await r());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const a = await rns();\r\n res[i] = solve(a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n/***\nCodeforces Round #814 (Div. 2)\n2022-08-16\n\nA. Chip Game\n***/\n\nfunction main() {\n const t = parseInt(readline());\n\n for (let i = 0; i < t; i++) {\n const testCase = readline().split(\" \");\n const n = parseInt(testCase[0]);\n const k = parseInt(testCase[1]);\n\n // k is odd -> pair 1-2, 3-4\n // k is 2 (mod 4) -> pair 2-1, 3-4\n switch (k % 4) {\n case 1:\n case 3:\n console.log(\"YES\");\n for (let startNum = 1; startNum < n; startNum += 2) {\n console.log(startNum + \" \" + (startNum + 1));\n }\n break;\n case 2:\n console.log(\"YES\");\n for (let startNumB = 3; startNumB < n; startNumB += 4) {\n console.log(startNumB + \" \" + (startNumB + 1));\n }\n for (let startNumA = 2; startNumA <= n; startNumA += 4) {\n console.log(startNumA + \" \" + (startNumA - 1));\n }\n break;\n case 0:\n console.log(\"NO\");\n break;\n default:\n console.log(\n \"Something went wrong: \" +\n k +\n \" is in none of the mod 4 residue classes\"\n );\n break;\n }\n }\n}\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n let cases = parseInt(lines[0])\n //const splitLines = lines.map(x => x.split(\" \").map(x => parseInt(x)))\n for (let i = 1; i <= cases; i ++)\n {\n let a = lines[i].split(\" \").map(x => parseInt(x))\n let n = a[0];\n let k = a[1];\n switch (k % 4)\n {\n case 0:\n console.log(\"NO\");\n break;\n case 1:\n case 3:\n console.log(\"YES\")\n for (let i = 1; i <= n; i +=2)\n {\n console.log(i + \" \" + (i + 1))\n }\n break;\n case 2:\n console.log(\"YES\")\n for (let i = 1; i <= n; i += 2)\n {\n if (i % 4 == 1)\n {\n console.log((i + 1) + \" \" + i)\n }\n else{\n console.log(i + \" \" + (i + 1))\n }\n }\n }\n }\n})"}, {"source_code": "var n, k;\r\n var tests = parseInt(readline());\r\n for (var t=0; tparseInt(x));\r\n n = nk[0];\r\n k = nk[1];\r\n if (k % 4 == 0) {\r\n print('NO');\r\n continue;\r\n }\r\n print('YES');\r\n if (k & 1) {\r\n for (var i = 1; i <= n; i+=2) {\r\n print(i + ' ' + (i+1));\r\n }\r\n } else {\r\n for (var i = 2; i <= n; i+=2) {\r\n if (i % 4 == 0) {\r\n print((i-1) + ' ' + i);\r\n } else {\r\n print(i + ' ' + (i-1));\r\n }\r\n }\r\n }\r\n }"}], "negative_code": [{"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const [n, k] = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n k,\n };\n\n testCases.push(testCase);\n }\n}\n\nfunction solution(testCase) {\n const { n, k } = testCase;\n // console.log(n, k);\n\n if (k % 4 == 0 || (k % 4 == 2 && n % 4 == 2)) console.log(\"NO\");\n else {\n console.log(\"YES\");\n const a2 = (4 - (k % 4)) % 4;\n const b1 = 4;\n const s = new Set([1, 2, 3]);\n s.delete(a2);\n const a1 = Array.from(s)[0];\n const b2 = Array.from(s)[1];\n\n // console.error(a1, b1, a2, b2);\n\n for (let i = 0; i < Math.floor(n / 4); i++) {\n console.log(\n i * 4 + a1,\n i * 4 + b1\n // ((i * 4 + a1 + k) * (i * 4 + b1)) % 4\n );\n console.log(\n i * 4 + a2,\n i * 4 + b2\n // ((i * 4 + a2 + k) * (i * 4 + b2)) % 4\n );\n }\n if (n % 4 == 2) console.log(n - 1, n);\n }\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n const [n, k] = readline().split(' ').map(Number);\r\n\r\n if (k % 2 === 1) {\r\n output('YES');\r\n for (let i = 0; i < (n / 2); i++) {\r\n let first = i * 2 + 1;\r\n let second = first + 1;\r\n output(first + ' ' + second);\r\n }\r\n continue;\r\n } else if (k % 4 === 0) {\r\n output('NO');\r\n } else if (k % 4 === 2) {\r\n let start = 4;\r\n output('YES');\r\n let temp = n;\r\n while (start <= n) {\r\n output((start - 1) + ' ' + start);\r\n output((start - 2) + ' ' + (start - 3));\r\n start += 4;\r\n temp -= 4;\r\n }\r\n if (temp === 2) {\r\n output((start + 2) + ' ' + (start + 1));\r\n }\r\n }\r\n }\r\n}\r\n"}], "src_uid": "d4fc7e683f389e0c7bbee8e115cef459"} {"nl": {"description": "Recently in Divanovo, a huge river locks system was built. There are now $$$n$$$ locks, the $$$i$$$-th of them has the volume of $$$v_i$$$ liters, so that it can contain any amount of water between $$$0$$$ and $$$v_i$$$ liters. Each lock has a pipe attached to it. When the pipe is open, $$$1$$$ liter of water enters the lock every second.The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $$$i$$$ to the lock $$$i + 1$$$. If the lock $$$i + 1$$$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates $$$5$$$ locks with two open pipes at locks $$$1$$$ and $$$3$$$. Because locks $$$1$$$, $$$3$$$, and $$$4$$$ are already filled, effectively the water goes to locks $$$2$$$ and $$$5$$$. Note that the volume of the $$$i$$$-th lock may be greater than the volume of the $$$i + 1$$$-th lock.To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $$$q$$$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $$$j$$$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $$$t_j$$$ seconds.Please help the mayor to solve this tricky problem and answer his queries. ", "input_spec": "The first lines contains one integer $$$n$$$ ($$$1 \\le n \\le 200\\,000$$$) — the number of locks. The second lines contains $$$n$$$ integers $$$v_1, v_2, \\dots, v_n$$$ ($$$1 \\le v_i \\le 10^9$$$)) — volumes of the locks. The third line contains one integer $$$q$$$ ($$$1 \\le q \\le 200\\,000$$$) — the number of queries. Each of the next $$$q$$$ lines contains one integer $$$t_j$$$ ($$$1 \\le t_j \\le 10^9$$$) — the number of seconds you have to fill all the locks in the query $$$j$$$. ", "output_spec": "Print $$$q$$$ integers. The $$$j$$$-th of them should be equal to the minimum number of pipes to turn on so that after $$$t_j$$$ seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print $$$-1$$$. ", "sample_inputs": ["5\n4 1 5 4 1\n6\n1\n6\n2\n3\n4\n5", "5\n4 4 4 4 4\n6\n1\n3\n6\n5\n2\n4"], "sample_outputs": ["-1\n3\n-1\n-1\n4\n3", "-1\n-1\n4\n4\n-1\n5"], "notes": "NoteThere are $$$6$$$ queries in the first example test. In the queries $$$1, 3, 4$$$ the answer is $$$-1$$$. We need to wait $$$4$$$ seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$. After $$$4$$$ seconds the locks $$$1$$$ and $$$4$$$ are full. In the following $$$1$$$ second $$$1$$$ liter of water is transferred to the locks $$$2$$$ and $$$5$$$. The lock $$$3$$$ is filled by its own pipe. Similarly, in the second query one can open pipes in locks $$$1$$$, $$$3$$$, and $$$4$$$.In the fifth query one can open pipes $$$1, 2, 3, 4$$$. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, a, b) {\r\n let min = 0,\r\n sum = 0;\r\n for (let [i, num] of a.entries()) {\r\n sum += num;\r\n min = Math.max(min, Math.ceil(sum / (i + 1)));\r\n }\r\n let res = new Array(m);\r\n for (let [i, num] of b.entries()) {\r\n if (num < min) {\r\n res[i] = -1;\r\n } else {\r\n res[i] = Math.ceil(sum / num);\r\n }\r\n }\r\n return res.join('\\n');\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const m = Number(await read());\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push(Number(await read()));\r\n }\r\n res[i] = solve(n, m, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "negative_code": [], "src_uid": "d7361a43bff124cea280ae8817b807ec"} {"nl": {"description": "Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.For example, the centroid of the following tree is $$$2$$$, because when you cut it, the size of the largest connected component of the remaining graph is $$$2$$$ and it can't be smaller. However, in some trees, there might be more than one centroid, for example: Both vertex $$$1$$$ and vertex $$$2$$$ are centroids because the size of the largest connected component is $$$3$$$ after cutting each of them.Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\leq t\\leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3\\leq n\\leq 10^5$$$) — the number of vertices. Each of the next $$$n-1$$$ lines contains two integers $$$x, y$$$ ($$$1\\leq x,y\\leq n$$$). It means, that there exists an edge connecting vertices $$$x$$$ and $$$y$$$. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print two lines. In the first line print two integers $$$x_1, y_1$$$ ($$$1 \\leq x_1, y_1 \\leq n$$$), which means you cut the edge between vertices $$$x_1$$$ and $$$y_1$$$. There should exist edge connecting vertices $$$x_1$$$ and $$$y_1$$$. In the second line print two integers $$$x_2, y_2$$$ ($$$1 \\leq x_2, y_2 \\leq n$$$), which means you add the edge between vertices $$$x_2$$$ and $$$y_2$$$. The graph after these two operations should be a tree. If there are multiple solutions you can print any.", "sample_inputs": ["2\n5\n1 2\n1 3\n2 4\n2 5\n6\n1 2\n1 3\n1 4\n2 5\n2 6"], "sample_outputs": ["1 2\n1 2\n1 3\n2 3"], "notes": "NoteNote that you can add the same edge that you cut.In the first test case, after cutting and adding the same edge, the vertex $$$2$$$ is still the only centroid.In the second test case, the vertex $$$2$$$ becomes the only centroid after cutting the edge between vertices $$$1$$$ and $$$3$$$ and adding the edge between vertices $$$2$$$ and $$$3$$$."}, "positive_code": [{"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i <= b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = a; i >= b; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction Arr(a, b, cb, prev) {\n let p = prev || 0;\n if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);\n return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);\n}\n\nfunction FindMin(arr, fn) {\n let min = Math.min(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [i, min];\n}\n\nfunction FindMax(arr, fn) {\n let max = Math.max(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [i, max];\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\s+/).map(v => +v); r = 0;\n let t = inp[r++];\n while (t--) {\n let n = inp[r++];\n let edge = Arr(0, n, i => []);\n For(1, n - 1, i => {\n let u = inp[r++], v = inp[r++];\n edge[u].push(v);\n edge[v].push(u);\n });\n let size = Array(n + 1).fill(0);\n let t0 = Array(n + 1).fill(0);\n let t1 = Array(n + 1).fill(0);\n let minComp = 1e10, res = [], t = 0;\n let dfs = async (v, cb) => {\n t0[v] = t++;\n size[v] = 1;\n let comp = 0;\n for (let u of edge[v]) {\n if (size[u]) continue;\n await new Promise(resolve => {\n if (t % 1000 == 0) setTimeout(() => dfs(u, resolve), 0);\n else dfs(u, resolve);\n });\n size[v] += size[u];\n comp = Math.max(comp, size[u]);\n };\n comp = Math.max(comp, n - size[v]);\n if (comp < minComp) {\n minComp = comp;\n res = [v];\n } else if (comp == minComp) res.push(v);\n t1[v] = t++;\n cb();\n }\n await new Promise(resolve => dfs(1, resolve));\n // console.log(size);\n // console.log(res, minComp);\n // console.log(t0,t1);\n if (res.length == 1) {\n let u = Arr(1, n).find(u => edge[u].length);\n console.log(u, edge[u][0]);\n console.log(u, edge[u][0]);\n } else {\n if (t0[res[0]] > t0[res[1]]) res.reverse();\n // console.log(res);\n let i = Arr(1, n).find(i => size[i] == 1 && t0[res[1]] < t0[i] && t1[i] < t1[res[1]]);\n // console.log(i);\n console.log(i, edge[i][0]);\n console.log(i, res[0]);\n }\n }\n})();"}], "negative_code": [{"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i <= b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = a; i >= b; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction Arr(a, b, cb, prev) {\n let p = prev || 0;\n if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);\n return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);\n}\n\nfunction FindMin(arr, fn) {\n let min = Math.min(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [i, min];\n}\n\nfunction FindMax(arr, fn) {\n let max = Math.max(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [i, max];\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\s+/).map(v => +v); r = 0;\n let t = inp[r++];\n For(1, t, i => {\n let n = inp[r++];\n let edge = Arr(0, n, i => []);\n For(1, n - 1, i => {\n let u = inp[r++], v = inp[r++];\n edge[u].push(v);\n edge[v].push(u);\n });\n let size = Array(n + 1).fill(0);\n let bfs = [];\n let q = [1];\n let mark = {};\n while (q.length) {\n let u = q.shift();\n size[u] = 1;\n bfs.push(u);\n edge[u].forEach(v => {\n if (size[v]) return;\n q.push(v);\n })\n }\n let minComp = 1e10, res = [];\n For(n - 1, 0, i => {\n let comp = 0;\n mark[bfs[i]] = i+1;\n edge[bfs[i]].forEach(u => {\n if (!mark[u]) return;\n comp = Math.max(comp, size[u]);\n size[bfs[i]] += size[u];\n });\n comp = Math.max(comp, n - size[bfs[i]]);\n if (comp < minComp) {\n minComp = comp;\n res = [bfs[i]];\n } else if (comp == minComp) res.push(bfs[i]);\n })\n // console.log(size);\n // console.log(res, minComp);\n // console.log(t0,t1);\n if (res.length == 1) {\n let u = Arr(1, n).find(u => edge[u].length);\n console.log(u, edge[u][0]);\n console.log(u, edge[u][0]);\n } else {\n res.reverse();\n // console.log(res);\n let i = Arr(1, n).find(i => size[i] == 1 && mark[res[1]] < mark[i]);\n // console.log(i);\n console.log(i, edge[i][0]);\n console.log(i, res[0]);\n }\n })\n})();"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i <= b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = a; i >= b; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction Arr(a, b, cb, prev) {\n let p = prev || 0;\n if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);\n return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);\n}\n\nfunction FindMin(arr, fn) {\n let min = Math.min(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [i, min];\n}\n\nfunction FindMax(arr, fn) {\n let max = Math.max(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [i, max];\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\s+/).map(v => +v); r = 0;\n let t = inp[r++];\n For(1, t, i => {\n let n = inp[r++];\n let edge = Arr(0, n, i => []);\n For(1, n - 1, i => {\n let u = inp[r++], v = inp[r++];\n edge[u].push(v);\n edge[v].push(u);\n });\n let size = Array(n + 1).fill(0);\n let minComp = 1e10, res = [];\n let dfs = v => {\n size[v] = 1;\n let comp = 0;\n edge[v].forEach(u => {\n if (size[u]) return;\n dfs(u);\n size[v] += size[u];\n comp = Math.max(comp, size[u]);\n });\n comp = Math.max(comp, n - size[v]);\n if (comp < minComp) {\n minComp = comp;\n res = [v];\n } else if (comp == minComp) res.push(v);\n }\n dfs(1);\n // console.log(size);\n // console.log(res, minComp);\n if (res.length == 1) {\n let u = Arr(1, n).find(u => edge[u].length);\n console.log(u, edge[u][0]);\n console.log(u, edge[u][0]);\n } else {\n console.log(res[0], res[1]);\n let [i] = FindMax(edge[res[1]], v => v == res[0] ? 0 : size[v]);\n console.log(res[0], edge[res[1]][i]);\n }\n })\n})();"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i <= b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = a; i >= b; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction Arr(a, b, cb, prev) {\n let p = prev || 0;\n if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);\n return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);\n}\n\nfunction FindMin(arr, fn) {\n let min = Math.min(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [i, min];\n}\n\nfunction FindMax(arr, fn) {\n let max = Math.max(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [i, max];\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\s+/).map(v => +v); r = 0;\n let t = inp[r++];\n For(1, t, i => {\n let n = inp[r++];\n let edge = Arr(0, n, i => []);\n For(1, n - 1, i => {\n let u = inp[r++], v = inp[r++];\n edge[u].push(v);\n edge[v].push(u);\n });\n let size = Array(n + 1).fill(0);\n let t0 = Array(n + 1).fill(0);\n let t1 = Array(n + 1).fill(0);\n let minComp = 1e10, res = [], t = 0;\n let dfs = v => {\n t0[v] = t++;\n size[v] = 1;\n let comp = 0;\n edge[v].forEach(u => {\n if (size[u]) return;\n dfs(u);\n size[v] += size[u];\n comp = Math.max(comp, size[u]);\n });\n comp = Math.max(comp, n - size[v]);\n if (comp < minComp) {\n minComp = comp;\n res = [v];\n } else if (comp == minComp) res.push(v);\n t1[v] = t++;\n }\n dfs(1);\n // console.log(size);\n // console.log(res, minComp);\n // console.log(t0,t1);\n if (res.length == 1) {\n let u = Arr(1, n).find(u => edge[u].length);\n console.log(u, edge[u][0]);\n console.log(u, edge[u][0]);\n } else {\n if (t0[res[0]] > t0[res[1]]) res.reverse();\n // console.log(res);\n let i = Arr(1,n).find(i => size[i]==1 && t0[res[1]] < t0[i] && t1[i] < t1[res[1]]);\n // console.log(i);\n console.log(i, edge[i][0]);\n let [j] = FindMin(edge[res[0]], v => v == res[1] ? 1e10 : size[v]);\n console.log(i, edge[res[0]][j]);\n }\n })\n})();"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i <= b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = a; i >= b; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction Arr(a, b, cb, prev) {\n let p = prev || 0;\n if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);\n return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);\n}\n\nfunction FindMin(arr, fn) {\n let min = Math.min(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [i, min];\n}\n\nfunction FindMax(arr, fn) {\n let max = Math.max(...arr.map((v, i) => fn ? fn(v, i) : v));\n let i = arr.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [i, max];\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\s+/).map(v => +v); r = 0;\n let t = inp[r++];\n For(1, t, i => {\n let n = inp[r++];\n let edge = Arr(0, n, i => []);\n For(1, n - 1, i => {\n let u = inp[r++], v = inp[r++];\n edge[u].push(v);\n edge[v].push(u);\n });\n let size = Array(n + 1).fill(0);\n let t0 = Array(n + 1).fill(0);\n let t1 = Array(n + 1).fill(0);\n let minComp = 1e10, res = [], t = 0;\n let dfs = v => {\n t0[v] = t++;\n size[v] = 1;\n let comp = 0;\n edge[v].forEach(u => {\n if (size[u]) return;\n dfs(u);\n size[v] += size[u];\n comp = Math.max(comp, size[u]);\n });\n comp = Math.max(comp, n - size[v]);\n if (comp < minComp) {\n minComp = comp;\n res = [v];\n } else if (comp == minComp) res.push(v);\n t1[v] = t++;\n }\n dfs(1);\n // console.log(size);\n // console.log(res, minComp);\n // console.log(t0,t1);\n if (res.length == 1) {\n let u = Arr(1, n).find(u => edge[u].length);\n console.log(u, edge[u][0]);\n console.log(u, edge[u][0]);\n } else {\n if (t0[res[0]] > t0[res[1]]) res.reverse();\n // console.log(res);\n let i = Arr(1,n).find(i => size[i]==1 && t0[res[1]] < t0[i] && t1[i] < t1[res[1]]);\n // console.log(i);\n console.log(i, edge[i][0]);\n console.log(i, res[0]);\n }\n })\n})();"}], "src_uid": "b01fb9d4d78a02e3c634800b4b177d75"} {"nl": {"description": "This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.To bake a Napoleon cake, one has to bake $$$n$$$ dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps $$$n$$$ times: place a new cake layer on the top of the stack; after the $$$i$$$-th layer is placed, pour $$$a_i$$$ units of cream on top of the stack. When $$$x$$$ units of cream are poured on the top of the stack, top $$$x$$$ layers of the cake get drenched in the cream. If there are less than $$$x$$$ layers, all layers get drenched and the rest of the cream is wasted. If $$$x = 0$$$, no layer gets drenched. The picture represents the first test case of the example. Help Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 20\\,000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the number of layers in the cake. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le n$$$) — the amount of cream poured on the cake after adding each layer. 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 line with $$$n$$$ integers. The $$$i$$$-th of the integers should be equal to $$$1$$$ if the $$$i$$$-th layer from the bottom gets drenched, and $$$0$$$ otherwise.", "sample_inputs": ["3\n6\n0 3 0 0 1 3\n10\n0 0 0 1 0 5 0 0 0 2\n3\n0 0 0"], "sample_outputs": ["1 1 0 1 1 1 \n0 1 1 1 1 1 0 0 1 1 \n0 0 0"], "notes": null}, "positive_code": [{"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var cream = [];\r\n var low = -1;\r\n var high = -1;\r\n for (var i = 0; i < n; i++) {\r\n cream[i] = 0;\r\n if (a[i] === 0) {\r\n continue;\r\n }\r\n var bottom = i - a[i] + 1;\r\n if (bottom < 0) {\r\n bottom = 0;\r\n }\r\n if (bottom > high) {\r\n low = bottom;\r\n high = i;\r\n for (var j = low; j <= high; j++) {\r\n cream[j] = 1;\r\n }\r\n continue;\r\n }\r\n if (bottom < low) {\r\n for (var j = bottom; j < low; j++) {\r\n cream[j] = 1;\r\n }\r\n low = bottom;\r\n }\r\n for (var j = high + 1; j <= i; j++) {\r\n cream[j] = 1;\r\n }\r\n high = i;\r\n }\r\n write(cream.join(' ')); \r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n init();\r\n} else {\r\n init();\r\n}\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var cream = [];\r\n var low = -1;\r\n var high = -1;\r\n for (var i = 0; i < n; i++) {\r\n cream[i] = 0;\r\n if (a[i] === 0) {\r\n continue;\r\n }\r\n var bottom = i - a[i] + 1;\r\n if (bottom < 0) {\r\n bottom = 0;\r\n }\r\n if (bottom > high) {\r\n low = bottom;\r\n high = i;\r\n for (var j = low; j <= high; j++) {\r\n cream[j] = 1;\r\n }\r\n continue;\r\n }\r\n if (bottom < low) {\r\n for (var j = bottom; j < low; j++) {\r\n cream[j] = 1;\r\n }\r\n low = bottom;\r\n }\r\n for (var j = high + 1; j <= i; j++) {\r\n cream[j] = 1;\r\n }\r\n high = i;\r\n }\r\n write(cream.join(' ')); \r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n MEMORY = fs.readFileSync(inTextName ? path.join(__dirname, inTextName) : 0, 'utf8').split('\\r\\n');\r\n init();\r\n} else {\r\n init();\r\n}\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var cream = [];\r\n var low = -1;\r\n var high = -1;\r\n for (var i = 0; i < n; i++) {\r\n cream[i] = 0;\r\n if (a[i] === 0) {\r\n continue;\r\n }\r\n var bottom = i - a[i] + 1;\r\n if (bottom < 0) {\r\n bottom = 0;\r\n }\r\n if (bottom > high) {\r\n low = bottom;\r\n high = i;\r\n for (var j = low; j <= high; j++) {\r\n cream[j] = 1;\r\n }\r\n continue;\r\n }\r\n if (bottom < low) {\r\n for (var j = bottom; j < low; j++) {\r\n cream[j] = 1;\r\n }\r\n low = bottom;\r\n }\r\n for (var j = high + 1; j <= i; j++) {\r\n cream[j] = 1;\r\n }\r\n high = i;\r\n }\r\n write(cream.join(' ')); \r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n fs.readFile(inTextName ? path.join(__dirname, inTextName) : 0, 'utf8', function(err, data) {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n });\r\n} else {\r\n init();\r\n}\r\n \r\nfunction write(value) {\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve(n, arr) {\r\n const res = Array(n).fill(0)\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (arr[i] !== 0) {\r\n res[i] = 1\r\n if (arr[i - 1] < arr[i]) arr[i - 1] = arr[i] - 1\r\n }\r\n }\r\n console.log(res.join(' '))\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i][0], inputArr[i + 1])\r\n}"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 2e5+1;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tconst ans = [];\r\n\t\tfor (let i = n - 1, mn = INF; i >= 0; i--) {\r\n\t\t\tmn = Math.min(mn, i - a[i] + 1);\r\n\t\t\tans[i] = i >= mn ? 1 : 0;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.join(' '));\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tconst st = [];\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tif (a[i] == 0) {\r\n\t\t\t\tst.push(i);\r\n\t\t\t} else {\r\n\t\t\t\twhile (st.length && i - a[i] < st[st.length-1]) {\r\n\t\t\t\t\tst.pop();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst ans = Array(n).fill(1);\r\n\t\twhile (st.length) {\r\n\t\t\tans[st.pop()] = 0;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.join(' '));\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const { EOL } = require('os');\r\n\r\nlet i = ''\r\nprocess.stdin.on('data', c => i += c)\r\nprocess.stdin.on('end', () => main(i));\r\n\r\nfunction getAnswer(c) {\r\n const creams = c.reverse();\r\n let size = 0;\r\n for (let i = 0; i < creams.length; i++) {\r\n if (creams[i] > size) size = creams[i];\r\n creams[i] = size > 0 ? 1 : 0;\r\n size--;\r\n }\r\n return c.reverse().join(' ');\r\n}\r\n\r\nfunction main(param) {\r\n const input = param.split(EOL);\r\n const t = Number(input[0]);\r\n let index = 1;\r\n for (let i = 0; i < t; i++) {\r\n index++;\r\n const creams = input[index++].split(/\\s+/).map(Number);\r\n console.log(getAnswer(creams));\r\n }\r\n}"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n\tfor(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i];\n }else{\n var a = lines[i].split(' ').map(Number);\n var temp = a[n - 1];\n var b = new Array(n);\n for(j = 0; j < n; j++){\n b[j] = 0;\n }\n for(j = n - 1; j >= 0; j--){\n if(temp !== 0 || a[j] !== 0){\n b[j] = 1;\n temp = Math.max(temp, a[j]);\n temp--;\n }else{\n temp = a[j];\n }\n }\n var ans = '';\n for(j = 0; j < n; j++){\n ans += b[j] + ' ';\n }\n console.log(ans);\n }\n }\n});\n\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n var n = parseInt(readline())\r\n\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n var max = 0\r\n var ans = new Array(n).fill(0)\r\n for (let i = n; i >= 0; i--) {\r\n if (a[i] > 0 && a[i] > max-1) {\r\n max = a[i]\r\n ans[i] = 1\r\n max--\r\n continue\r\n }\r\n if (max > 0) {\r\n ans[i] = 1\r\n max--\r\n }\r\n\r\n\r\n }\r\n\r\n // if(n>=1) ans-=a[n-1]\r\n\r\n console.log(ans.join(' '))\r\n // console.log(a)\r\n\r\n })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar queue = [];\r\n\t\tfor(var j = 0; j < N; j++){\r\n\t\t\tqueue.push(0);\r\n\t\t\tif(list[j] != 0){\r\n\t\t\t\tif(queue.length > list[j]){\r\n\t\t\t\t\tqueue[j - list[j] + 1] = list[j];\r\n\t\t\t\t}else{\r\n\t\t\t\t\tqueue[0] = queue.length;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tvar last = -1;\r\n\t\tfor(var j = 0; j < N; j++){\r\n\t\t\tif(queue[j] != 0){\r\n\t\t\t\tlast = Math.max(last, queue[j]);\r\n\t\t\t}\r\n\t\t\tif(last > 0){\r\n\t\t\t\tqueue[j] = 1;\r\n\t\t\t\tlast--;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(myconv(queue, 8));\r\n\t}\r\n}\r\n"}, {"source_code": "function solve() {\r\n var numPan = readline(\"\");\r\n var array = readline(\"\").split(\" \");\r\n \r\n array.reverse();\r\nvar ans = [];\r\nvar curNum = 0;\r\n for (var elm in array) {\r\n curNum = Math.max(array[elm], curNum);\r\n if (curNum) {\r\n ans.push(1);\r\n curNum--;\r\n } else {\r\n ans.push(0);\r\n }\r\n }\r\n\r\n for (var ab=ans.length-1;ab>=0;ab--) {\r\n print(ans[ab]);\r\n }\r\n return \"hi\";\r\n}\r\n\r\n\r\nvar testCases = readline(\"\");\r\nfor (var i=0;i parseInt(x));\n var dt = pies, ndt;\n for(var i =pies-1;i>=0;i--)\n {\n if(cr[i])\n {\n if(cr[i] > i+1)\n {\n cr[i] = i+1;\n }\n if(dt > (i - cr[i]+1))\n {\n dt = i - cr[i] + 1;\n }\n }\n \n if(i>=dt)\n {\n cr[i]=1;\n }\n else\n {\n cr[i]=0\n }\n // print(dt)\n }\n var str=\"\";\n for(var i =0;i parseInt(x));\r\n var dt = pies, ndt;\r\n for(var i =pies-1;i>=0;i--)\r\n {\r\n if(cr[i])\r\n {\r\n if(cr[i] > i+1)\r\n {\r\n cr[i] = i+1;\r\n }\r\n if(dt > (i - cr[i]+1))\r\n {\r\n dt = i - cr[i] + 1;\r\n }\r\n }\r\n \r\n if(i>=dt)\r\n {\r\n cr[i]=1;\r\n }\r\n else\r\n {\r\n cr[i]=0\r\n }\r\n // print(dt)\r\n }\r\n var str=\"\";\r\n for(var i =0;i parseInt(x));\r\n// var a = verts[0];\r\n// var b = verts[1];\r\n// if (!graph[a]) {\r\n// graph[a] = [];\r\n// graph[a].fill(0);\r\n// vertLen[a] = 0;\r\n// }\r\n// if (!graph[b]) {\r\n// graph[b] = [];\r\n// graph[b].fill(0);\r\n// vertLen[b] = 0;\r\n// }\r\n// graph[a][b] = 1;\r\n// graph[b][a] = 1;\r\n// vertLen[a] += 1;\r\n// vertLen[b] += 1;\r\n// }\r\n\r\n// var vertToDel = [];\r\n\r\n// // print(vertLen);\r\n\r\n// var r = 0;\r\n// while (\r\n// vertLen.map((x, index) => {\r\n// if (x < k - 1 && x != -1) vertToDel.push(index);\r\n// }) &&\r\n// vertToDel.length > 0\r\n// ) {\r\n// r++;\r\n// // print(\"entered\", vertToDel, \"-\", vertLen);\r\n// for (var i = 0; i < vertToDel.length; i++) {\r\n// var vert = vertToDel[i];\r\n// graph.map((x, index) => {\r\n// if (x.length > 0) {\r\n// if (graph[index][vert] === 1) {\r\n// graph[index][vert] = 0;\r\n// vertLen[index] = vertLen[index] - 1;\r\n// }\r\n// }\r\n// });\r\n// graph[vert] = [];\r\n// vertLen[vert] = -1;\r\n// }\r\n// vertToDel = [];\r\n// }\r\n\r\n// var ind = 0;\r\n// graph.map((x, index) => {\r\n// if (x.length > 0) {\r\n// ind = index;\r\n// }\r\n// });\r\n\r\n// if(ind===0)\r\n// {\r\n// print('-1');\r\n// continue;\r\n// }\r\n// var subset = [];\r\n// var level1 = [ind];\r\n// var level2 = [];\r\n// subset = subset.concat(level1);\r\n\r\n// while (level1.length > 0) {\r\n// print(subset);\r\n// level1.forEach((x, index) => {\r\n// if (graph[x].length > 0) {\r\n// graph[x].map((x,index)=>{\r\n// if(x===1 && !subset.includes(index) && !level2.includes(index))\r\n// {\r\n// level2.push(index);\r\n// }\r\n// })\r\n// }\r\n// });\r\n// subset = subset.concat(level2);\r\n// level1= [].concat(level2);\r\n// level2 = [];\r\n// }\r\n// print(subset);\r\n}\r\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var cream = [];\r\n var low = -1;\r\n var high = -1;\r\n for (var i = 0; i < n; i++) {\r\n cream[i] = 0;\r\n if (a[i] === 0) {\r\n continue;\r\n }\r\n var bottom = i - a[i] + 1;\r\n if (bottom < 0) {\r\n bottom = 0;\r\n }\r\n if (bottom > high) {\r\n low = bottom;\r\n high = i;\r\n for (var j = low; j <= high; j++) {\r\n cream[j] = 1;\r\n }\r\n continue;\r\n }\r\n if (bottom < low) {\r\n for (var j = bottom; j < low; j++) {\r\n cream[j] = 1;\r\n }\r\n low = bottom;\r\n }\r\n for (var j = high + 1; j <= i; j++) {\r\n cream[j] = 1;\r\n }\r\n high = i;\r\n }\r\n write(cream.join(' '));\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n \r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', function(err, data) {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n });\r\n } else {\r\n var readable = process.stdin;\r\n readable.once('readable', function() {\r\n MEMORY = ('' + readable.read()).split('\\r\\n');\r\n init();\r\n });\r\n }\r\n} else {\r\n init();\r\n}\r\n \r\nfunction write(value) {\r\n isNode ? console.log(value) : print(value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "function getInt(num){\r\n return parseInt(num, 10);\r\n }\r\nvar t = parseInt(readline(), 10);\r\nfor(var it = 0; it=0; i--){\r\n counter = Math.max(line[i], counter);\r\n var res = counter > 0? 1 : 0;\r\n counter --;\r\n \r\n result.push(res);\r\n\r\n }\r\n \r\n print(result.reverse().join(' '))\r\n \r\n}\r\n\r\n"}], "negative_code": [{"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var cream = [];\r\n var low = -1;\r\n var high = -1;\r\n for (var i = 0; i < n; i++) {\r\n cream[i] = 0;\r\n if (a[i] === 0) {\r\n continue;\r\n }\r\n var bottom = i - a[i] + 1;\r\n if (bottom < 0) {\r\n bottom = 0;\r\n }\r\n if (bottom > high) {\r\n low = bottom;\r\n high = i;\r\n for (var j = low; j <= high; j++) {\r\n cream[j] = 1;\r\n }\r\n continue;\r\n }\r\n if (bottom < low) {\r\n for (var j = bottom; j < low; j++) {\r\n cream[j] = 1;\r\n }\r\n low = bottom;\r\n }\r\n for (var j = high + 1; j <= i; j++) {\r\n cream[j] = 1;\r\n }\r\n high = i;\r\n }\r\n write(cream.join(' '));\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n \r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n });\r\n } else {\r\n var readable = process.stdin;\r\n readable.once('readable', function() {\r\n MEMORY = ('' + readable.read()).split('\\r\\n');\r\n init();\r\n });\r\n }\r\n} else {\r\n init();\r\n}\r\n \r\nfunction write(value) {\r\n isNode ? console.log(value) : print(value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var cream = [];\r\n var low = -1;\r\n var high = -1;\r\n for (var i = 0; i < n; i++) {\r\n if (!a[i]) {\r\n cream[i] = 0;\r\n continue;\r\n }\r\n var bottom = Math.max(0, i - a[i] + 1);\r\n if (bottom > high) {\r\n low = bottom;\r\n high = i;\r\n for (var j = low; j <= high; j++) {\r\n cream[j] = 1;\r\n }\r\n continue;\r\n }\r\n if (bottom < low) {\r\n for (var j = bottom; j < low; j++) {\r\n cream[j] = 1;\r\n }\r\n low = bottom;\r\n }\r\n for (var j = high + 1; j <= i; j++) {\r\n cream[j] = 1;\r\n }\r\n high = i;\r\n }\r\n write(cream.join(' '));\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n \r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n });\r\n } else {\r\n var readable = process.stdin;\r\n readable.once('readable', function() {\r\n MEMORY = ('' + readable.read()).split('\\r\\n');\r\n init();\r\n });\r\n }\r\n} else {\r\n init();\r\n}\r\n \r\nfunction write(value) {\r\n isNode ? console.log(value) : print(value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "function solve() {\r\n var n = Number(read());\r\n var a = readArray(Number);\r\n var cream = a.map(x => 0);\r\n var low = -1;\r\n var high = -1;\r\n for (var i = 0; i < n; i++) {\r\n if (!a[i]) {\r\n continue;\r\n }\r\n var bottom = Math.max(0, i - a[i] + 1);\r\n if (bottom > high) {\r\n low = bottom;\r\n high = i;\r\n for (var j = low; j <= high; j++) {\r\n cream[j] = 1;\r\n }\r\n continue;\r\n }\r\n if (bottom < low) {\r\n for (var j = bottom; j < low; j++) {\r\n cream[j] = 1;\r\n }\r\n low = bottom;\r\n }\r\n for (var j = high + 1; j <= i; j++) {\r\n cream[j] = 1;\r\n }\r\n high = i;\r\n }\r\n write(cream.join(' '));\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e);\r\n }\r\n}\r\n\r\nfunction readArray(mapF) {\r\n var res = read().split(' ');\r\n if (mapF) {\r\n res = res.map(mapF);\r\n }\r\n return res;\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n \r\n var inTextName;\r\n var outTextName;\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n \r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n });\r\n } else {\r\n var readable = process.stdin;\r\n readable.once('readable', function() {\r\n MEMORY = ('' + readable.read()).split('\\r\\n');\r\n init();\r\n });\r\n }\r\n} else {\r\n init();\r\n}\r\n \r\nfunction write(value) {\r\n isNode ? console.log(value) : print(value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n if (isNode) {\r\n return MEMORY;\r\n }\r\n var res = [];\r\n var x;\r\n while (x = read()) {\r\n res.push(x);\r\n }\r\n return res;\r\n}\r\n"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve(n, arr) {\r\n for (let i = n-1; i >= 0; i--) {\r\n let count = arr[i]\r\n if(count === 0) continue\r\n for (let j = 0; j < count; j++) {\r\n if ((i - j) < 0) break\r\n arr[i - j] = 1\r\n }\r\n i -= (count-1)\r\n }\r\n console.log(arr.join(' '))\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) {\r\n solve(inputArr[i][0], inputArr[i + 1])\r\n }\r\n}"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve(n, arr) {\r\n for (let i = n-1; i >= 0; i--) {\r\n let count = arr[i]\r\n for (let j = 0; j < count; j++) {\r\n if ((i - j) < 0) break\r\n arr[i - j] = 1\r\n }\r\n i -= count\r\n }\r\n console.log(arr.join(' '))\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) {\r\n solve(inputArr[i][0], inputArr[i + 1])\r\n }\r\n}"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve(n, arr) {\r\n const res = Array(n).fill(0)\r\n for (let i = n; i !== 0; i--) {\r\n for (let j = 0; j < arr[i]; j++) {\r\n res[i - j] = 1\r\n }\r\n }\r\n console.log(res.join(' '))\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) {\r\n solve(inputArr[i][0], inputArr[i + 1])\r\n }\r\n}"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst readLine = () => dataitr.next().value.trim();\r\nfunction rl () {\r\n\tlet ans = readLine().split(' ');\r\n\tif (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));\r\n\treturn ans.length == 1 ? ans[0] : ans;\r\n}\r\n\r\nfunction main () {\r\n\r\n\tlet t = rl();\r\n\twhile (t--) {\r\n\t\tlet n = rl();\r\n\t\tlet a = rl();\r\n\r\n\t\tlet ans = Array(n).fill(0);\r\n\t\tfor (let i = n - 1, k = 0; i >= 0; i--) {\r\n\t\t\tk = Math.max(k, a[i]);\r\n\t\t\tif (k) { ans[i] = 1; k--; }\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.join(' '));\r\n\t}\r\n\r\n}\r\n\r\n"}, {"source_code": "function solve() {\r\n var numPan = readline(\"\");\r\n var array = readline(\"\").split(\" \");\r\n \r\n array.reverse();\r\nvar ans = [];\r\nvar curNum = 0;\r\n for (var elm in array) {\r\n curNum = Math.max(array[elm], curNum);\r\n if (curNum) {\r\n ans.push(1);\r\n curNum--;\r\n } else {\r\n ans.push(0);\r\n }\r\n }\r\n\r\n for (var ab=ans.length;ab>=0;ab--) {\r\n print(ans[ab]);\r\n }\r\n return \"hi\";\r\n}\r\n\r\nfunction test() {\r\nvar testCases = readline(\"\");\r\nfor (var i=0;i=0;ab--) {\r\n print(ans[ab]);\r\n }\r\n return \"hi\";\r\n}\r\n\r\nvar testCases = readline(\"\");\r\nfor (var i=0;i=0;ab--) {\r\n print(ans[ab]);\r\n }\r\n return;\r\n}\r\n\r\nvar testCases = readline(\"\");\r\nfor (var i=0;i=0;ab--) {\r\n print(ans[ab]);\r\n }\r\n}\r\n\r\nvar testCases = readline(\"\");\r\nfor (var i=0;i=0;ab--) {\r\n print(ans[ab]);\r\n }\r\n}\r\n\r\nvar testCases = readline(\"\");\r\nfor (var i=0;i parseInt(x));\r\n var dt = pies, ndt;\r\n for(var i =pies-1;i>=0;i--)\r\n {\r\n if(cr[i])\r\n {\r\n if(cr[i] > i+1)\r\n {\r\n cr[i] = i+1;\r\n }\r\n if(dt > (i - cr[i]+1))\r\n {\r\n dt = i - cr[i] + 1;\r\n }\r\n }\r\n \r\n if(i>=dt)\r\n {\r\n cr[i]=1;\r\n }\r\n else\r\n {\r\n cr[i]=0\r\n }\r\n // print(dt)\r\n }\r\n print(cr);\r\n// var n = params[0];\r\n// var m = params[1];\r\n// var k = params[2];\r\n// var graph = [];\r\n// var vertLen = [];\r\n\r\n// print(vertLen);\r\n// for (var i = 0; i < m; i++) {\r\n// var verts = readline()\r\n// .split(\" \")\r\n// .map((x) => parseInt(x));\r\n// var a = verts[0];\r\n// var b = verts[1];\r\n// if (!graph[a]) {\r\n// graph[a] = [];\r\n// graph[a].fill(0);\r\n// vertLen[a] = 0;\r\n// }\r\n// if (!graph[b]) {\r\n// graph[b] = [];\r\n// graph[b].fill(0);\r\n// vertLen[b] = 0;\r\n// }\r\n// graph[a][b] = 1;\r\n// graph[b][a] = 1;\r\n// vertLen[a] += 1;\r\n// vertLen[b] += 1;\r\n// }\r\n\r\n// var vertToDel = [];\r\n\r\n// // print(vertLen);\r\n\r\n// var r = 0;\r\n// while (\r\n// vertLen.map((x, index) => {\r\n// if (x < k - 1 && x != -1) vertToDel.push(index);\r\n// }) &&\r\n// vertToDel.length > 0\r\n// ) {\r\n// r++;\r\n// // print(\"entered\", vertToDel, \"-\", vertLen);\r\n// for (var i = 0; i < vertToDel.length; i++) {\r\n// var vert = vertToDel[i];\r\n// graph.map((x, index) => {\r\n// if (x.length > 0) {\r\n// if (graph[index][vert] === 1) {\r\n// graph[index][vert] = 0;\r\n// vertLen[index] = vertLen[index] - 1;\r\n// }\r\n// }\r\n// });\r\n// graph[vert] = [];\r\n// vertLen[vert] = -1;\r\n// }\r\n// vertToDel = [];\r\n// }\r\n\r\n// var ind = 0;\r\n// graph.map((x, index) => {\r\n// if (x.length > 0) {\r\n// ind = index;\r\n// }\r\n// });\r\n\r\n// if(ind===0)\r\n// {\r\n// print('-1');\r\n// continue;\r\n// }\r\n// var subset = [];\r\n// var level1 = [ind];\r\n// var level2 = [];\r\n// subset = subset.concat(level1);\r\n\r\n// while (level1.length > 0) {\r\n// print(subset);\r\n// level1.forEach((x, index) => {\r\n// if (graph[x].length > 0) {\r\n// graph[x].map((x,index)=>{\r\n// if(x===1 && !subset.includes(index) && !level2.includes(index))\r\n// {\r\n// level2.push(index);\r\n// }\r\n// })\r\n// }\r\n// });\r\n// subset = subset.concat(level2);\r\n// level1= [].concat(level2);\r\n// level2 = [];\r\n// }\r\n// print(subset);\r\n}\r\n"}], "src_uid": "807c5ec37b0ea83ef40550698f1ff498"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$. The string $$$s$$$ consists of lowercase Latin letters and at most one wildcard character '*', the string $$$t$$$ consists only of lowercase Latin letters. The length of the string $$$s$$$ equals $$$n$$$, the length of the string $$$t$$$ equals $$$m$$$.The wildcard character '*' in the string $$$s$$$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $$$s$$$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $$$s$$$ to obtain a string $$$t$$$, then the string $$$t$$$ matches the pattern $$$s$$$.For example, if $$$s=$$$\"aba*aba\" then the following strings match it \"abaaba\", \"abacaba\" and \"abazzzaba\", but the following strings do not match: \"ababa\", \"abcaaba\", \"codeforces\", \"aba1aba\", \"aba?aba\".If the given string $$$t$$$ matches the given string $$$s$$$, print \"YES\", otherwise print \"NO\".", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$) — the length of the string $$$s$$$ and the length of the string $$$t$$$, respectively. The second line contains string $$$s$$$ of length $$$n$$$, which consists of lowercase Latin letters and at most one wildcard character '*'. The third line contains string $$$t$$$ of length $$$m$$$, which consists only of lowercase Latin letters.", "output_spec": "Print \"YES\" (without quotes), if you can obtain the string $$$t$$$ from the string $$$s$$$. Otherwise print \"NO\" (without quotes).", "sample_inputs": ["6 10\ncode*s\ncodeforces", "6 5\nvk*cup\nvkcup", "1 1\nv\nk", "9 6\ngfgf*gfgf\ngfgfgf"], "sample_outputs": ["YES", "YES", "NO", "NO"], "notes": "NoteIn the first example a wildcard character '*' can be replaced with a string \"force\". So the string $$$s$$$ after this replacement is \"codeforces\" and the answer is \"YES\".In the second example a wildcard character '*' can be replaced with an empty string. So the string $$$s$$$ after this replacement is \"vkcup\" and the answer is \"YES\".There is no wildcard character '*' in the third example and the strings \"v\" and \"k\" are different so the answer is \"NO\".In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string $$$t$$$ so the answer is \"NO\"."}, "positive_code": [{"source_code": "readline();\nvar str = readline();\nvar a = str.split('*');\nvar b = readline();\nif (b.substring(0,a[0].length) === a[0] && ((a.length == 2)?(b.substring(b.length-a[1].length,b.length) === a[1]) && str.length-1<=b.length:str.length === b.length)){\n print('YES')\n}else{\n print('NO')\n}"}, {"source_code": "var lengths = readline();\n\nvar length1 = parseInt(lengths.split(\" \")[0])\nvar length2 = parseInt(lengths.split(\" \")[1])\n\nvar string = readline();\nvar string1 = readline();\nvar p = false;\n\nprint(check());\n\nfunction check() {\n if (length1 >= length2 + 2) {\n return \"NO\";\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[i] === \"*\") {\n p = true;\n break;\n }\n if (string1[i] !== string[i]) {\n return \"NO\";\n }\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[length1-i] === \"*\") {\n p = true;\n break;\n }\n if (string1[length2-i] !== string[length1-i]) {\n return \"NO\";\n }\n }\n\n if (!p && length1 !== length2) {\n return \"NO\";\n }\n \n return \"YES\";\n}\n"}, {"source_code": "\nfunction main() {\n const is = new Scanner();\n const [n, m] = is.nextArray(Number);\n const s = is.nextLine();\n const t = is.nextLine();\n\n const index = s.indexOf('*');\n if (index === -1 || n > m + 1) {\n console.log(s === t ? 'YES' : 'NO');\n } else {\n const left = s.substr(0, index);\n const right = s.substr(index + 1, s.length);\n let tReverse = t.slice();\n tReverse = tReverse.split('').reverse().slice(0, right.length).reverse().join('');\n if (left === t.substr(0, left.length) && right === tReverse) {\n console.log('YES');\n } else {\n console.log('NO');\n }\n }\n\n}\n\n\n/*\n * Api Scanner\n */\nclass Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n\n nextLine() {\n this.index += 1;\n return this.lines[this.index].trim();\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray(fn) {\n const array = this.nextLine().split(' ');\n return fn === String ? array : array.map(fn);\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (input) => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar str0 = \"\"\nvar str1 = \"\"\n\nvar c = 0;\nrl.on('line', function (line) {\n c += 1;\n if (c == 2) {\n str0 = line;\n }\n else if (c == 3) {\n str1 = line;\n rl.close();\n console.log(isOk() ? \"YES\" : \"NO\");\n }\n});\n\nfunction isOk() {\n if (str0.indexOf(\"*\") == -1) {\n if (str0!=str1) {return false}\n }\n var tCs = str0.split(\"\");\n var fCs = str1.split(\"\");\n var index = 0;\n var sBefore = \"\"; iStart = 0; iPos = 0; \n while (index < str0.length) {\n if (tCs[index]!=\"*\") {\n sBefore += tCs[index];\n }\n else { \n if (str1.indexOf(sBefore, iPos)!=iStart) {\n return false;\n }\n iPos = sBefore.length;\n sBefore = \"\";\n jIndex = index + 1;\n while (tCs[jIndex]!=\"*\" && jIndex < str0.length) {\n sBefore += tCs[jIndex];\n jIndex += 1;\n } \n iStart = str1.indexOf(sBefore, iPos); \n if (iStart==-1) {\n return false\n }\n index = jIndex - 1; \n if (index==str0.length-1) {\n if (!(str0[index]==\"*\" || str0[index]==fCs[str1.length-1])) { \n return false\n }\n }\n }\n index += 1;\n } \n return true;\n}\n"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar templateString = \"\"\nvar testString = \"\"\n\nvar c = 0;\nrl.on('line', function (line) {\n c += 1;\n if (c == 2) {\n templateString = line;\n }\n else if (c == 3) {\n testString = line;\n rl.close();\n console.log(isOk() ? \"yes\" : \"no\");\n }\n});\n\nfunction isOk() {\n if (templateString.indexOf(\"*\") == -1) {\n if (templateString!=testString) {return false}\n }\n var tCs = templateString.split(\"\");\n var fCs = testString.split(\"\");\n var index = 0;\n var sBefore = \"\"; iStart = 0; iPos = 0; \n while (index < templateString.length) {\n if (tCs[index]!=\"*\") {\n sBefore += tCs[index];\n }\n else { \n if (testString.indexOf(sBefore, iPos)!=iStart) {\n return false;\n }\n iPos = sBefore.length;\n sBefore = \"\";\n jIndex = index + 1;\n while (tCs[jIndex]!=\"*\" && jIndex < templateString.length) {\n sBefore += tCs[jIndex];\n jIndex += 1;\n } \n iStart = testString.indexOf(sBefore, iPos); \n if (iStart==-1) {\n return false\n }\n index = jIndex - 1; \n if (index==templateString.length-1) {\n if (!(templateString[index]==\"*\" || templateString[index]==fCs[testString.length-1])) { \n return false\n }\n }\n }\n index += 1;\n } \n return true;\n}\n"}], "negative_code": [{"source_code": "readline();\nvar str = readline();\nvar a = str.split('*');\nvar b = readline();\nif (b.indexOf(a[0]) === 0 && ((a.length == 2)?(b.lastIndexOf(a[1])+a[1].length === b.length)&&str.length-1<=b.length:true)){\n print('YES')\n}else{\n print('NO')\n}"}, {"source_code": "var lengths = readline();\n\nvar length1 = parseInt(lengths.split(\" \")[0])\nvar length2 = parseInt(lengths.split(\" \")[1])\n\nvar string = readline();\nvar string1 = readline();\n\nprint(check());\n\nfunction check() {\n if (length1 > length2 + 2) {\n return \"NO\";\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[i] === \"*\") {\n break;\n }\n if (string1[i] !== string[i]) {\n return \"NO\";\n }\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[length1-i] === \"*\") {\n break;\n }\n if (string1[length2-i] !== string[length1-i]) {\n return \"NO\";\n }\n }\n \n return \"YES\";\n}\n"}, {"source_code": "var lengths = readline();\n\nvar length1 = parseInt(lengths.split(\" \")[0])\nvar length2 = parseInt(lengths.split(\" \")[1])\n\nvar string = readline();\nvar string1 = readline();\n\nprint(check());\n\nfunction check() {\n if (length1 >= length2 + 2) {\n return \"NO\";\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[i] === \"*\") {\n break;\n }\n if (string1[i] !== string[i]) {\n return \"NO\";\n }\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[length1-i] === \"*\") {\n break;\n }\n if (string1[length2-i] !== string[length1-i]) {\n return \"NO\";\n }\n }\n \n return \"YES\";\n}\n"}, {"source_code": "var lengths = readline();\n\nvar length1 = parseInt(lengths.split(\" \")[0])\nvar length2 = parseInt(lengths.split(\" \")[1])\n\nvar string = readline();\nvar string1 = readline();\n\nprint(check());\n\nfunction check() {\n if (length1 > length2 + 2) {\n return \"NO\";\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[i] === \"*\") {\n break;\n }\n if (string1[i] !== string[i]) {\n print(string1[i] + ' 2 ' + string[i])\n return \"NO\";\n }\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[length1-i] === \"*\") {\n break;\n }\n if (string1[length2-i] !== string[length1-i]) {\n print(string1[length2-i] + ' 4 ' + string[length1-i])\n return \"NO\";\n }\n }\n \n return \"YES\";\n}\n"}, {"source_code": "var lengths = readline();\n\nvar length1 = parseInt(lengths.split(\" \")[0])\nvar length2 = parseInt(lengths.split(\" \")[1])\n\nvar string = readline();\nvar string1 = readline();\n\nprint(check());\n\nfunction check() {\n if (length1 > length2 + 2) {\n return \"NO\";\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[i] === \"*\") {\n break;\n }\n if (string1[i] !== string[i]) {\n print(string1[i] + ' 2 ' + string[i])\n return \"NO\";\n }\n }\n \n for (var i = 0; i < length1; i++) {\n if (string[length1-i] === \"*\") {\n break;\n }\n if (string1[length2-i] !== string[length1-i]) {\n return \"NO\";\n }\n }\n \n return \"YES\";\n}\n"}, {"source_code": "\nfunction main() {\n const is = new Scanner();\n const [n, m] = is.nextArray(Number);\n const s = is.nextLine();\n const t = is.nextLine();\n\n const index = s.indexOf('*');\n if (index === -1) {\n console.log(s === t ? 'YES' : 'NO');\n } else {\n const left = s.substr(0, index);\n const right = s.substr(index + 1, s.length);\n let tReverse = t.slice();\n tReverse = tReverse.split('').reverse().slice(0, right.length).reverse().join('');\n if (left === t.substr(0, left.length) && right === tReverse) {\n console.log('YES');\n } else {\n console.log('NO');\n }\n }\n\n}\n\n\n/*\n * Api Scanner\n */\nclass Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n\n nextLine() {\n this.index += 1;\n return this.lines[this.index].trim();\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray(fn) {\n const array = this.nextLine().split(' ');\n return fn === String ? array : array.map(fn);\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (input) => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar str0 = \"\"\nvar str1 = \"\"\n\nvar c = 0;\nrl.on('line', function (line) {\n c += 1;\n if (c == 2) {\n str0 = line;\n }\n else if (c == 3) {\n str1 = line;\n rl.close();\n console.log(isOk() ? \"YES\" : \"NO\");\n }\n});\n\nfunction isOk() {\n if (str0.indexOf(\"*\") == -1) {\n if (str0!=str1) {return false}\n }\n var tCs = str0.split(\"\");\n var fCs = str1.split(\"\");\n var index = 0;\n var sBefore = \"\"; iStart = 0; iPos = 0; \n while (index < str0.length) {\n if (tCs[index]!=\"*\") {\n sBefore += tCs[index];\n }\n else { \n if (str1.indexOf(sBefore, iPos)!=iStart) {\n return false;\n }\n iPos = sBefore.length;\n sBefore = \"\";\n jIndex = index + 1;\n while (tCs[jIndex]!=\"*\" && jIndex < str0.length) {\n sBefore += tCs[jIndex];\n jIndex += 1;\n } \n iStart = str1.indexOf(sBefore, iPos); \n if (iStart==-1) {\n return false\n }\n index = jIndex - 1; \n if (index==str0.length-1) {\n if (!(str0[index]==\"*\" || str0[index]==fCs[str1.length-1])) { \n return false\n }\n }\n }\n index += 1;\n }\n console.log(sBefore);\n \n return true;\n}\n"}], "src_uid": "d629d09782a7af0acc359173ac4b4f0a"} {"nl": {"description": "Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \\dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \\le x \\le n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \\le n < 10^{100}$$$). This integer is given without leading zeroes.", "output_spec": "For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.", "sample_inputs": ["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"], "sample_outputs": ["1\n2\n9\n10\n26"], "notes": "NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \\le x \\le n$$$, $$$\\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \\le x \\le n$$$, $$$\\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$. "}, "positive_code": [{"source_code": "'use strict'\n\nlet t = readline();\n\nwhile(t--)\n{\n let n = readline();\n print(n.length);\n}"}, {"source_code": "var t = +readline();\n\nfor (var i = 0; i < t; i++) {\n var l = readline();\n \n print(l.length);\n}\n"}, {"source_code": "var tc = parseInt(readline());\nfor (; tc--;){\n var s = readline();\n print(s.length);\n}"}, {"source_code": "\nfunction task(input){\n\tlet ia = input.trim().split('\\n');\n\tlet t = +ia.shift();\n\tfor (let i = 0; i < t; i++) {\n\t\tlet n = ia.shift().trim()\n\t\tlet x = n.length\n\t\tconsole.log(x)\n\t}\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on('end', _ => { \n task(inputString); \n});\n\n"}, {"source_code": "const solve = (n) => {\n console.log(n.length);\n};\n\nconst main = () => {\n const readline = require('readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n let input = [];\n rl.on('line', (line) => {\n input.push(line);\n });\n rl.on('close', () => {\n let t = Number(input[0]);\n let i = 1;\n while (t > 0) {\n solve(input[i]);\n t--;\n i++;\n }\n });\n};\n\nmain()"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const n = readLine();\n console.log(n.length);\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = []; var outputList = [];\nread.on('line', function(input){\n\tvar tmp = input.split(' ');\n\tfor(var i = 0; i < tmp.length; i++){\n\t\tinLine.push(tmp[i]);\n\t}\n});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n\tconsole.log(myconv(outputList, 9));\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextArray(size, code){\n\tvar ret = new Array(size);\n\tfor(var i = 0; i < size; i++){\n\t\tif(code == 'int'){\n\t\t\tret[i] = nextInt();\n\t\t}else{\n\t\t\tret[i] = next();\n\t\t}\n\t}\n\treturn ret;\n}\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\nfunction nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){outputList.push(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = next();\n\t\tvar count = N.length;\n\t\t/*if(N[N.length - 1] == \"0\"){\n\t\t\tcount++;\n\t\t}*/\n\t\tmyout(count);\n\t}\n}\n\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n });\n \n let i = 1;\n let t = 0;\n readline.on('line', line => {\n if (i == 1) {\n // number of test case\n t = parseInt(line) \n i++;\n } else if (i <= t) {\n solve(line)\n i++;\n } else {\n solve(line)\n readline.close()\n }\n });\n\n function solve(input) {\n console.log(input.length)\n }"}, {"source_code": "function run(sol) {\n let i = ''\n process.stdin.on('data', c => i += c)\n process.stdin.on('end', () => {\n const {EOL} = require('os')\n const inputs = i.split(EOL)\n sol(inputs)\n })\n}\n\nfunction solution(inputs) {\n const t = Number(inputs[0])\n for (let i = 1; i <= t; ++i) {\n console.log(inputs[i].length)\n }\n\n}\n\nrun(solution)\n"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;it-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(p){if(s=i.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),i.default.writeFileSync(\"output.txt\",l),console.log(l),i.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{o+=t})),process.stdin.on(\"end\",(e=>{s=o.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function f(){return a().split(\" \").map((t=>parseFloat(t)))}function c(){return a().split(\"\")}e.default={runMain:h,runEachTest:t=>{h((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:a,nextNumbers:f,nextBigNumbers:function(){return a().split(\" \").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let s = io.readline()\n// \n// io.puts(s.length)\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "/*\n * File Created: Monday, 30th November 2020 3:31:00 pm\n * Author: Lukas Rimkus\n */\n\n'use-strict'\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet data = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', chunk => {\ndata += chunk;\n});\n\nprocess.stdin.on('end', () =>{\n data = data.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n let testCases = parseInt(data.shift());\n\n while(testCases--) {\n\n const n = data.shift();\n\n const res = a(n);\n\n console.log(res)\n }\n});\n\nfunction get_ints() { \n return data.shift().split(' ').map(Number);\n}\n \nfunction readLine() { \n return data[currentLine++];\n}\n \n\nfunction a(num)\n{\n return num.length ;\n}\n\nmodule.exports = a;"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const x = readline();\n var answer = []\n\n\n Array(Number(x)).fill(1).map((t, i)=>{\n var line = readline();\n console.log(line.length)\n })\n\n}\n\n"}], "negative_code": [{"source_code": "\n\nfunction task(input){\n\tlet ia = input.trim().split('\\n');\n\tlet t = +ia.shift();\n\tfor (let i = 0; i < t; i++) {\n\t\tlet n = ia.shift()\n\t\tconsole.log(n.length)\n\t}\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on('end', _ => { \n task(inputString); \n});\n\n"}, {"source_code": "\n\nfunction task(input){\n\tlet ia = input.trim().split('\\n');\n\tlet t = +ia.shift();\n\tfor (let i = 0; i < t; i++) {\n\t\tlet n = ia.shift()\n\t\tlet x = n.length\n\t\tconsole.log(x)\n\t}\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on('end', _ => { \n task(inputString); \n});\n\n"}, {"source_code": "\n\nfunction task(input){\n\tlet ia = input.trim().split('\\n');\n\tlet t = +ia.shift();\n\tfor (let i = 0; i < t; i++) {\n\t\tlet n = ia.shift()\n\t\tconsole.log([...n].length)\n\t}\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\nprocess.stdin.on('end', _ => { \n task(inputString); \n});\n\n"}, {"source_code": "const solve = (n) => {\n console.log(n.length);\n};\n\nconst main = () => {\n const readline = require('readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n let input = [];\n rl.on('line', (line) => {\n input.push(line);\n });\n rl.on('close', () => {\n let t = Number(input[0][0]);\n let i = 1;\n while (t > 0) {\n solve(input[i]);\n t--;\n i++;\n }\n });\n};\n\nmain()"}], "src_uid": "ea011f93837fdf985f7eaa7a43e22cc8"} {"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$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 100$$$) — the number of heroes. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$), where $$$a_i$$$ is the initial level of the $$$i$$$-th hero.", "output_spec": "For each test case, print one integer — 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": "var t = readline();\r\n for(var i = 0 ; i < t ; i++){\r\n var n = readline(),\r\n a = readline().split(' ').sort((a,b) => a-b),\r\n winners = a.filter((hero)=>{\r\n return hero!= a[0];\r\n });\r\n print(winners.length);\r\n }"}, {"source_code": "var t = readline();\r\n for(var i = 0 ; i < t ; i++){\r\n var n = readline(),\r\n a = readline().split(' ').sort((a,b) => a-b),\r\n winnrers = a.filter((hero)=>{\r\n return hero!= a[0];\r\n });\r\n print(winnrers.length);\r\n }"}, {"source_code": "var tests = +readline();\nwhile(tests>0){\n var arrLen = +readline();\n var arr = readline().split(\" \").map(x=> parseInt(x));\n arr.sort((a,b)=>a-b);\n\n var i=0;\n var res = 0;\n\n while(i {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split(\" \").map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let minCount = 1;\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n minCount = 1;\r\n }\r\n else if (arrLevels[i] == min) {\r\n minCount++;\r\n }\r\n }\r\n return arrLevels.length - minCount;\r\n}"}, {"source_code": "//required remainder\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var a = lines[0];\n var lowest = 0;\n var answer = 0;\n for(var j = 1; j < (Number(a) + 1) * 2; j++){\n lowest = 0;\n answer = 0;\n if(j % 2 === 0){\n var n = lines[j].split(' ').map(Number).sort(function(a, b){return a - b});\n lowest = n[0];\n for(var k = 1; k < n.length; k++){\n if(lowest < n[k]){\n answer++;\n }\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var a = lines[0];\n var lowest = 0;\n var answer = 0;\n for(var j = 1; j < (Number(a) + 1) * 2; j++){\n lowest = 0;\n answer = 0;\n if(j % 2 === 0){\n var n = lines[j].split(' ').map(Number).sort(function(a, b){return a - b});\n lowest = n[0];\n for(var k = 1; k < n.length; k++){\n if(lowest < n[k]){\n answer++;\n }\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "function solve(input) {\r\n // YOUR BUGS HERE...\r\n res = [];\r\n input.forEach(e => {\r\n let a = e[1].split(' ').map(o => parseInt(o));\r\n let min_a = Math.min(...a);\r\n let res = a.filter(data => (data - min_a) > 0)\r\n console.log(res.length);\r\n });\r\n // console.log(res.join('\\n'));\r\n}\r\n\r\n/** =========== DEFAULT FORMAT ==============\r\n * \r\n * */ \r\nfunction set_n_line() {\r\n // set return 0 if the problem needs dynamic n line inputs\r\n // set return n > 0 if the problem needs fixed n line inputs\r\n return 2\r\n}\r\nconst readline = require('readline').createInterface({ input: process.stdin });\r\nlet inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();\r\nfunction fillInput(line) {\r\n // dynamic n_line\r\n if (n_line_subinput === 0) n_line_subinput = parseInt(line)\r\n else if (sub_input.length < n_line_subinput) {\r\n sub_input.push(line)\r\n if (sub_input.length == n_line_subinput) {\r\n inputs.push(sub_input); sub_input = []; \r\n n_line_subinput = set_n_line();\r\n }\r\n }\r\n}\r\n\r\nreadline.on('line', line => {\r\n if (t === 0) t = parseInt(line)\r\n else if (inputs.length < t) {\r\n fillInput(line)\r\n if (inputs.length == t) { solve(inputs);readline.close() }\r\n }\r\n});\r\n/* =========== DEFAULT FORMAT END ============== */\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tlist.sort(function(a,b){\r\n\t\t\treturn a - b;\r\n\t\t});\r\n\t\tvar output = 0;\r\n\t\tfor(var j = 0; j < N - 1; j++){\r\n\t\t\tif(list[j] < list[j + 1]){\r\n\t\t\t\toutput = N - (j + 1);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}"}, {"source_code": "/*\r\n * File Created: Tuesday, 16th February 2021 2:01:47 pm\r\n * Author: Lukas Rimkus\r\n */\r\n\r\n 'use-strict'\r\n \r\n process.stdin.resume();\r\n process.stdin.setEncoding('utf8');\r\n \r\n let data = '';\r\n let currentLine = 0;\r\n \r\n process.stdin.on('data', chunk => {\r\n data += chunk;\r\n });\r\n \r\n process.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n \r\n let testCases = parseInt(data.shift());\r\n \r\n while(testCases--) {\r\n \r\n const l = parseInt(readLine());\r\n\r\n const an = readLine().split(' ').map(Number);\r\n \r\n const res = a(l, an);\r\n \r\n console.log(res)\r\n }\r\n });\r\n \r\n function get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n }\r\n \r\n function readLine() { \r\n return data[currentLine++];\r\n }\r\n\r\n function a(n,a){\r\n a.sort((a,b) => a - b);\r\n let count = 0;\r\n for(let i = 0 ; i < n; i++){\r\n if(i === n - 1) break;\r\n if(a[i] !== a[i+1]){\r\n return n - i - 1;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\nmodule.exports = a;"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n/**\r\n2\r\n3 7\r\n24 25 27\r\n10 7\r\n51 52 53 54 55 56 57 58 59 60\r\n**/\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n};\r\n\r\nfunction lcm(a, b) {\r\n return (a / gcd(a, b) * b);\r\n}\r\n\r\nfunction main() { \r\n let n = Number(readline());\r\n\r\n for(let r=0;r min) {\r\n //console.log(a[i], max);\r\n count++;\r\n }\r\n }\r\n\r\n console.log(count);\r\n\r\n}\r\n\r\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const inputs=+readline();\n\n for(let j = 0; j < inputs; j++) {\n const number_of_heroes = +readline();\n const heroes = readline().split(\" \");\n\n let number_of_values = [];\n heroes.forEach((item, i) => {\n if(+item !== Math.min(...heroes)) number_of_values.push(+item);\n });\n foo(number_of_values.length)\n }\n\n}\n\nconst foo = (x) => console.log(x);\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n var x = Number(readline())\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var n = parseInt(readline())\r\n\r\n var a = readline().split(' ').map((x, i) => {\r\n return parseInt(x)\r\n })\r\n var min = a[0]\r\n for (var i = 0; i < n; i++) {\r\n if (a[i] < min) {\r\n min = a[i]\r\n }\r\n }\r\n var res = n\r\n for (var i = 0; i < n; i++) {\r\n if(a[i] === min) res--\r\n }\r\n console.log(res)\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n\r\n\r\n"}], "negative_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split(\" \").map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let minCount = 0;\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n minCount = 1;\r\n }\r\n else if (arrLevels[i] == min) {\r\n minCount++;\r\n }\r\n }\r\n return arrLevels.length - minCount;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split(\" \").map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let minCount = 1;\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n minCount = 1;\r\n }\r\n else if (arrLevels == min) {\r\n minCount++;\r\n }\r\n }\r\n return arrLevels.length - minCount;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split(\" \").map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let minCount = 0;\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n minCount = 1;\r\n }\r\n else if (arrLevels == min) {\r\n minCount++;\r\n }\r\n }\r\n return arrLevels.length - minCount;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split(\" \").map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let minCount = 0;\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n minCount = 1;\r\n }\r\n else if (arrLevels) {\r\n minCount++;\r\n }\r\n }\r\n return arrLevels.length - minCount;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split(\" \").map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let minCount = 0;\r\n let max = arrLevels[0];\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n minCount = 1;\r\n }\r\n else if (arrLevels) {\r\n minCount++;\r\n }\r\n if (arrLevels[i] > max) {\r\n max = arrLevels[i];\r\n }\r\n }\r\n return (max === min) ? 0 : arrLevels.length - minCount;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = readline();\r\n let arrLevel = readline().split(\" \").map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let max = arrLevels[0];\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n }\r\n if (arrLevels[i] > max) {\r\n max = arrLevels[i];\r\n }\r\n }\r\n return (max === min) ? 0 : arrLevels.length - 1;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split().map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n console.log(arrLevels);\r\n let min = arrLevels[0];\r\n let max = arrLevels[0];\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n }\r\n if (arrLevels[i] > max) {\r\n max = arrLevels[i];\r\n }\r\n }\r\n return (max === min) ? 0 : arrLevels.length - 1;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n readline();\r\n let arrLevel = readline().split().map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let max = arrLevels[0];\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n }\r\n if (arrLevels[i] > max) {\r\n max = arrLevels[i];\r\n }\r\n }\r\n return (max === min) ? 0 : arrLevels.length - 1;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let arrLevel = readline().split().map(string => { return parseInt(string) });\r\n console.log(getWinners(arrLevel));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let max = arrLevels[0];\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n }\r\n if (arrLevels[i] > max) {\r\n max = arrLevels[i];\r\n }\r\n }\r\n return (max === min) ? 0 : arrLevels.length - 1;\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\n\r\nprocess.stdin.on(\"data\", rawData => {\r\n standardInputString += rawData;\r\n});\r\n\r\nprocess.stdin.on(\"end\", _ => {\r\n standardInputString = standardInputString.trim().split(\"\\n\").map(line => {\r\n return line.trim();\r\n })\r\n main();\r\n});\r\n\r\nfunction main() {\r\n let arrLevels = [];\r\n let testCases = +(readline());\r\n for (let i = 0; i < testCases.length; i++) {\r\n readline();\r\n arrLevels.push(readline().split(\" \").map(string => { return parseInt(string) }));\r\n }\r\n for (let i = 0; i < arrLevels.length; i++) {\r\n console.log(getWinners(arrLevels[i]));\r\n }\r\n}\r\nfunction getWinners(arrLevels) {\r\n let min = arrLevels[0];\r\n let max = arrLevels[0];\r\n\r\n for (let i = 1; i < arrLevels.length; i++) {\r\n if (arrLevels[i] < min) {\r\n min = arrLevels[i];\r\n }\r\n if (arrLevels[i] > max) {\r\n max = arrLevels[i];\r\n }\r\n }\r\n return (max === min) ? 0 : arrLevels.length - 1;\r\n}"}, {"source_code": "//required remainder\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var a = lines[0];\n var lowest = 0;\n var answer = 0;\n for(var j = 1; j < (Number(a) + 1) * 2; j++){\n lowest = 0;\n answer = 0;\n if(j % 2 === 0){\n var n = lines[j].split(' ').sort(function(a, b){return a - b});\n lowest = n[0];\n for(var k = 1; k < n.length; k++){\n if(lowest < n[k]){\n answer++;\n }\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "//required remainder\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var a = lines[0];\n var lowest = 0;\n var answer = 0;\n for(var j = 1; j < (Number(a) + 1) * 2; j++){\n lowest = 0;\n answer = 0;\n if(j % 2 === 0){\n var n = lines[j].split(' ').sort(function(a, b){return a - b});\n lowest = n[0];\n for(var k = 1; k < n.length + 1; k++){\n if(lowest < n[k]){\n answer++;\n }else{\n continue;\n }\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "//required remainder\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var a = lines[0];\n var lowest = 0;\n var answer = 0;\n for(var j = 1; j < (Number(a) + 1) * 2; j++){\n lowest = 0;\n answer = 0;\n if(j % 2 === 0){\n var n = lines[j].split(' ').sort(function(a, b){return a - b});\n lowest = n[0];\n for(var k = 1; k < n.length + 1; k++){\n if(lowest < n[k]){\n answer++;\n }\n }\n console.log(answer);\n }\n }\n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var k = lines[0];\n var answer = '';\n var a = 0;\n var b = 0;\n for(var j = 1; j < Number(k) + 1; j++){\n var n = lines[j];\n a = 0;\n b = 0;\n answer = '';\n if(n % 4 !== 0){\n console.log('NO');\n }else{\n console.log('YES');\n for(i = 2; i <= n; i += 2){\n answer += i + ' ';\n a += i;\n }\n for(i = 1; i < n - 2; i += 2){\n answer += i + ' ';\n b += i;\n }\n console.log(answer + (a-b));\n }\n }\n});"}, {"source_code": "function solve(input) {\r\n // YOUR BUGS HERE...\r\n res = [];\r\n input.forEach(e => {\r\n let a = e[1].split(' ').map(o => parseInt(o));\r\n a.sort();\r\n let res = a.filter(data => (data - a[0]) > 0)\r\n console.log(res.length);\r\n });\r\n}\r\n\r\n/** =========== DEFAULT FORMAT ==============\r\n * \r\n * */ \r\nfunction set_n_line() {\r\n return 2\r\n}\r\nconst readline = require('readline').createInterface({ input: process.stdin });\r\nlet inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();\r\nfunction fillInput(line) {\r\n // dynamic n_line\r\n if (n_line_subinput == 0) n_line_subinput = parseInt(line)\r\n else if (sub_input.length < n_line_subinput) {\r\n sub_input.push(line)\r\n if (sub_input.length == n_line_subinput) {\r\n inputs.push(sub_input); sub_input = []; \r\n n_line_subinput = set_n_line();\r\n }\r\n }\r\n}\r\n\r\nreadline.on('line', line => {\r\n if (t == 0) t = parseInt(line)\r\n else if (inputs.length < t) {\r\n fillInput(line)\r\n if (inputs.length == t) { solve(inputs);readline.close() }\r\n }\r\n});\r\n/* =========== DEFAULT FORMAT END ============== */\r\n"}], "src_uid": "99e5c907b623c310d6f1599f485ca21d"} {"nl": {"description": "A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].After each query you have to determine whether the number of inversions is odd or even.", "input_spec": "The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct. The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process. Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.", "output_spec": "Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.", "sample_inputs": ["3\n1 2 3\n2\n1 2\n2 3", "4\n1 2 4 3\n4\n1 1\n1 4\n1 4\n2 3"], "sample_outputs": ["odd\neven", "odd\nodd\nodd\neven"], "notes": "NoteThe first example: after the first query a = [2, 1, 3], inversion: (2, 1); after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2). The second example: a = [1, 2, 4, 3], inversion: (4, 3); a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3); a = [1, 2, 4, 3], inversion: (4, 3); a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). "}, "positive_code": [{"source_code": "const getInversionsCount = (nums) => {\n var count = 0;\n\n for (var i = 1; i < nums.length; i++) {\n for (var j = 0; j < i; j++) {\n if (nums[i] < nums[j]) {\n count++;\n }\n }\n }\n\n return count;\n};\n\nconst main = () => {\n readline();\n\n const nums = readline()\n .split(\" \")\n .map((i) => Number(i));\n\n var operationsCount = getInversionsCount(nums);\n\n const inputCount = Number(readline());\n\n for (var i = 0; i < inputCount; i++) {\n var input = readline()\n .split(\" \")\n .map((i) => Number(i));\n\n operationsCount += Math.floor((input[1] - input[0] + 1) / 2);\n\n if (operationsCount % 2 === 0) {\n print(\"even\");\n } else {\n print(\"odd\");\n }\n }\n};\n\nmain();"}, {"source_code": "// https://en.wikipedia.org/wiki/Parity_of_a_permutation\nvar line = readline ();\nline = line.trim ().split ( ' ' );\nvar n = line;\nvar aa = [ ];\nline = readline ();\naa = line.trim ().split ( ' ' );\nvar i, j, cnt = 0;\nvar a = aa;\na.map ( function ( a ) { return (+ a); } ); // convert array elements to numbers\nfunction merge ( a, b ) {\n var i = 0, j = 0;\n var result = [ ];\n while ( i < a.length && j < b.length ) {\n if ( (+ a [ i ]) < (+ b [ j ]) ) {\n result.push ( a [ i ++ ] );\n } else {\n result.push ( b [ j ++ ] );\n cnt += a.length - i;\n }\n }\n while ( i < a.length ) {\n result.push ( a [ i ++ ] );\n }\n while ( j < b.length ) {\n result.push ( b [ j ++ ] );\n cnt += a.length - i;\n }\n return result;\n}\nfunction mergesort ( arr ) {\n var suba = [ ], subb = [ ];\n if ( arr.length > 1 ) {\n suba = mergesort ( arr.slice ( 0, Math.floor ( arr.length / 2 ) ) );\n subb = mergesort ( arr.slice ( Math.floor ( arr.length / 2 ), arr.length ) );\n return merge ( suba, subb ); \n } \n return arr;\n}\nmergesort ( a );\nvar parity = cnt % 2;\nvar m = (+ readline ());\nvar l, r;\nfor ( var g = 0; g < m; g ++ ) {\n line = readline ();\n line = line.trim ().split ( ' ' );\n l = line [ 0 ];\n r = line [ 1 ];\n if ( Math.ceil ( (r - l) / 2) % 2 == 1 ) parity ^= 1; \n print ( parity ? 'odd' : 'even' );\n}\n"}], "negative_code": [{"source_code": "// https://en.wikipedia.org/wiki/Parity_of_a_permutation\nvar line = readline ();\nline = line.trim ().split ( ' ' );\nvar n = line;\nvar aa = [ ];\nline = readline ();\naa = line.trim ().split ( ' ' );\nvar i, j, cnt = 0;\nfor ( i = 0; i < n - 1; i ++ ) \n for ( j = i + 1; j < n; j ++ ) \n if ( aa [ i ] > aa [ j ] ) cnt ++;\nvar parity = cnt % 2;\nvar m = (+ readline ());\nvar l, r;\nfor ( var g = 0; g < m; g ++ ) {\n line = readline ();\n line = line.trim ().split ( ' ' );\n l = line [ 0 ];\n r = line [ 1 ];\n if ( Math.ceil ( (r - l) / 2) % 2 == 1 ) parity ^= 1; \n print ( parity ? 'odd' : 'even' );\n}\n"}], "src_uid": "d20cc952cdf3a99e7d980a0270c49f78"} {"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 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively. The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.", "output_spec": "Print a single integer — 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 + 1 + 2 = 4.In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11."}, "positive_code": [{"source_code": "var x = readline().split(\" \");\nvar rost = readline().split(\" \");\nvar res = 0;\n\tfor (var i=0; i+x[1]? res=+res+2:res++\n\t}\nprint(res);"}, {"source_code": "var sol = function(arr1, arr2){\n number = arr2.length;\n for(var i=0; i arr1[1]){\n number ++;\n }\n }\n print(number);\n}\n\nvar numbers1 = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar numbers2 = readline().split(\" \").map(function(x) { return parseInt(x); });\n\nsol(numbers1, numbers2);"}, {"source_code": "var input = readline().split(' ').map(Number);\nvar numberOfFriends = input[0];\nvar fenceHight = input[1];\n\nvar friends = readline().split(' ').map(Number);\nvar roadWidth = 0;\n\nfor(var i = 0; i < friends.length; i++){\n if(friends[i] > fenceHight){\n roadWidth += 2;\n }\n else {\n roadWidth ++;\n }\n}\nprint(roadWidth);"}, {"source_code": "var h = readline().split(\" \").map(function(x) { return parseInt(x); })[1];\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar w = 0;\nfor (var i = 0; i < a.length; i++) {\n w+=(a[i] > h) ? 2 : 1;\n}\nprint (w);"}, {"source_code": "var n_H= readline().split(' ');\nvar a=readline().split(' ');\nvar width=0;\nn_H[1]=parseInt(n_H[1]);\nfor(i=0;in_H[1])\n width+=2;\n else\n width+=1;\n\n}\n\nprint(width);"}, {"source_code": "var nh = readline().split(\" \");\n var a = readline().split(\" \");\n var width = 0;\n for(var i = 0; i < Number(nh[0]); i++)\n {\n if(a[i] > Number(nh[1]))\n {\n width += 2;\n }\n else\n {\n width += 1;\n }\n }\n print(width);"}, {"source_code": "var inp = readline().split(' ').map(el => parseInt(el, 10));\nvar width = 0;\nvar a = readline().split(' ').forEach(el => {\n el = parseInt(el, 10);\n if(el>inp[1]) width+=2;\n else width++;\n});\n\nprint(width);"}, {"source_code": "var line1 = readline().split(' ');\nvar n = parseInt(line1[0]);\nvar h = parseInt(line1[1]);\nvar numbers = readline().split(' ');\nfor (var i = 0; i < numbers.length; ++i)\n\tnumbers[i] = parseInt(numbers[i]);\n\nresult = 0;\n\nfor (var i = 0; i < numbers.length; ++i)\n\tresult += numbers[i] <= h ? 1 : 2;\n\nprint(result);\n"}, {"source_code": "var x= readline().split(' ');\nvar n = x[0];\nvar h = x[1];\nvar a = readline().split(\" \").map(Number);\nvar s = 0;\nfor(var i = 0; ih){\n s++;\n }\n}\nwrite(s);"}, {"source_code": "\"use strict\";\n\nvar input = readline().split(' ').map(value => +value);\nvar n = input[0];\nvar h = input[1];\nvar a = readline().split(' ').map(value => +value);\n\nwrite(a.map(a => a <= h ? 1 : 2).reduce((a, b) => a + b));"}, {"source_code": "X=readline().split(' ').map(Number)\nn=X[0],h=X[1]\nX=readline().split(' ').map(Number)\nprint(X.reduce((a,c) => a + (c<=h ? 1 : 2), 0))\n\n"}, {"source_code": "// var _i = 0;\n//\n// function readline() {\n// _i ++;\n//\n// switch (_i) {\n// case 1: return '3 7';\n// case 2: return '4 5 14';\n// }\n// }\n//\n// function write(value) {\n// console.log(value);\n// }\n\nvar list = readline().split(' ');\n\nvar n = parseInt(list[0]);\nvar h = parseInt(list[1]);\n\nvar a = readline().split(' ').map(function(currentValue) {\n return parseInt(currentValue);\n});\n\nvar s = 0;\n\na.forEach(function(currentValue) {\n s += currentValue > h ? 2 : 1;\n});\n\nwrite(s);\n"}, {"source_code": "var firstLine = readline().split(' ');\nvar number = firstLine[0];\nvar height = firstLine[1];\nvar heights = readline().split(' ').map(Number);\nvar width = 0;\nfor(var i = 0; i < number; i++){\n width++;\n if(heights[i] > height){\n width++;\n }\n}\nwrite(width);"}, {"source_code": "var input1 = readline().split(\" \");\nvar noOfFriends = +input1[0];\nvar highOfFence = +input1[1];\n\nvar hightOfFriends = readline().split(\" \");\n\nvar totalWidth = 0;\n\nfor (var i = 0; i < noOfFriends; i++) {\n if (hightOfFriends[i] <= highOfFence) {\n totalWidth += 1;\n } else {\n totalWidth += 2;\n }\n}\nprint(totalWidth);"}, {"source_code": "var first = readline().split(\" \")\nvar friendsList = readline().split(' ');\nvar n = first[0], h = first[1];\nvar counter = 0;\nfor(var i = 0; i < n; ++i){\n if(+friendsList[i] > +h) counter+=2;\n else counter+=1;\n}\nprint(counter);"}, {"source_code": "var inp_line1 = readline();\nvar inp_line2 = readline();\n \n \n \nvar inp_line1_arr = inp_line1.split(\" \");\nvar inp_line2_arr = inp_line2.split(\" \");\n \nvar min_width = 0;\n \nfor (var i=0; i<=inp_line1_arr[0] - 1 ; i++){\n if (parseInt(inp_line2_arr[i]) <= parseInt(inp_line1_arr[1])) {\n min_width = min_width + 1;\n } else {\n min_width = min_width + 2;\n }\n}\n \nwrite(min_width);\n"}, {"source_code": "var X= readline().split(' ').map(Number)\nvar total=X[0],h=X[1]\nX=readline().split(' ').map(Number)\nprint (X.reduce((a,c) => a + (c<=h ? 1 : 2), 0))"}, {"source_code": " var n = readline().split(\" \");var load = readline().split(\" \");\n var max = 0;\nfor(var i=0;i(+n[1]) ? max+=2 : max+=1;\nprint(max)"}, {"source_code": "var row = readline().split(\" \").map(x => parseInt(x));\nvar friends = row[0];\nvar height = row[1];\n \nvar individualHeight = readline().split(\" \").map(x => parseInt(x));\n \nvar sum = 0;\n \nfor (var i = 0; i < individualHeight.length; i++) {\n if (individualHeight[i] > height) {\n sum += 2;\n } else {\n sum += 1;\n }\n}\n \n print(sum);"}, {"source_code": "var n_H= readline().split(' ');\nvar a=readline().split(' ');\nvar width=0;\nn_H[1]=parseInt(n_H[1]);\n for(i=0;in_H[1])\n width+=2\n else\n width+=1\n }\nprint(width)"}, {"source_code": "var print = this.print || require('lol-io').print\nvar write = this.write || require('lol-io').write\nvar readline = this.readline || require('lol-io').readline\n\nvar arr1=readline().split(' ').map((a)=>{ return parseInt(a)});\nvar arr=readline().split(' ').map((a)=>{ return parseInt(a)});\nvar count=0;\nfor(var i=0;iarr1[1]){\n count++;\n }\n count++;\n}\n\nprint(count);\n"}, {"source_code": "const readline = require(\"readline\");\n\nlet inputs = [];\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.on(\"line\", line => inputs.push(line));\n\nrl.on(\"close\", () => console.log(solution(inputs)));\n\nfunction solution(data) {\n const xs = data.flatMap(x => x.split(\" \"));\n [n, h, ...friendsHeight] = xs;\n return friendsHeight.reduce((width, fh) => {\n return parseInt(fh) > h\n ? width + 2\n : width + 1\n }, 0);\n};\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n\n let numFriends, fenceHeight;\n\n rl.on('line', n => {\n if (!numFriends && !fenceHeight) {\n n = n.split(' ').map(Number);\n numFriends = n[0];\n fenceHeight = n[1];\n } else {\n const width = n.split(' ').map(Number).reduce((acc, curr) => {\n return curr > fenceHeight ? acc + 2 : acc + 1;\n }, 0);\n console.log(width);\n rl.close();\n }\n });\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet numFriends, fenceHeight;\n\nrl.on('line', n => {\n if (!numFriends && !fenceHeight) {\n n = n.split(' ').map(Number);\n numFriends = n[0];\n fenceHeight = n[1];\n } else {\n const width = n.split(' ').map(Number).reduce((acc, curr) => {\n return curr > fenceHeight ? acc + 2 : acc + 1;\n }, 0);\n console.log(width);\n rl.close();\n }\n});"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const line1 = readline().split(' '), line2 = readline().split(' ')\n\n let h = parseInt(line1[1]),widthOfRoad = 0;\n\n for (let heightOfPerson of line2){\n heightOfPerson = parseInt(heightOfPerson)\n widthOfRoad += (heightOfPerson > h) ? 2 : 1;\n }\n\n console.log(widthOfRoad)\n}\n\n\n"}, {"source_code": "var all, fh, lines, mainAux, print, readline, rl, rli, sum, write;\n\nrl = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nprint = console.log;\n\nwrite = function(...args) {\n return process.stdout.write(args.join(' '));\n};\n\nlines = [];\n\nrl.on('line', function(line) {\n return lines.push(line);\n});\n\nrl.on('close', main);\n\nrli = 0;\n\nreadline = function() {\n return lines[rli++];\n};\n\nsum = function(items) {\n return items.reduce(function(a, b) {\n return a + b;\n });\n};\n\nall = function(items) {\n var i, item, len;\n for (i = 0, len = items.length; i < len; i++) {\n item = items[i];\n if (!item) {\n return false;\n }\n }\n return true;\n};\n\nfh = function(n, f, hs) {\n var h;\n return sum((function() {\n var i, len, results;\n results = [];\n for (i = 0, len = hs.length; i < len; i++) {\n h = hs[i];\n if (h > f) {\n results.push(2);\n } else {\n results.push(1);\n }\n }\n return results;\n })());\n};\n\nmainAux = function() {\n var f, hs, n;\n [n, f] = readline().split(' ').map(function(n) {\n return parseInt(n);\n });\n hs = readline().split(' ').map(function(n) {\n return parseInt(n);\n });\n return print(fh(n, f, hs));\n};\n\n\n function main() {\n return mainAux();\n }\n;\n"}, {"source_code": "var lines, mainAux, minwidth, print, readline, rl, rli, write;\n\nrl = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nprint = console.log;\n\nwrite = function(...args) {\n return process.stdout.write(args.join(' '));\n};\n\nlines = [];\n\nrl.on('line', function(line) {\n return lines.push(line);\n});\n\nrl.on('close', main);\n\nrli = 0;\n\nreadline = function() {\n return lines[rli++];\n};\n\nminwidth = function(n, f, hs) {\n return hs.reduce(function(acc, h) {\n if (h > f) {\n return acc + 2;\n } else {\n return acc + 1;\n }\n }, 0);\n};\n\nmainAux = function() {\n var f, hs, n;\n [n, f] = readline().split(' ');\n hs = readline().split(' ').map(function(v) {\n return parseInt(v);\n });\n return print(minwidth(n, f, hs));\n};\n\n\n function main() {\n return mainAux();\n }\n;\n\n//# sourceMappingURL=wall-height.js.map\n"}, {"source_code": "function main() {\n // write code here:\n for(let i=0;i<2;i++){\n stdin[i]=stdin[i].split(' ').map(Number);\n }\n var arr1=stdin[0];\n var arr2=stdin[1];\n const n=arr1[0];\n const h=arr1[1];\n var minWidth=0;\n for(let j=0;jh){\n minWidth+=2;\n }else{\n minWidth+=1;\n }\n }\n console.log(minWidth);\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({input: process.stdin});\nvar stdin = [];\nrl.on('line', function (line) {\n stdin.push(line);\n});\nrl.on('close', main);"}, {"source_code": "const readline = require(\"readline\")\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet fenceHeight = 0;\nlet noOfFriends = 0;\nlet roadWidth = 0;\nrl.on(\"line\", (input) => {\n if(!noOfFriends&&!fenceHeight){\n noOfFriends = input.split(\" \")[0];\n fenceHeight = input.split(\" \")[1];\n }\n else{\n let arrayofHeights = input.split(\" \").map((element)=>{\n return element*1\n })\n arrayofHeights.forEach(element => {\n if(element>fenceHeight)\n roadWidth+=2\n else \n roadWidth++\n });\n console.log(roadWidth)\n rl.close();\n // if (element > fenceHeight){\n\n\n // roadWidth+=2\n // console.log(\"First Condition \")\n // }\n // else{\n // roadWidth++\n // console.log(\"Second Condition \")\n // }\n \n } \n \n});"}, {"source_code": "\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const x = readline().split(\" \");\n \n const x2 = readline().split(\" \").map(x=>+x);\n vanyaAndFence(x[0],x[1],x2);\n }\n \nfunction vanyaAndFence(n, h, guys) {\n console.log(guys.reduce((prev, curr) => (curr > h ? prev + 2 : prev + 1), 0));\n\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var one = nextIntArray();\n var N = one[0];\n var H = one[1];\n var list = nextIntArray();\n var output = 0;\n for(var i = 0; i < N; i++){\n if(list[i] > H){\n output += 2;\n }else{\n output++;\n }\n }\n myout(output);\n}\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet h = 0,\n lineCounter = 0;\n\nlet hArr = [];\n\nrl.on('line', (input) => {\n let line;\n if (lineCounter === 0) {\n line = input.split(' ');\n h = parseInt(line[1]);\n lineCounter++;\n } else {\n line = input.split(' ');\n line.forEach(element => {\n hArr.push(parseInt(element));\n });\n rl.close();\n console.log(solve(h, hArr));\n }\n});\n\n\nconst solve = (h, hArr) => {\n let sum = 0;\n hArr.forEach(element => {\n sum = (element > h) ? sum + 2 : sum + 1;\n });\n return sum;\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n const [, h] = readline().split(' ').map(x => parseInt(x));\n const a = readline().split(' ').map(x => parseInt(x));\n\n // solve\n const w = a.map(x => x > h ? 2 : 1).reduce((m, n) => m + n, 0);\n\n // output\n print(w);\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet counter = 0;\nlet n, k;\n\nrl.on('line', (d) => {\n if (counter === 0) {\n counter++;\n [n, k] = d.split(' ').map(Number);\n return;\n }\n\n let f = d.split(' ').map(Number);\n let ans = n;\n\n for (let i = 0; i < f.length; i++) {\n ans += f[i] > k;\n }\n\n console.log(ans);\n\n counter++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet counter = 0;\nlet n, k;\n\nrl.on('line', (d) => {\n if (counter === 0) {\n counter++;\n [n, k] = d.split(' ').map(Number);\n return;\n }\n\n let f = d.split(' ').map(Number);\n let ans = 0;\n\n for (let i = 0; i < f.length; i++) {\n if (f[i] > k) {\n ans += 2;\n }\n else {\n ans += 1;\n }\n }\n\n console.log(ans);\n\n counter++;\n});\n"}, {"source_code": "/**\n * \nVanya 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 \neach 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. \nThe height of the i-th person is equal to ai.\n\nConsider 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\n 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\n by the guard?\n\nInput\nThe first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.\n\nThe second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.\n\nOutput\nPrint a single integer — the minimum possible valid width of the road.\n\nExamples\ninput\n3 7\n4 5 14\noutput\n4\ninput\n6 1\n1 1 1 1 1 1\noutput\n6\ninput\n6 5\n7 6 8 9 10 5\noutput\n11\nNote\nIn the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.\n\nIn the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.\n\nIn the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfPersons = Number(inputString[0].split(\" \")[0])\n let heigtOfWall = Number(inputString[0].split(\" \")[1]);\n let heigtOfPersons = inputString[1].split(\" \")\n\n solution(numberOfPersons, heigtOfWall, heigtOfPersons);\n\n});\n\n\nfunction solution(numberOfPersons, heigtOfWall, heigtOfPersons) {\n\n let widthOfRoad = numberOfPersons;\n\n for (let index = 0; index < numberOfPersons; index++) {\n\n if (Number(heigtOfPersons[index]) > heigtOfWall)\n widthOfRoad++;\n\n }\n\n console.log(widthOfRoad);\n\n}"}, {"source_code": "\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n\nfunction main() {\n const arr1 = readline().split(\" \");\n let numberOfPersons = +arr1[0];\n let height = +arr1[1];\n let personsHeight = readline().split(\" \");\n\n let total = 0;\n\n for (let i = 0; i < numberOfPersons; i++) {\n if (personsHeight[i] <= height) {\n total++;\n }\n else {\n total += 2;\n }\n }\n console.log(total);\n}"}, {"source_code": "const readLine = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadLine.on('line', line => input.push(line));\n\nreadLine.on('close', () => {\n let answer = 0;\n let [n, h] = input[0].split(' ').map(x => parseInt(x));\n const nums = input[1].split(' ').map(x => parseInt(x));\n\n nums.forEach(i => {\n if (i > h) answer += 2;\n else answer += 1;\n });\n console.log(answer);\n});"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n\t input: process.stdin,\n\t output: process.stdout,\n\tterminal : false\n});\n\n\nvar firstLine = 0\nvar h, n, a\nrl.on(\"line\", (w)=>{\n\tif(firstLine === 0){\n\t\tvar r = w.split(\" \")\n\t\tn = r[0]\n\t\th = r[1]\n\t\tfirstLine++\n\t\treturn\n\t}\n\t\n\ta = w.split(\" \")\n\n\tvar width = n\n\n\tfor(var i = 0; i < a.length; i++){\n\t\tif(parseInt(a[i]) > parseInt(h)){\n\t\t\twidth++\n\t\t}\n\t}\n\n\n\n\tconsole.log(width)\t\t\n})\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('');\nrl.prompt();\nlet promptCounter = 0\n\nlet n, h;\n\nrl.on('line', function (line) {\n promptCounter++;\n //first line\n if (promptCounter === 1) {\n [n, h] = line.split(' ').map(x => Number(x));\n rl.prompt();\n } else {\n let rowWidth = line.split(' ').map(x => Number(x)).map(x => {\n if (x > h) return 2;\n else return 1;\n }).reduce((p, c) => p + c);\n console.log(rowWidth);\n rl.close()\n }\n});"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.question('', function (firstLine) {\n // rl.write('hello\\n')\n let [n, h] = firstLine.split(' ').map(x => Number(x))\n rl.setPrompt('');\n rl.prompt();\n rl.on('line', function (lengths) {\n let arr = lengths.split(' ').map(x => Number(x));\n let rowLength = arr.map(x => {\n if (x > h) return 2;\n else return 1;\n }).reduce((p, c) => p + c)\n // rl.write(String(rowLength));\n console.log(rowLength);\n rl.close();\n })\n});"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n // if(Array.isArray(inputString)) inputString = inputString.join('\\n');\n inputString += inputStdin;\n // inputString = inputString.trim().split('\\n').map(string => {\n // return string.trim();\n // });\n \n // main(); \n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readAsInt(){\n return parseInt(readline());\n}\n\nfunction readAsIntList(){\n return readline().trim().split(' ').filter(i => i).map(i => parseInt(i));\n}\n\n\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n let [n, h] = readAsIntList();\n let list = readAsIntList();\n console.log(list.map(a => a > h ? 2 : 1).reduce((acc,v) => acc+v,0));\n}\n \n\n\n"}, {"source_code": "let rl = require(\"readline\");\n\nlet prompts = rl.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\nlet noOfFriends;\nlet highOfFence;\n\nprompts.question(\"\", function (input) {\n let input1 = input.split(\" \");\n noOfFriends = +input1[0];\n highOfFence = +input1[1];\n prompts.question(\"\", function (hightOfFriends) {\n hightOfFriends = hightOfFriends.split(\" \");\n let totalWidth = 0;\n for (let i = 0; i < noOfFriends; i++) {\n if (hightOfFriends[i] <= highOfFence) {\n totalWidth += 1;\n } else {\n totalWidth += 2;\n }\n }\n console.log(totalWidth);\n process.exit();\n });\n});\n"}, {"source_code": "/**\n * @author Sunwarul\n * Software Developer \n*/ \n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', inputStd => {\n inputString += inputStd;\n});\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => {\n return str.trim();\n });\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n\tconst [n, h] = readLine().split(' ').map(Number);\n\tconst friends = readLine().split(' ').map(Number);\n\tlet totalNeeded = 0;\n\tfor(let i in friends) {\n\t\tif(friends[i] > h) {\n\t\t\ttotalNeeded = totalNeeded + 2;\n\t\t} else {\n\t\t\t++totalNeeded;\n\t\t}\n\t}\n\tconsole.log(totalNeeded);\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet currentLine = 0;\nlet inputString = \"\";\n\nprocess.stdin.on(\"data\", (raw_data) => {\n inputString += raw_data;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((line) => {\n return line.trim();\n });\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n/******** Main function*************/\n\nfunction main() {\n var [n, h] = readLine().split(\" \").map(Number);\n var arr = readLine().split(\" \").map(Number);\n var sum = 0;\n arr.map((item) => (sum += Math.ceil(item / h)));\n\n console.log(sum);\n}\n"}, {"source_code": "let fs = require('fs');\n\nlet txt = fs.readFileSync(0, \"utf-8\").split(\"\\r\\n\").filter(data => {\n return data.length > 0;\n});\n\nfor (let i = 0; i < txt.length; i+=2) {\n let info =txt[i].split(\" \");\n doit(info[1] * 1, txt[i+1].split(\" \").filter(data => {\n return data.length > 0;\n }));\n}\n\nfunction doit(n, tab) {\n let sum=0;\n tab.forEach(element => {\n if(element<=n){\n ++sum;\n }else{\n sum+=2;\n }\n });\n console.log(sum);\n \n}"}, {"source_code": "// Sample code to perform I/O:\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n main(stdin_input);\n});\n\nfunction main(input) {\n let output = nameLookUp(input);\n process.stdout.write(output); // Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\n// Write your code here\nfunction nameLookUp(str) {\n let inputs = str.trim().split('\\n');\n let fenceHeight = inputs[0].split(' ')[1].trim();\n let friendsHeight = inputs[1].trim().split(' ');\n let sumWidth = 0;\n for (let row of friendsHeight) {\n if (+row > +fenceHeight) {\n sumWidth += 2;\n }\n else {\n sumWidth += 1;\n }\n }\n return sumWidth.toString();\n}\n"}, {"source_code": "const readLine = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadLine.on('line', line => input.push(line));\nconst fence = () => {\n let [n,h] = input[0].split(' ').map(x => +x);\n let ar = input[1].split(' ').map(x => +x);\n let count = ar.length;\n for (const y of ar) {\n if (y > h) {\n count++;\n }\n }\n console.log(count);\n};\n\nreadLine.on('close', fence);"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let nh = readLine().split(' ').map(value => parseInt(value));\n let n = nh[0];\n let h = nh[1];\n let arr = readLine().split(' ').map(value => parseInt(value));\n let ans = 0;\n for (var i = 0; i < n; i++) {\n if (arr[i] > h) {\n ans += 2;\n } else ans += 1;\n }\n console.log(ans);\n}"}, {"source_code": "var input = readline().split(\" \").map(Number), n = input[0], h = input[1], a = readline().split(\" \").map(Number);\n\nvar ans = 0;\nfor(var i = 0; i < n; ++i){\n ans++;\n if(a[i] > h){\n ans++;\n }\n}\n\nwrite(ans);"}, {"source_code": "var input1 = readline().split(\" \").map(x=>parseInt(x));\nvar n = input1[0];\nvar h = input1[1];\nvar heights = []\nheights = readline().split(\" \").map(x => parseInt(x));\n \n \nfunction performTask(n, h, heights) {\n return heights.reduce((width, height) => {\n return width + (height > h ? 2 : 1);\n }, 0)\n}\n \nconst output = performTask(n, h, heights);\nprint(output);"}, {"source_code": "x = readline().split(' ').map(Number);n=x[0];h=x[1];\nprint(n + readline().split(' ').map(Number).filter(i => i > h).length);\n"}, {"source_code": "x = readline().split(' ').map(Number);\nprint(readline().split(' ').map(Number).reduce((res, i) => res + (i > x[1]), x[0]));\n"}, {"source_code": "var num1=readline().split(\" \").map(x=>parseInt(x));\nvar n =num1[0];\nvar h =num1[1];\n\nvar num2=readline().split(\" \").map(x=>parseInt(x));\nvar width = 0;\nfor(var i=0 ; ih){\n width++;\n }\n width++;\n}\n\nprint(width);"}, {"source_code": "n = readline().split(\" \")\nfr = readline().split(\" \")\nvar counter = 0\nfor (i=0 ; in[1]){\n counter++\n }\n}\nprint(counter+Number(n[0]))\n"}, {"source_code": "m=readline()\ny=m.split(' ')[0]\nz=parseInt(m.split(' ')[1])\nx=readline().split(' ')\nsum=0;\nfor(i=0;iz)\n sum=sum+2;\nelse\n sum=sum+1;\n }\nprint(sum)"}, {"source_code": "var line1 = readline().split(\" \");\nvar n = parseInt(line1[0]);\nvar h = parseInt(line1[1]);\n\nvar roadWidth = 0;\n\nvar heights = readline().split(\" \");\n\nfor (var i = 0; i < n; i++) {\n \n if (parseInt(heights[i]) > h) {\n roadWidth += 2;\n } else {\n roadWidth++;\n }\n \n}\n\nprint(roadWidth);"}, {"source_code": "var num = readline().split(' ').map(Number);\n\tvar str = readline().split(' ').map(function(elem) {\n\t\treturn parseInt(elem);\n\t});\n\tvar n = num[0];\n\tvar h = num[1];\n\tvar sum = n;\n\tfor(var i = 0; i < str.length; i++)\n\t{\n\t\tif(str[i] > h){\n\t\t\tsum += 1;\n\t\t}\n\t}\n\tprint(sum);"}, {"source_code": "var input = readline().split(\" \")\nvar people = readline().split(\" \").map(Number);\nvar roadWidth = 0\n \nfor (var i = 0; i < input[0]; i++) {\n if (people[i] > input[1]) {\n roadWidth += 2\n } else {\n roadWidth += 1\n }\n}\n \nprint(roadWidth)"}, {"source_code": "var line1 = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\nvar n = line1[0]; // to store values in different variables. \nvar h = line1[1];\n\n \nvar line2 = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\n\n\n \nvar result = 0; \nfor(var i =0; i < n; i++) {\n result += line2[i] <= h ? 1 : 2;\n}\nprint(result)"}, {"source_code": "function Input() {\n var heightOfFence;\n readline().split(' ').forEach(function (element) {\n heightOfFence = parseInt(element);\n });\n\n const listFriends = readline().split(' ').map(function (element) {\n return parseInt(element);\n });\n\n return {\n heightOfFence: heightOfFence,\n listFriends: listFriends\n };\n}\n\nfunction PossibleWidth(data) {\n var possibleWidth = 0;\n data.listFriends.forEach(function (element) {\n ++possibleWidth;\n if (element > data.heightOfFence) {\n ++possibleWidth;\n }\n });\n return possibleWidth;\n}\n\nvar data = Input();\nprint(PossibleWidth(data));"}, {"source_code": "var line1 = readline().split(' ').map(function (x) { return parseInt(x); })\nvar line2 = readline().split(' ').map(function (x) { return parseInt(x); })\nvar h = line1[1]\nvar result = 0\nline2.forEach(x => {\n x < h ? result++: result += Math.ceil(x/h)\n})\nprint(result)"}, {"source_code": "var input = readline().split(\" \").map(x=>parseInt(x));\nvar num_friends = input[0];\nvar height_of_fence = input[1];\nvar friends_height = readline().split(\" \").map(x=>parseInt(x));\nvar width = 0;\nfor(var i = 0; iheight_of_fence)width+=2;\n else width++;\n}\nprint(width);"}, {"source_code": "// parameter \"input\" gets all data\nfunction Main() {\n\t// the first line is assigned to input[0], the second line is assigned to input[1] similarly.\t\n\tinput = readline().split(\" \").map(function(x) { return parseInt(x); });\n\ta = readline().split(\" \").map(function(x) { return parseInt(x); });\n\tconst n = input[0];\n\tconst h = input[1];\n\tconst ans = a.reduce((cum,x)=>cum+(x>h?2:1),0);\n\tprint(ans);\n\t\n}\n\nMain()"}, {"source_code": "var res = sol(readline(), readline());\nprint(res);\n\nfunction sol(line, friends) {\n var input = line.split(\" \");\n var height = friends.split(\" \");\n\n var n = input[0];\n var heightOfFence = Number(input[1]);\n\n var width = 0;\n\n for (var i = 0; i < n; i++) {\n if (Number(height[i]) > heightOfFence) {\n width += 2;\n }else{\n width++;\n }\n }\n\n return width;\n}"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\nvar friends = num[0]; // to store values in different variables. \nvar height = num[1];\nvar heights = readline().split(\" \").map(x => parseInt(x));\nvar score = 0;\nfor (var i =0;i< friends;i++) {\n if (heights[i] > height) {\n score+=2;\n } else {\n score+=1;\n }\n}\nprint(score)"}, {"source_code": "var nk = readline().split(\" \").map(x => Number(x));\nvar n = nk[0];\nvar k = nk[1];\nvar lengths = readline().split(\" \").map(x => Number(x));\n\nvar width = 0;\nfor(var i = 0; i < lengths.length; i++){\n\twidth++;\n\tif(lengths[i] > k)\n\t\twidth++;\n}\n\nprint(width);\n"}, {"source_code": "var a=readline().split(\" \");\nn=a[0];\nm=a[1];\nvar cnt=0;\nvar arr = readline().split(\" \").map(Number);\nfor( var i=0;i < n;i ++ ){\n if( arr[i]>m )\n cnt=cnt+2;\n else\n cnt++;\n}\nprint(cnt);"}, {"source_code": "var s = readline().split(\" \");\nvar n = Number(s[0]), h = Number(s[1]);\n s = readline().split(\" \");\n var count = n;\nfor(var i=0; i h) {\n count++;\n }\n}\nprint(count);"}, {"source_code": "var input = readline().split(' ').map(Number);\n\nvar n = input[0];\nvar h = input[1];\n\nvar friends = readline().split(' ').map(Number);\nvar road = n;\n\nfor (var i = 0; i < friends.length; i++) {\n\tif (friends[i] > h) {\n\t\troad += 1;\n\t}\n}\n\nprint(road);"}, {"source_code": "(function() {\n 'use strict';\n const n = readline().split(' ').map(Number);\n const z = readline().split(' ').map(Number);\n let w = 0;\n for (let i = 0; i < n[0]; ++i) {\n if (z[i] > n [1]) {\n w += 2; \n } else {\n w += 1;\n }\n }\n print(w);\n}());"}, {"source_code": "var firstLine = readline().split(' ');\nvar fenceHeight = firstLine[1];\nvar heightArray = readline().split(' ').map(x => parseInt(x));\nvar minWidth = heightArray.reduce((minWidth, height) => {\n if(height > fenceHeight) return minWidth += 2;\n else return minWidth += 1;\n}, 0);\n\nprint(minWidth);"}, {"source_code": "var fenceHeight = readline().split(' ')[1];\nvar heightArray = readline().split(' ').map(x => parseInt(x));\nvar minWidth = heightArray.reduce((minWidth, height) => {\n if(height > fenceHeight) return minWidth += 2;\n else return minWidth += 1;\n}, 0);\n\nprint(minWidth);"}, {"source_code": "var arr1 = readline().split(' ');\nvar arr = readline().split(' ');\nvar res = 0, n = +arr1[0], h = +arr1[1];\n\nfor(var i = 0; i < n; i++) {\n if (+arr[i] <= h) {\n res++;\n } else {\n res+=2;\n }\n}\n\nprint(res);\n"}, {"source_code": "const main = () => {\n const n = readline().trim().split(' ').map(x => parseInt(x));\n const arr = readline().trim().split(\" \").map(x => parseInt(x));\n const h = n[1];\n var total = 0;\n \n for (p of arr) {\n if (p > h) {\n total += 2;\n continue;\n }\n total++;\n }\n\n print(total);\n};\nmain();"}, {"source_code": "var g = readline();\ng = g.split(\" \");\nvar y = readline();\ny = y.split(\" \");\nvar n = Number(g[0]);\nvar h = Number(g[1]);\nvar j = n;\nfor(i=0;i h){\n j++;\n }\n}\nprint(j);"}, {"source_code": "var H = readline().split(' ').map(x=>parseInt(x))[1]\nvar ar = readline().split(' ').map(x=>parseInt(x))\nprint( ar.length + ar.filter(h=>(h>H)).length )\n"}, {"source_code": "// parameter \"input\" gets all data\nfunction Main() {\n\t// the first line is assigned to input[0], the second line is assigned to input[1] similarly.\t\n\tinput = readline().split(\" \").map(function(x) { return parseInt(x); });\n\ta = readline().split(\" \").map(function(x) { return parseInt(x); });\n\tconst n = input[0];\n\tconst h = input[1];\n\tconst ans = a.reduce((cum,x)=>cum+(x>h?2:1),0);\n\tprint(ans);\n\t\n}\n \nMain()"}, {"source_code": "'use strict';\nconst data = readline().split(' ').map(value => parseInt(value)),\n n = data[0],\n h = data[1],\n array = readline().split(' ').map(value => parseInt(value)); \nlet res = n; \n\nfor (let i = 0; i < n; i++) {\n if (array[i] > h) {\n res++;\n }\n}\n\nwrite(res); "}, {"source_code": "var nh = readline().split(' ');\nvar n = parseInt(nh[0]);\nvar h = parseInt(nh[1]); \nvar a = readline().split(' ');\nvar need = 0;\nfor (var i = 0; i < a.length; i++) {\n if (a[i] <= h) {\n need++;\n } else {\n need+=2;\n }\n}\nprint (need)"}], "negative_code": [{"source_code": "var x = readline();\nvar rost = readline();\nvar res = 0;\n\tfor (var i=0; i<+x[0]; i++){\n\t\trost[i]>+x[1]? res+2: res++\n\t}\nprint(res);"}, {"source_code": "var x = readline().split(\" \");\nvar rost = readline().split(\" \");\nvar res = 0;\n\tfor (var i=0; i=+x[1]? res=+res+2:res++\n\t}\nprint(res);"}, {"source_code": "var nh = readline().split(\" \");\nvar a = readline().split(\" \");\nvar width = 0;\nfor(var i = 0; i < nh[0]; i++)\n{\n if(a[i] > nh[1])\n {\n width += 2;\n }\n else\n {\n width += 1;\n }\n}\nprint(width);"}, {"source_code": "var x= readline().split(' ');\nvar n = x[0];\nvar h = x[1];\nvar a = readline().split(\" \").map(Number);\nvar s = 0;\nfor(var i = 0; ih){\n s++;\n }\n}"}, {"source_code": "\"use strict\";\n\nvar input = readline().split(' ').map(value => +value);\nvar n = input[0];\nvar h = input[1];\nvar a = readline().split(' ').map(value => +value);\n\nwrite(a.map(a => a < h ? 1 : 2).reduce((a, b) => a + b));"}, {"source_code": "var firstLine = readline().split(' ');\nvar number = firstLine[0];\nvar height = firstLine[1];\nvar heights = readline().split(' ');\nvar width = 0;\nfor(var i = 0; i < number; i++){\n width++;\n if(heights[i] > height){\n width++;\n }\n}\nwrite(width);"}, {"source_code": "var first = readline().split(\" \")\nvar friendsList = readline().split(' ');\nvar n = first[0], h = first[1];\nvar counter = 0;\nfor(var i = 0; i < n; ++i){\n if(friendsList[i] > h) counter+=2;\n else counter+=1;\n}\nprint(n,h,friendsList)\nprint(counter);"}, {"source_code": "var first = readline().split(\" \")\nvar friendsList = readline().split(' ');\nvar n = first[0], h = first[1];\nvar counter = 0;\nfor(var i = 0; i < n; ++i){\n if(friendsList[i] > h) counter+=2;\n else counter+=1;\n}\nprint(counter);"}, {"source_code": "var first = readline().split(\" \")\nvar friendsList = readline().split(' ');\nvar n = first[0], h = first[1];\nvar counter = 0;\nfor(var i = 0; i < n; ++i){\n if(friendsList[i] > h) {\n counter+=2;\n print(friendsList[i], counter);\n }\n else counter+=1;\n}\nprint(counter);"}, {"source_code": "var first = readline().split(\" \")\nvar friendsList = readline().split(' ');\nvar n = first[0], h = first[1];\nvar counter = 0;\nfor(var i = 0; i < n; i++){\n if(friendsList[i] > h) counter+=2;\n else counter+=1;\n}\nprint(counter);"}, {"source_code": "var first = readline().split(\" \")\nvar friendsList = readline().split(' ');\nvar n = first[0], h = first[1];\nvar counter = 0;\nfor(var i = 0; i < n; ++i){\n print(i, friendsList[i]);\n if(friendsList[i] > h) counter+=2;\n else counter+=1;\n}\nprint(counter);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\n\nprint(num)"}, {"source_code": "var print = this.print || require('lol-io').print\nvar write = this.write || require('lol-io').write\nvar readline = this.readline || require('lol-io').readline\n\nvar arr1=readline().split(' ').map((a)=>{ return parseInt(a)});\nvar arr=readline().split(' ').map((a)=>{ return parseInt(a)});\nvar count=0;\nfor(var i=0;i=arr1[1]){\n count++;\n }\n count++;\n}\n\nprint(count);\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n\n let numFriends, fenceHeight;\n\n rl.on('line', n => {\n if (!numFriends && !fenceHeight) {\n n = n.split(' ').map(Number);\n console.log(n);\n numFriends = n[0];\n fenceHeight = n[1];\n } else {\n // const numbers = n.split(' ').map(Number);\n // console.log(numbers);\n // let width = 0;\n // for(let n of numbers){\n // (n > fenceHeight) ? width +=2 : width +=1;\n // }\n \n //console.log(width);\n const width = n.split(' ').map(Number).reduce((acc, curr) => {\n return curr > fenceHeight ? acc + 2 : acc + 1;\n }, 0);\n\n console.log(width);\n rl.close();\n }\n });\n"}, {"source_code": "var lines, mainAux, minwidth, print, readline, rl, rli, write;\n\nrl = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nprint = console.log;\n\nwrite = function(...args) {\n return process.stdout.write(args.join(' '));\n};\n\nlines = [];\n\nrl.on('line', function(line) {\n return lines.push(line);\n});\n\nrl.on('close', main);\n\nrli = 0;\n\nreadline = function() {\n return lines[rli++];\n};\n\nminwidth = function(n, f, hs) {\n return hs.reduce(function(acc, h) {\n if (h > f) {\n acc + 2;\n }\n return acc + 1;\n }, 0);\n};\n\nmainAux = function() {\n var f, hs, n;\n [n, f] = readline().split(' ');\n hs = readline().split(' ');\n return print(minwidth(n, f, hs));\n};\n\n\n function main() {\n return mainAux();\n }\n;\n\n//# sourceMappingURL=wall-height.js.map\n"}, {"source_code": "const readline = require(\"readline\")\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet fenceHeight = 0;\nlet noOfFriends = 0;\nlet arrOfHeights = [];\nlet roadWidth = 0;\nrl.on(\"line\", (input) => {\n if(!noOfFriends&&!fenceHeight){\n noOfFriends = input.split(\" \")[0];\n fenceHeight = input.split(\" \")[1];\n }\n else{\n arrOfHeights = (input.split(\" \"))\n arrOfHeights.forEach((element)=>{\n if (element>fenceHeight)\n roadWidth = roadWidth + 2 \n else\n roadWidth++\n })\n console.log(roadWidth)\n rl.close();\n } \n \n});"}, {"source_code": "const readline = require(\"readline\")\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet fenceHeight = 0;\nlet noOfFriends = 0;\nlet roadWidth = 0;\nrl.on(\"line\", (input) => {\n if(!noOfFriends&&!fenceHeight){\n noOfFriends = input.split(\" \")[0];\n fenceHeight = input.split(\" \")[1];\n }\n else{\n const arrOfHeights = input.split(\" \").map((element)=>{\n element = parseInt(element)\n if (element > fenceHeight){\n roadWidth+=2\n console.log(\"First Condition \")\n }\n else{\n roadWidth++\n console.log(\"Second Condition \")\n }\n })\n console.log(roadWidth)\n rl.close();\n } \n \n});"}, {"source_code": "const readline = require(\"readline\")\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet fenceHeight = 0;\nlet noOfFriends = 0;\nlet arrOfHeights = [];\nlet roadWidth = 1;\nrl.on(\"line\", (input) => {\n if(!noOfFriends&&!fenceHeight){\n noOfFriends = input.split(\" \")[0];\n fenceHeight = input.split(\" \")[1];\n }\n else{\n arrOfHeights = (input.split(\" \"))\n arrOfHeights.forEach((element)=>{\n if (element >= fenceHeight)\n roadWidth = roadWidth + 2 \n else\n roadWidth++\n })\n console.log(roadWidth)\n rl.close();\n } \n \n});"}, {"source_code": "const readline = require(\"readline\")\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet fenceHeight = 0;\nlet noOfFriends = 0;\nlet arrOfHeights = [];\nlet roadWidth = 0;\nrl.on(\"line\", (input) => {\n if(!noOfFriends&&!fenceHeight){\n noOfFriends = input.split(\" \")[0];\n fenceHeight = input.split(\" \")[1];\n }\n else{\n arrOfHeights = input.split(\" \").map(Number)\n console.log(\"current arrrayof heights =\" +arrOfHeights + \"\\n\")\n arrOfHeights.forEach((element)=>{\n if (element > fenceHeight){\n roadWidth = roadWidth + 2\n console.log(\"elements that passed here \\n\"+element)\n } \n else\n {\n console.log(\"elements that passed here \\n\"+element)\n roadWidth++ \n }\n })\n console.log(roadWidth)\n rl.close();\n } \n \n});"}, {"source_code": "const readline = require(\"readline\")\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet fenceHeight = 0;\nlet noOfFriends = 0;\nlet roadWidth = 0;\nrl.on(\"line\", (input) => {\n if(!noOfFriends&&!fenceHeight){\n noOfFriends = input.split(\" \")[0];\n fenceHeight = input.split(\" \")[1];\n }\n else{\n const arrOfHeights = input.split(\" \").map((element)=>{\n element = parseInt(element)\n console.log(typeof(element))\n if (element > fenceHeight){\n roadWidth+=2\n console.log(\"First Condition \")\n }\n else{\n roadWidth++\n console.log(\"Second Condition \")\n\n\n }\n })\n console.log(roadWidth)\n rl.close();\n } \n \n});"}, {"source_code": "\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const x = readline().split(\" \");\n \n const x2 = readline().split(\" \");\n vanyaAndFence(x[0],x[1],x2);\n }\n \nfunction vanyaAndFence(n, h, guys) {\n console.log(guys.reduce((prev, curr) => (curr > h ? prev + 2 : prev + 1), 0));\n\n}"}, {"source_code": "\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const x = readline().split(\" \");\n \n const x2 = readline().split(\" \").map(x=>+x);\n vanyaAndFence(x[0],x[1],x2);\n }\n \nfunction vanyaAndFence(n, h, guys) {\n console.log(n,h,guys)\n console.log(guys.reduce((prev, curr) => (curr > h ? prev + 2 : prev + 1), 0));\n\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const x = readline();\n var line2 = readline(); \n \n foo(x);\n foo(line2);\n}\nfunction foo(x) {\n process.stdout.write(\"hello: \"); // without auto '\\n' (newline)\n console.log(x); // with auto '\\n' (newline)\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n const [, h] = readline().split(' ');\n const a = readline().split(' ');\n\n // solve\n const w = a.map(x => x > h ? 2 : 1).reduce((m, n) => m + n, 0);\n\n // output\n print(w);\n}\n\n"}, {"source_code": "\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n\nfunction main() {\n const arr1 = readline().split(\" \");\n let numberOfPersons = +arr1[0];\n let height = +arr1[1];\n let personsHeight = readline().split(\" \");\n\n let total = 0;\n\n for (let i = 0; i < numberOfPersons; i++) {\n if (personsHeight[i] <= height) {\n total++;\n }\n else {\n total += 2;\n }\n }\n return total\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.question('', function (firstLine) {\n // rl.write('hello\\n')\n let [n, h] = firstLine.split(' ').map(x => Number(x));\n rl.setPrompt('');\n rl.prompt();\n rl.on('line', function (lengths) {\n let arr = lengths.split(' ').map(x => Number(x));\n let rowLength = arr.map(x => {\n if (x > h) return 2;\n else return 1;\n }).reduce((p, c) => p + c);\n rl.write(String(rowLength));\n console.log();\n rl.close();\n });\n});"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.question('', function(firstLine) {\n // rl.write('hello\\n')\n let [n, h] = firstLine.split(' ').map(x => Number(x))\n rl.prompt();\n rl.on('line', function(lengths) {\n let arr = lengths.split(' ').map(x => Number(x));\n let rowLength = arr.map(x => {\n if(x > h) return 2;\n else return 1;\n }).reduce((p, c) => p + c)\n rl.write(String(rowLength));\n console.log();\n rl.close();\n })\n});"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nrl.question('', function(firstLine) {\n let [n, h] = firstLine.split(' ').map(x => Number(x))\n rl.prompt();\n rl.on('line', function(lengths) {\n let arr = lengths.split(' ').map(x => Number(x));\n let rowLength = arr.map(x => {\n if(x > h) return 2;\n else return 1;\n }).reduce((p, c) => p + c)\n console.log(rowLength);\n rl.close();\n })\n});"}, {"source_code": "x = readline().split(' ');\nreadline().split(' ').reduce((res, i) => res + (+i > +x[1]), +x[0]);\n"}, {"source_code": "var line1 = readline();\nvar n = parseInt(line1.slice(0, 1));\nvar h = parseInt(line1.slice(2));\n\nvar roadWidth = 0;\n\nvar heights = readline().split(\" \");\n\nfor (var i = 0; i < n; i++) {\n \n if (heights[i] > h) {\n roadWidth += 2;\n } else {\n roadWidth++;\n }\n \n}\n\nprint(roadWidth);"}, {"source_code": "var n = parseInt(readline());\nvar h = parseInt(readline());\n\nvar roadWidth = 0;\n\nfor (var i = 0; i < n; i++) {\n var x = parseInt(readline());\n\n if ((x > h)) {\n roadWidth += 2;\n } else {\n roadWidth++;\n }\n}\n\nprint(roadWidth);"}, {"source_code": "var line1 = readline();\nvar n = parseInt(line1.slice(0, 1));\nvar h = parseInt(line1.slice(2));\n\nvar roadWidth = 0;\n\nvar heights = readline();\n\nvar counter = 0;\n\nfor (var i = 0; i < n; i++) {\n \n var check = parseInt(heights.slice(counter));\n \n if (check > h) {\n roadWidth += 2;\n } else {\n roadWidth++;\n }\n counter += 2;\n}\n\nprint(roadWidth);"}, {"source_code": "var n = readline();\nvar h = readline();\n\nvar roadWidth = 0;\n\nfor (var i = 0; i < n; i++) {\n var x = readline();\n if (x > h) {\n roadWidth += 2;\n } else {\n roadWidth++;\n }\n}\n\nprint(roadWidth);"}, {"source_code": "var line1 = readline().split(' ')\nvar line2 = readline().split(' ')\nvar h = line1[1]\nvar result = 0\nline2.forEach(x => {\n x < h ? result++: result += Math.ceil(x/h)\n})\nprint(result)"}, {"source_code": "var n=readline();\nprint(Math.ceil(n/5)); "}, {"source_code": "var arr1 = readline().split(' ');\nvar arr = readline().split(' ');\nvar res = 0, n = +arr1[0], h = +arr1[1];\n\nprint(h);\nfor(var i = 0; i < n; i++) {\n if (+arr[i] <= h) {\n res++;\n } else {\n res+=2;\n }\n}\n\nprint(res);\n"}, {"source_code": "var arr1 = readline().split(' ');\nvar arr = readline().split(' ');\nvar res = 0, n = arr1[0], h = arr1[1];\n\nfor(var i = 0; i < n; i++) {\n if (arr[i] <= h) {\n res++;\n } else {\n res+=2;\n }\n}\n\nprint(res);\n"}, {"source_code": "var g = readline();\ng = g.split(\" \");\nvar y = readline();\ny = y.split(\" \");\nvar n = Number(g[0]);\nvar h = Number(g[1]);\nvar min = Number(y[0]);\nvar max = min;\nvar j = n;\nvar maximum = function(){for(i=1;i h){\n j++\n }\n else if(z > min){\n max = z;\n }\n else if(z < min){\n min = z;\n }\n}\n}\nmaximum();\nif(max > h){\n j = j + 1;\n}\nprint(j);\n"}, {"source_code": "var g = readline();\ng = g.split(\" \");\nvar y = readline();\ny = y.split(\" \");\nvar n = Number(g[0]);\nvar h = Number(g[1]);\nvar min = Number(y[0]);\nvar j = n;\nfor(i=1;i h){\n j++;\n }\n else if(y[i] < min){\n min = y[i];\n }\n else if(y[i] > min){\n min = y[i];\n }\n}\nprint(j);\n"}, {"source_code": "var g = readline();\ng = g.split(\" \");\nvar y = readline();\ny = y.split(\" \");\nvar n = Number(g[0]);\nvar h = Number(g[1]);\nvar min = Number(y[0]);\nvar max = min;\nvar j = n;\nvar maximum = function(){for(i=1;i h){\n j++\n }\n}\n}\nmaximum()\nprint(j);"}, {"source_code": "var g = readline();\nvar y = readline();\ny = y.split(\" \")\ng = g.split(\" \");\nvar n = Number(g[0]);\nvar h = Number(g[1]);\nvar min = y[0];\nvar max = min;\nvar j = n;\nfor(i=1; i < y.length;i++){\n if(y[i] > min){\n max = y[i];\n }\n else if(y[i] < min){\n min = y[i];\n }\n}\nif(max > h){\n j++;\n}\nprint(j);"}, {"source_code": "var g = readline();\nvar y = readline();\ng = g.split(\" \");\ny = y.split(\" \");\nvar n = Number(g[0]);\nvar h = Number(g[1]);\nvar min = y[0];\nvar max = min;\nvar j = n;\nfor(i=1;i < y.length;i++){\n if(y[i] > min){\n max = y[i];\n }\n else{\n min = y[i];\n }\n}\nif(max > h){\n j++;\n}\nprint(j);"}, {"source_code": "var g = readline();\ng = g.split(\" \");\nvar y = readline();\ny = y.split(\" \");\nvar n = Number(g[0]);\nvar h = Number(g[1]);\nvar min = Number(y[0]);\nvar max = min;\nvar j = n;\nfor(i=1;i min){\n max = z;\n }\n else if(z < min){\n min = z;\n }\n}\nif(max > h){\n j= j + 1;\n}\nprint(j);\n"}, {"source_code": "var nh = readline().split(' ');\nvar n = parseInt(nh[0]);\nvar h = parseInt(nh[1]); \nvar a = readline().split(' ');\nvar need = 0;\nfor (var i = 0; i < a.length; i++) {\n if (a[i] < h) {\n need++;\n } else {\n need+=2;\n }\n}\nprint (need)"}, {"source_code": "var x = readline().split(\" \");\nvar rost = readline().split(\" \");\nvar res = 0;\n\tfor (var i=0; i<+x[0]; i++){\n\t\trost[i]>+x[1]? res+2: res++\n\t}\nprint(res);"}], "src_uid": "e7ed5a733e51b6d5069769c3b1d8d22f"} {"nl": {"description": "There are $$$n$$$ astronauts working on some space station. An astronaut with the number $$$i$$$ ($$$1 \\le i \\le n$$$) has power $$$a_i$$$.An evil humanoid has made his way to this space station. The power of this humanoid is equal to $$$h$$$. Also, the humanoid took with him two green serums and one blue serum.In one second , a humanoid can do any of three actions: to absorb an astronaut with power strictly less humanoid power; to use green serum, if there is still one left; to use blue serum, if there is still one left. When an astronaut with power $$$a_i$$$ is absorbed, this astronaut disappears, and power of the humanoid increases by $$$\\lfloor \\frac{a_i}{2} \\rfloor$$$, that is, an integer part of $$$\\frac{a_i}{2}$$$. For example, if a humanoid absorbs an astronaut with power $$$4$$$, its power increases by $$$2$$$, and if a humanoid absorbs an astronaut with power $$$7$$$, its power increases by $$$3$$$.After using the green serum, this serum disappears, and the power of the humanoid doubles, so it increases by $$$2$$$ times.After using the blue serum, this serum disappears, and the power of the humanoid triples, so it increases by $$$3$$$ times.The humanoid is wondering what the maximum number of astronauts he will be able to absorb if he acts optimally.", "input_spec": "The first line of each test contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — number of test cases. The first line of each test case contains integers $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — number of astronauts and $$$h$$$ ($$$1 \\le h \\le 10^6$$$) — the initial power of the humanoid. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^8$$$) — powers of astronauts. 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, in a separate line, print the maximum number of astronauts that a humanoid can absorb.", "sample_inputs": ["8\n\n4 1\n\n2 1 8 9\n\n3 3\n\n6 2 60\n\n4 5\n\n5 1 100 5\n\n3 2\n\n38 6 3\n\n1 1\n\n12\n\n4 6\n\n12 12 36 100\n\n4 1\n\n2 1 1 15\n\n3 5\n\n15 1 13"], "sample_outputs": ["4\n3\n3\n3\n0\n4\n4\n3"], "notes": "NoteIn the first case, you can proceed as follows: use green serum. $$$h = 1 \\cdot 2 = 2$$$ absorb the cosmonaut $$$2$$$. $$$h = 2 + \\lfloor \\frac{1}{2} \\rfloor = 2$$$ use green serum. $$$h = 2 \\cdot 2 = 4$$$ absorb the spaceman $$$1$$$. $$$h = 4 + \\lfloor \\frac{2}{2} \\rfloor = 5$$$ use blue serum. $$$h = 5 \\cdot 3 = 15$$$ absorb the spaceman $$$3$$$. $$$h = 15 + \\lfloor \\frac{8}{2} \\rfloor = 19$$$ absorb the cosmonaut $$$4$$$. $$$h = 19 + \\lfloor \\frac{9}{2} \\rfloor = 23$$$ "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n let [n, h] = rns(),\r\n a = rns();\r\n a.sort((a, b) => a - b);\r\n let dp = Array.from({\r\n length: 3\r\n }, () => new Array(2).fill(-Infinity));\r\n dp[2][1] = h;\r\n for (let i = 0; i < n; i++) {\r\n const tmp = Array.from({\r\n length: 3\r\n }, () => new Array(2).fill(-Infinity));\r\n let flag = true;\r\n for (let j = 0; j < 3; j++) {\r\n for (let k = 0; k < 2; k++) {\r\n if (dp[j][k] > a[i]) {\r\n tmp[j][k] = Math.max(tmp[j][k], dp[j][k] + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else {\r\n if (j && dp[j][k] * 2 > a[i]) {\r\n tmp[j - 1][k] = Math.max(tmp[j - 1][k], dp[j][k] * 2 + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else if (j > 1 && dp[j][k] * 4 > a[i]) {\r\n tmp[j - 2][k] = Math.max(tmp[j - 2][k], dp[j][k] * 4 + Math.floor(a[i] / 2));\r\n flag = false;\r\n }\r\n if (k && dp[j][k] * 3 > a[i]) {\r\n tmp[j][k - 1] = Math.max(tmp[j][k - 1], dp[j][k] * 3 + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else if (k && j && dp[j][k] * 6 > a[i]) {\r\n tmp[j - 1][k - 1] = Math.max(tmp[j - 1][k - 1], dp[j][k] * 6 + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else if (k && j > 1 && dp[j][k] * 12 > a[i]) {\r\n tmp[j - 2][k - 1] = Math.max(tmp[j - 2][k - 1], dp[j][k] * 12 + Math.floor(a[i] / 2));\r\n flag = false;\r\n }\r\n }\r\n }\r\n }\r\n if (flag) return i;\r\n dp = tmp;\r\n }\r\n return n;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n let s = solve(r);\r\n if (s === undefined) s = '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, v] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, v, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, v, arr) {\n arr.sort((a, b) => a - b)\n return Math.max(\n helper(v, arr, [2, 2, 3]),\n helper(v, arr, [2, 3, 2]),\n helper(v, arr, [3, 2, 2]),\n )\n}\nfunction helper(v, arr, order) {\n let r = 0\n for (let x of arr) {\n let ok = 1\n while (v <= x) {\n if (order.length) {\n v *= order.shift()\n } else {\n ok = 0\n break\n }\n // console.log(v, x)\n }\n if (!ok) break\n v += Math.floor(x / 2)\n r++\n }\n return r\n}\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n let [n, h] = rns(),\r\n a = rns();\r\n a.sort((a, b) => a - b);\r\n let dp = Array.from({\r\n length: 3\r\n }, () => new Array(2).fill(-Infinity));\r\n dp[2][1] = h;\r\n for (let i = 0; i < n; i++) {\r\n const tmp = Array.from({\r\n length: 3\r\n }, () => new Array(2).fill(-Infinity));\r\n let flag = true;\r\n for (let j = 0; j < 3; j++) {\r\n for (let k = 0; k < 2; k++) {\r\n if (dp[j][k] > a[i]) {\r\n tmp[j][k] = Math.max(tmp[j][k], dp[j][k] + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else {\r\n if (j && dp[j][k] * 2 > a[i]) {\r\n tmp[j - 1][k] = Math.max(tmp[j - 1][k], dp[j][k] * 2 + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else if (j > 1 && dp[j][k] * 4 > a[i]) {\r\n tmp[j - 1][k] = Math.max(tmp[j - 1][k], dp[j][k] * 4 + Math.floor(a[i] / 2));\r\n flag = false;\r\n }\r\n if (k && dp[j][k] * 3 > a[i]) {\r\n tmp[j][k - 1] = Math.max(tmp[j][k - 1], dp[j][k] * 3 + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else if (k && j && dp[j][k] * 6 > a[i]) {\r\n tmp[j][k - 1] = Math.max(tmp[j][k - 1], dp[j][k] * 6 + Math.floor(a[i] / 2));\r\n flag = false;\r\n } else if (k && j > 1 && dp[j][k] * 12 > a[i]) {\r\n tmp[j][k - 1] = Math.max(tmp[j][k - 1], dp[j][k] * 12 + Math.floor(a[i] / 2));\r\n flag = false;\r\n }\r\n }\r\n }\r\n }\r\n if (flag) return i;\r\n dp = tmp;\r\n }\r\n return n;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n let s = solve(r);\r\n if (s === undefined) s = '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "src_uid": "1f46c4ba21e734a1c7de8b2434791f77"} {"nl": {"description": "You are given two arrays of integers $$$a_1,\\ldots,a_n$$$ and $$$b_1,\\ldots,b_m$$$.Your task is to find a non-empty array $$$c_1,\\ldots,c_k$$$ that is a subsequence of $$$a_1,\\ldots,a_n$$$, and also a subsequence of $$$b_1,\\ldots,b_m$$$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$ and $$$[4,3,1]$$$, but not a subsequence of $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\\le n,m\\le 1000$$$)  — the lengths of the two arrays. The second line of each test case contains $$$n$$$ integers $$$a_1,\\ldots,a_n$$$ ($$$1\\le a_i\\le 1000$$$)  — the elements of the first array. The third line of each test case contains $$$m$$$ integers $$$b_1,\\ldots,b_m$$$ ($$$1\\le b_i\\le 1000$$$)  — the elements of the second array. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$1000$$$ ($$$\\sum\\limits_{i=1}^t n_i, \\sum\\limits_{i=1}^t m_i\\le 1000$$$).", "output_spec": "For each test case, output \"YES\" if a solution exists, or \"NO\" otherwise. If the answer is \"YES\", on the next line output an integer $$$k$$$ ($$$1\\le k\\le 1000$$$)  — the length of the array, followed by $$$k$$$ integers $$$c_1,\\ldots,c_k$$$ ($$$1\\le c_i\\le 1000$$$)  — the elements of the array. If there are multiple solutions with the smallest possible $$$k$$$, output any.", "sample_inputs": ["5\n4 5\n10 8 6 4\n1 2 3 4 5\n1 1\n3\n3\n1 1\n3\n2\n5 3\n1000 2 2 2 3\n3 1 5\n5 5\n1 2 3 4 5\n1 2 3 4 5"], "sample_outputs": ["YES\n1 4\nYES\n1 3\nNO\nYES\n1 3\nYES\n1 2"], "notes": "NoteIn the first test case, $$$[4]$$$ is a subsequence of $$$[10, 8, 6, 4]$$$ and $$$[1, 2, 3, 4, 5]$$$. This array has length $$$1$$$, it is the smallest possible length of a subsequence of both $$$a$$$ and $$$b$$$.In the third test case, no non-empty subsequences of both $$$[3]$$$ and $$$[2]$$$ exist, so the answer is \"NO\"."}, "positive_code": [{"source_code": "//↓見なくていいよ!ここから--------------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//↑見なくていいよ!ここまで--------------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = [];\n\tfor(var i = 0; i < t; i++){\n\t\tvar one = nextIntArray();\n\t\tvar a = one[0];\n\t\tvar b = one[1];\n\t\tvar alist = nextIntArray();\n\t\tvar blist = nextIntArray();\n\t\tvar set = new Set();\n\t\tfor(var j = 0; j < a; j++){\n\t\t\tset.add(alist[j]);\n\t\t}\n\t\tvar isOK = false;\n\t\tfor(var j = 0; j < b; j++){\n\t\t\tif(set.has(blist[j])){\n\t\t\t\tisOK = true;\n\t\t\t\toutput.push(\"YES\");\n\t\t\t\toutput.push(\"1 \" + blist[j]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(!isOK){\n\t\t\toutput.push(\"NO\");\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n\tdata = data.split('\\n');\n\tconst testCases = data[0] * 3;\n\tlet i = 1;\n\twhile (i <= testCases) {\n let a = data[i + 1].trim().split(' ');\n let b = data[i + 2].trim().split(' ');\n let r = null;\n if (a.length >= b.length) {\n for (let i = 0; i < b.length; i += 1) {\n if (a.indexOf(b[i]) !== -1) {r = b[i]; break;}\n }\n } else {\n for (let i = 0; i < a.length; i += 1) {\n if (b.indexOf(a[i]) !== -1) {r = a[i]; break;}\n }\n }\n if (r !== null) {\n console.log('YES');\n console.log(1, r);\n } else console.log('NO');\n i += 3;\n\t}\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const t = Number(readLine())\n for (let i = 0; i < t; i++) {\n const [n, m] = readLine().split(/\\s/).map(Number)\n const as = readLine().split(/\\s/).map(Number), bs = readLine().split(/\\s/).map(Number)\n let found = false\n for (const a of as) {\n if (bs.some(b => a === b)) {\n console.log('YES')\n console.log(`1 ${a}`)\n found = true\n break;\n }\n }\n if (!found) {\n console.log('NO')\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = parseInt(a[i]);\n\n return a;\n}\n\nfunction pi(x){\n return parseInt(x);\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [n,m] = ti(readline().split(' '));\n let a = ti(readline().split(' '));\n let b = ti(readline().split(' '));\n\n let map = new Array(1000+10);\n \n for(let i = 0; i < a.length; i++)\n map[a[i]] = 1;\n\n let isFound = false;\n for(let i = 0; i < b.length; i++){\n if(map[b[i]] === 1){\n console.log('YES');\n console.log(1, b[i]);\n isFound = true;\n break;\n }\n }\n\n if(!isFound)\n console.log('NO');\n }\n}"}, {"source_code": "function solve() {\n var nm = readArray(Number);\n var o1 = {};\n var o2 = {};\n var isFirst = true;\n function f(elem) {\n if (isFirst) {\n o1[elem] = true;\n return;\n }\n if (o1[elem]) {\n o2[elem] = true;\n }\n }\n readArray(f);\n isFirst = false;\n readArray(f);\n var ans = Object.keys(o2)[0];\n if (ans) {\n write('YES');\n write('1 ' + ans);\n } else {\n write('NO');\n }\n\n}\n\nfunction init() {\n var T;\n T = 1;\n T = Number(read());\n for (var t = 0; t < T; t++) {\n solve();\n }\n}\n\nfunction sortF(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\n\nfunction readArray(f) {\n return read().split(' ').map(f);\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n\n var inTextName;\n var outTextName;\n\n var needWriteFile = false;\n\n var writeResult = '';\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n\n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n init();\n if (needWriteFile) {\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\n err ? console.error(err) : console.log('good')\n });\n }\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n\n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n\n RL.on('close', init);\n }\n} else {\n init();\n}\n\nfunction write(value) {\n if (needWriteFile) {\n writeResult += value + '\\n';\n return;\n }\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}], "negative_code": [], "src_uid": "776a06c14c6fa3ef8664eec0b4d50824"} {"nl": {"description": "Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence $$$a_1, a_2, \\ldots, a_n$$$ of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.Let's denote the fingers of hand by numbers from $$$1$$$ to $$$5$$$. We call a fingering any sequence $$$b_1, \\ldots, b_n$$$ of fingers numbers. A fingering is convenient if for all $$$1\\leq i \\leq n - 1$$$ the following holds: if $$$a_i < a_{i+1}$$$ then $$$b_i < b_{i+1}$$$, because otherwise Paul needs to take his hand off the keyboard to play the $$$(i+1)$$$-st note; if $$$a_i > a_{i+1}$$$ then $$$b_i > b_{i+1}$$$, because of the same; if $$$a_i = a_{i+1}$$$ then $$$b_i\\neq b_{i+1}$$$, because using the same finger twice in a row is dumb. Please note that there is $$$\\neq$$$, not $$$=$$$ between $$$b_i$$$ and $$$b_{i+1}$$$. Please provide any convenient fingering or find out that there is none.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) denoting the number of notes. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 2\\cdot10^5$$$) denoting the positions of notes on the keyboard.", "output_spec": "If there is no convenient fingering, print $$$-1$$$. Otherwise, print $$$n$$$ numbers $$$b_1, b_2, \\ldots, b_n$$$, each from $$$1$$$ to $$$5$$$, denoting a convenient fingering, separated by spaces.", "sample_inputs": ["5\n1 1 4 2 2", "7\n1 5 7 8 10 3 1", "19\n3 3 7 9 8 8 8 8 7 7 7 7 5 3 3 3 3 8 8"], "sample_outputs": ["1 4 5 4 5", "1 2 3 4 5 4 3", "1 3 4 5 4 5 4 5 4 5 4 5 4 3 5 4 3 5 4"], "notes": "NoteThe third sample test is kinda \"Non stop\" song by Reflex."}, "positive_code": [{"source_code": "function doIt() {\n\n var fl = readline();\n var sl = readline();\n var notes = sl.split(' ');\n\n var res = [], hills = [], dirs = [0, 0, 0];\n\n var testCheck = '100000 99999 99999 99999 99998 99998 99998 99997 99998 99998 99999 99998 99998 99998';\n var testCnt = 0;\n var specialCase = fl === '10000' && sl.substr(0, testCheck.length) === testCheck;\n\n var diff, j;\n for(var i = 1; i < notes.length; i++) {\n diff = notes[i] - notes[i - 1];\n if(diff) diff = diff / Math.abs(diff);\n\n diff += 1;\n\n if(!dirs[diff]) {\n for (j = 0; j < 3; j++) {\n if(dirs[j]) {\n hills.push({dir: j, count: dirs[j]});\n dirs[j] = 0;\n break;\n }\n }\n }\n\n dirs[diff]++;\n }\n\n if(diff !== undefined) hills.push({dir: diff, count: dirs[diff]});\n\n var first = hills[0];\n if(!first) {\n print('1');\n return;\n }\n\n if(first.dir === 0) {\n res.push(5);\n } else if (first.dir === 2) {\n res.push(1);\n } else {\n res.push(3);\n }\n\n var curr = res[0];\n var mistake;\n\n for(i = 0; i < hills.length; i++) {\n var dir = hills[i].dir;\n var count = hills[i].count;\n\n testCnt += count;\n\n if(dir === 1) {\n curr = curr === 3 ? 4 : 3;\n res.push(curr);\n for(j = 1; j < count; j++) {\n res.push(curr = 7 - curr);\n }\n } else {\n if(dir === 0 && curr - count < 1\n || dir === 2 && curr + count > 5) {\n mistake = true;\n break;\n }\n\n for(j = 0; j < count; j++) {\n res.push(curr += dir - 1);\n }\n }\n\n var next = hills[i + 1];\n if(!next) break;\n\n var nextDir = next.dir;\n if(nextDir !== 1) {\n curr = 5 - nextDir * 2;\n while(curr === res[res.length - 2]) {\n curr += nextDir - 1;\n }\n res[res.length - 1] = curr;\n }\n }\n\n if(mistake) {\n // if(specialCase) {\n // print(notes.slice(testCnt-15, testCnt+10).join(' '));\n // print(res.slice(testCnt-15).join(' '));\n // }\n print(-1);\n } else {\n print(res.join(' '));\n }\n}\n\ndoIt();"}, {"source_code": "function doIt2() {\n readline();\n var notes = readline().split(' ');\n var res = [3];\n var curr = 3;\n var currDiff, mistake;\n for(var i = 1; i < notes.length; i++) {\n var diff = notes[i] - notes[i - 1];\n\n if(diff) {\n diff /= Math.abs(diff);\n if(diff !== currDiff) {\n curr = 3 - diff * 2;\n while(curr === res[res.length - 2]) {\n curr += diff;\n }\n res[res.length - 1] = curr;\n }\n curr += diff;\n if(curr < 1 || curr > 5) {\n mistake = true;\n break;\n }\n } else {\n curr = curr === 3 ? 4 : 3;\n }\n\n currDiff = diff;\n\n res.push(curr);\n }\n\n if(mistake) {\n print(-1);\n } else {\n print(res.join(' '));\n }\n}\n\ndoIt2();"}], "negative_code": [{"source_code": "function doIt() {\n\n readline();\n var res = [], hills = [], dirs = [0, 0, 0];\n var notes = readline().split(' ');\n\n var diff;\n for(var i = 1; i < notes.length; i++) {\n diff = notes[i] - notes[i - 1];\n if(diff) diff = diff / Math.abs(diff);\n\n diff += 1;\n\n if(!dirs[diff]) {\n for (var j = 0; j < 3; j++) {\n if(dirs[j]) {\n hills.push({dir: j, count: dirs[j]});\n dirs[j] = 0;\n break;\n }\n }\n }\n\n dirs[diff]++;\n }\n\n if(diff !== undefined) hills.push({dir: diff, count: dirs[diff]});\n\n var first = hills[0];\n if(!first) {\n print('1');\n return;\n }\n\n if(first.dir === 0) {\n res.push(5);\n } else if (first.dir === 2) {\n res.push(1);\n } else {\n res.push(3);\n }\n\n var curr = res[0];\n var mistake;\n\n for(i = 0; i < hills.length; i++) {\n var dir = hills[i].dir;\n var count = hills[i].count;\n\n if(dir === 1) {\n curr = curr === 3 ? 4 : 3;\n res.push(curr);\n for(j = 1; j < count; j++) {\n res.push(curr = 7 - curr);\n }\n } else {\n if(dir === 0 && curr - count < 1\n || dir === 2 && curr + count > 5) {\n mistake = true;\n break;\n }\n\n for(j = 0; j < count; j++) {\n res.push(curr += dir - 1);\n }\n }\n\n var next = hills[i + 1];\n if(!next) break;\n\n var nextDir = next.dir;\n if(nextDir === 0 && res[res.length - 2]!== 5) {\n res[res.length - 1] = curr = 5;\n } else if (nextDir === 2 && res[res.length - 2]!== 1) {\n res[res.length - 1] = curr = 1;\n }\n }\n\n if(mistake) {\n print(-1);\n } else {\n print(res.join(' '));\n }\n\n}\n\ndoIt();"}, {"source_code": "function doIt() {\n\n var fl = readline();\n var sl = readline();\n var notes = sl.split(' ');\n\n var res = [], hills = [], dirs = [0, 0, 0];\n\n var testCheck = '100000 99999 99999 99999 99998 99998 99998 99997 99998 99998 99999 99998 99998 99998';\n var testCnt = 0;\n var specialCase = fl === '10000' && sl.substr(0, testCheck.length) === testCheck;\n\n var diff, j;\n for(var i = 1; i < notes.length; i++) {\n diff = notes[i] - notes[i - 1];\n if(diff) diff = diff / Math.abs(diff);\n\n diff += 1;\n\n if(!dirs[diff]) {\n for (j = 0; j < 3; j++) {\n if(dirs[j]) {\n hills.push({dir: j, count: dirs[j]});\n dirs[j] = 0;\n break;\n }\n }\n }\n\n dirs[diff]++;\n }\n\n if(diff !== undefined) hills.push({dir: diff, count: dirs[diff]});\n\n var first = hills[0];\n if(!first) {\n print('1');\n return;\n }\n\n if(first.dir === 0) {\n res.push(5);\n } else if (first.dir === 2) {\n res.push(1);\n } else {\n res.push(3);\n }\n\n var curr = res[0];\n var mistake;\n\n for(i = 0; i < hills.length; i++) {\n var dir = hills[i].dir;\n var count = hills[i].count;\n\n testCnt += count;\n\n if(dir === 1) {\n curr = curr === 3 ? 4 : 3;\n res.push(curr);\n for(j = 1; j < count; j++) {\n res.push(curr = 7 - curr);\n }\n } else {\n if(dir === 0 && curr - count < 1\n || dir === 2 && curr + count > 5) {\n mistake = true;\n break;\n }\n\n for(j = 0; j < count; j++) {\n res.push(curr += dir - 1);\n }\n }\n\n var next = hills[i + 1];\n if(!next) break;\n\n var nextDir = next.dir;\n if(nextDir === 0 && res[res.length - 2]!== 5) {\n res[res.length - 1] = curr = 5;\n } else if (nextDir === 2 && res[res.length - 2]!== 1) {\n res[res.length - 1] = curr = 1;\n }\n }\n\n if(mistake) {\n if(specialCase) {\n print(notes.slice(testCnt-15, testCnt+10).join(' '));\n print(res.slice(testCnt-15).join(' '));\n }\n print(-1);\n } else {\n print(res.join(' '));\n }\n}\n\ndoIt();"}, {"source_code": "function doIt() {\n\n var fl = readline();\n var sl = readline();\n var notes = sl.split(' ');\n\n var res = [], hills = [], dirs = [0, 0, 0];\n\n var testCheck = '100000 99999 99999 99999 99998 99998 99998 99997 99998 99998 99999 99998 99998 99998';\n var testCnt = 0;\n var specialCase = fl === '10000' && sl.substr(0, testCheck.length) === testCheck;\n\n var diff, j;\n for(var i = 1; i < notes.length; i++) {\n diff = notes[i] - notes[i - 1];\n if(diff) diff = diff / Math.abs(diff);\n\n diff += 1;\n\n if(!dirs[diff]) {\n for (j = 0; j < 3; j++) {\n if(dirs[j]) {\n hills.push({dir: j, count: dirs[j]});\n dirs[j] = 0;\n break;\n }\n }\n }\n\n dirs[diff]++;\n }\n\n if(diff !== undefined) hills.push({dir: diff, count: dirs[diff]});\n\n var first = hills[0];\n if(!first) {\n print('1');\n return;\n }\n\n if(first.dir === 0) {\n res.push(5);\n } else if (first.dir === 2) {\n res.push(1);\n } else {\n res.push(3);\n }\n\n var curr = res[0];\n var mistake;\n\n for(i = 0; i < hills.length; i++) {\n var dir = hills[i].dir;\n var count = hills[i].count;\n\n testCnt += count;\n\n if(dir === 1) {\n curr = curr === 3 ? 4 : 3;\n res.push(curr);\n for(j = 1; j < count; j++) {\n res.push(curr = 7 - curr);\n }\n } else {\n if(dir === 0 && curr - count < 1\n || dir === 2 && curr + count > 5) {\n mistake = true;\n break;\n }\n\n for(j = 0; j < count; j++) {\n res.push(curr += dir - 1);\n }\n }\n\n var next = hills[i + 1];\n if(!next) break;\n\n var nextDir = next.dir;\n if(nextDir !== 1) {\n curr = 5 - nextDir * 2;\n while(curr === res[res.length - 2]) {\n curr += nextDir - 1;\n }\n res[res.length - 1] = curr;\n }\n }\n\n if(mistake) {\n if(specialCase) {\n print(notes.slice(testCnt-15, testCnt+10).join(' '));\n print(res.slice(testCnt-15).join(' '));\n }\n print(-1);\n } else {\n print(res.join(' '));\n }\n}\n\ndoIt();"}, {"source_code": "function doIt() {\n\n var fl = readline();\n var sl = readline();\n var notes = sl.split(' ');\n\n var res = [], hills = [], dirs = [0, 0, 0];\n\n var testCheck = '100000 99999 99999 99999 99998 99998 99998 99997 99998 99998 99999 99998 99998 99998';\n var testCnt = 0;\n var specialCase = fl === '10000' && sl.substr(0, testCheck.length) === testCheck;\n\n var j;\n var diff;\n for(var i = 1; i < notes.length; i++) {\n diff = notes[i] - notes[i - 1];\n if(diff) diff = diff / Math.abs(diff);\n\n diff += 1;\n\n if(!dirs[diff]) {\n for (j = 0; j < 3; j++) {\n if(dirs[j]) {\n hills.push({dir: j, count: dirs[j]});\n dirs[j] = 0;\n break;\n }\n }\n }\n\n dirs[diff]++;\n }\n\n if(diff !== undefined) hills.push({dir: diff, count: dirs[diff]});\n\n var first = hills[0];\n if(!first) {\n print('1');\n return;\n }\n\n if(first.dir === 0) {\n res.push(5);\n } else if (first.dir === 2) {\n res.push(1);\n } else {\n res.push(3);\n }\n\n var curr = res[0];\n var mistake;\n\n for(i = 0; i < hills.length; i++) {\n var dir = hills[i].dir;\n var count = hills[i].count;\n \n testCnt += count;\n\n if(dir === 1) {\n curr = curr === 3 ? 4 : 3;\n res.push(curr);\n for(j = 1; j < count; j++) {\n res.push(curr = 7 - curr);\n }\n } else {\n if(dir === 0 && curr - count < 1\n || dir === 2 && curr + count > 5) {\n mistake = true;\n break;\n }\n\n for(j = 0; j < count; j++) {\n res.push(curr += dir - 1);\n }\n }\n\n var next = hills[i + 1];\n if(!next) break;\n\n var nextDir = next.dir;\n if(nextDir === 0 && res[res.length - 2]!== 5) {\n res[res.length - 1] = curr = 5;\n } else if (nextDir === 2 && res[res.length - 2]!== 1) {\n res[res.length - 1] = curr = 1;\n }\n }\n\n if(mistake) {\n if(specialCase) print(testCnt);\n print(-1);\n } else {\n print(res.join(' '));\n }\n}\n\ndoIt();"}], "src_uid": "c63b62ad5b8d0b274599b60442766e17"} {"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$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \\le x_1, y_1, z_1 \\le 10^8$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$a$$$. The second line of each test case also contains three integers $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \\le x_2, y_2, z_2 \\le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$b$$$.", "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": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [a, b, c] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const [d, e, f] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n let ans = Math.min(c, e);\n\n const extra = Math.max(f - (a + c - ans), 0);\n\n ans -= extra;\n\n console.log(ans * 2);\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.split(/\\n/);\n main(); \n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const t = Number(readLine())\n for (let _ = 0; _ < t; _++) {\n const [x1, y1, z1] = readLine().split(/\\s/).map(Number)\n const [x2, y2, z2] = readLine().split(/\\s/).map(Number)\n const positive = Math.min(z1, y2)\n const negative = Math.max(z2 - x1 - z1 + positive, 0)\n console.log((positive - negative) * 2)\n }\n}\n\n"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n a = a || 0;\n b = b || (this.length - 1);\n let prev = a;\n for (let i = a; i <= b; i++) {\n if (i == b || fn(this[i], this[i + 1])) {\n arr.push(this.slice(prev, i + 1));\n prev = i + 1;\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nfunction inv(b, m) {\n for (var a = m, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + m) % m;\n}\n\n// let MOD = 1e9 + 7\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;\n let t = $()\n while (t--) {\n let [a0, a1, a2, b0, b1, b2] = $(6);\n let plus = min(a2, b1);\n let minus = min(a1, (b0 + b1 + b2 - plus - b2))\n log(plus * 2 - min(a1 - minus) * 2)\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probB(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n let [n,k] = readline().split(' ');\n n = pi(n);\n k = pi(k);\n\n if(n < k)\n console.log(k-n);\n else{\n if((n+k) % 2 === 0){\n console.log(0);\n }else{\n console.log(n-k);\n }\n }\n }\n}\n\nfunction probB(){\n let t = pi(readline());\n\n while(t > 0){\n t--;\n let a = readline().split(' ');\n let b = readline().split(' ');\n\n a[0] = pi(a[0]);\n a[1] = pi(a[1]);\n a[2] = pi(a[2]);\n\n b[0] = pi(b[0]);\n b[1] = pi(b[1]);\n b[2] = pi(b[2]);\n\n let maxSum = 0;\n if(b[2] - (a[0] + a[2]) > 0){\n b[2] = b[2] - (a[0]+a[2]);\n a[0] = 0;\n a[2] = 0;\n }else if(b[2] - a[0] > 0){\n a[2] = a[2] - (b[2] - a[0]);\n b[2] = 0;\n a[0] = 0;\n }else{\n a[0] -= b[2];\n b[2] = 0;\n }\n\n if(a[2] > b[1])\n console.log((b[1] - b[2]) * 2)\n else\n console.log((a[2]-b[2]) * 2);\n\n }\n}"}, {"source_code": "var t = parseInt(readline());\n\nwhile(t--){\n a = readline().split(' ');\n x1 = parseInt(a[0]);\n y1 = parseInt(a[1]);\n z1 = parseInt(a[2]);\n \n a = readline().split(' ');\n x2 = parseInt(a[0]);\n y2 = parseInt(a[1]);\n z2 = parseInt(a[2]);\n \n result = 0;\n min = Math.min(z1, y2);\n result += min * 2;\n z1 -= min;\n y2 -= min;\n \n min = Math.min(z2, x1);\n z2 -= min;\n x1 -= min;\n \n min = Math.min(z2, z1);\n z1 -= min;\n z2 -= min;\n \n result -= z2 * 2;\n \n print(result);\n}"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [a, b, c] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const [d, e, f] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n let diff = 0;\n if (f - a > 0) {\n diff = Math.min(f - a, b) * 2;\n }\n let ans = Math.min(c, e) * 2;\n\n if (ans) {\n ans -= diff;\n }\n\n console.log(ans);\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [a, b, c] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const [d, e, f] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n let diff = 0;\n if (b + c > d + e) {\n diff = b + c - (d + e);\n }\n let ans = Math.min(c, e) * 2;\n\n if (ans) {\n ans -= diff * 2;\n }\n\n console.log(ans);\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [a, b, c] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const [d, e, f] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n console.log(Math.min(c, e) * 2);\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probB(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n let [n,k] = readline().split(' ');\n n = pi(n);\n k = pi(k);\n\n if(n < k)\n console.log(k-n);\n else{\n if((n+k) % 2 === 0){\n console.log(0);\n }else{\n console.log(n-k);\n }\n }\n }\n}\n\nfunction probB(){\n let t = pi(readline());\n\n while(t > 0){\n t--;\n let a = readline().split(' ');\n let b = readline().split(' ');\n\n a[0] = pi(a[0]);\n a[1] = pi(a[1]);\n a[2] = pi(a[2]);\n\n b[0] = pi(b[0]);\n b[1] = pi(b[1]);\n b[2] = pi(b[2]);\n\n let maxSum = 0;\n if(b[2] - (a[0] + a[2]) > 0){\n b[2] = b[2] - (a[0]+a[2]);\n a[0] = 0;\n a[1] = 0;\n }else if(b[2] - a[0] > 0){\n a[2] = a[2] - (b[2] - a[0]);\n b[2] = 0;\n a[0] = 0;\n }else{\n a[0] -= b[2];\n b[2] = 0;\n }\n\n if(a[2] > b[1])\n console.log((b[1] - b[2]) * 2)\n else\n console.log((a[2]-b[2]) * 2);\n\n }\n}"}], "src_uid": "e1de1e92fac8a6db3222c0d3c26843d8"} {"nl": {"description": "Given $$$n$$$, find any array $$$a_1, a_2, \\ldots, a_n$$$ of integers such that all of the following conditions hold: $$$1 \\le a_i \\le 10^9$$$ for every $$$i$$$ from $$$1$$$ to $$$n$$$.$$$a_1 < a_2 < \\ldots <a_n$$$For every $$$i$$$ from $$$2$$$ to $$$n$$$, $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$It can be shown that such an array always exists under the constraints of the problem.", "input_spec": "The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For each test case print $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ — the array you found. If there are multiple arrays satisfying all the conditions, print any of them.", "sample_inputs": ["3\n1\n2\n7"], "sample_outputs": ["1\n2 3\n111 1111 11111 111111 1111111 11111111 111111111"], "notes": "NoteIn the first test case, array $$$[1]$$$ satisfies all the conditions.In the second test case, array $$$[2, 3]$$$ satisfies all the conditions, as $$$2<3$$$ and $$$3$$$ is not divisible by $$$2$$$.In the third test case, array $$$[111, 1111, 11111, 111111, 1111111, 11111111, 111111111]$$$ satisfies all the conditions, as it's increasing and $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$ for any $$$i$$$ from $$$2$$$ to $$$7$$$."}, "positive_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL)\n var n = lines[0]\n for(var j = 1; j <= n; j++){\n var k = lines[j]\n var ans = ''\n var a = 2\n for(l = 0; l < k; l++){\n ans += a + ' ';\n a++\n }\n console.log(ans); \n }\n}); \n\n"}, {"source_code": "\r\n\r\n\"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n\r\n\r\nconst x=+readline();\r\nlet g=[];\r\nfor(let i=0;i stop += c);\nprocess.stdin.on('end', () => { \n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var n = lines[0];\n for(var i = 1; i <= n; i++){\n var k = lines[i];\n var ans = '';\n var a = 2;\n for(j = 0; j < k; j++){\n ans += a + ' '; \n a++;\n }\n console.log(ans); \n }\n}); "}], "negative_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL)\n var n = lines[0]\n for(var j = 1; j <= n; j++){\n var k = lines[j]\n var ans = ''\n var a = 1\n for(l = 2; l < k; l++){\n ans += l + ' '; \n a++\n }\n console.log(ans); \n }\n}); \n\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL)\n var n = lines[0]\n for(var j = 1; j <= n; j++){\n var k = lines[j]\n var ans = ''\n var a = 1\n for(l = 0; l < k; l++){\n ans += a + ' '; \n a++\n }\n console.log(ans); \n }\n}); \n\n"}, {"source_code": "\"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n\r\n\r\nconst x=+readline();\r\nlet g=[];\r\nfor(let i=0;i{\r\n arr = arr.sort((a,b)=>a-b);\r\n let one = false;\r\n let consec = false;\r\n for(let i=0;iparseInt(cur));\r\n console.log(solve(n,arr));\r\n }\r\n}\r\nmain();"}, {"source_code": "const solve = (n,arr)=>{\r\n arr = arr.sort((a,b)=>a-b);\r\n if(arr[0]>=2) return \"YES\";\r\n else if(arr[0]===0){\r\n for(let i=1;i=2) break;\r\n }\r\n else{\r\n for(let i=1;iparseInt(cur));\r\n console.log(solve(n,arr));\r\n }\r\n}\r\nmain();"}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\nconst N = Number(inputs[0])\r\ninputs.shift()\r\nmain(N, inputs)\r\nfunction main(N, inputs) {\r\n next: for (let _ = 0; _ < N; _++) {\r\n const n = Number(inputs[_ * 2]),\r\n nums = inputs[_ * 2 + 1].split(' ').map(Number)\r\n let has0 = nums.some(num => num === 0),\r\n has1 = nums.some(num => num === 1)\r\n if (has0 && has1) {\r\n console.log('NO')\r\n } else if (!has1) {\r\n console.log('YES')\r\n } else {\r\n nums.sort((a, b) => b - a)\r\n for (let i = 1; i < n; i++) {\r\n if (nums[i] === nums[i - 1] - 1) {\r\n console.log('NO')\r\n continue next\r\n }\r\n }\r\n\r\n console.log('YES')\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nconst print = console.log\nconst lines = []\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst EPS = 1e-6;\n \nfunction main() {\n let T = +readline();\n while (T--){\n let [n] = readline().split(' ').map(a=>+a);\n let arr = readline().split(' ').map(a=>+a);\n let can_turn_all_to_0 = true\n let can_turn_all_to_1 = true\n let has_1 = false\n let all_same = true;\n for (let a of arr){\n if (arr[0]!=a)\n all_same = false;\n if (a==1)\n can_turn_all_to_0 = false;\n if (a==1)\n has_1 = true;\n if (a==2 || a==0)\n can_turn_all_to_1 = false;\n }\n if (!has_1 || all_same){\n print('yes');\n } else {\n arr.sort((a, b)=>a-b);\n let fail;\n for (let i=0; i stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i];\n }else{\n var a = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});\n var flag1 = 0, flag2 = 0;\n for(j = 0; j < n; j++){\n if(a[j] == 1){\n flag1 = 1;\n }\n if(j < n - 1 && a[j + 1] - a[j] == 1){\n flag2 = 1;\n }\n }\n console.log(flag1 && flag2 ? 'NO' : 'YES'); \n }\n }\n});"}], "negative_code": [{"source_code": "const solve = (n,arr)=>{\r\n arr = arr.sort((a,b)=>a-b);\r\n if(arr[0]>=2) return \"YES\";\r\n else if(arr[0]===0){\r\n for(let i=1;i=2) break;\r\n }\r\n let arr1 = [arr[0]];\r\n for(let i=1;iparseInt(cur));\r\n console.log(solve(n,arr));\r\n }\r\n}\r\nmain();"}, {"source_code": "const solve = (n,arr)=>{\r\n arr = arr.sort((a,b)=>a-b);\r\n if(arr[0]===0){\r\n let flag = 1;\r\n for(let i=1;i=2)) return \"NO\";\r\n else if(arr[i]>=2) break;\r\n }\r\n }\r\n else if(arr[0]===1){\r\n for(let i=1;i2){\r\n for(let j=i+1;jparseInt(cur));\r\n console.log(solve(n,arr));\r\n }\r\n}\r\nmain();"}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\nconst N = Number(inputs[0])\r\ninputs.shift()\r\nmain(N, inputs)\r\nfunction main(N, inputs) {\r\n next: for (let _ = 0; _ < N; _++) {\r\n const n = Number(inputs[_ * 2]),\r\n nums = inputs[_ * 2 + 1].split(' ').map(Number)\r\n let has0 = nums.some(num => num === 0),\r\n has1 = nums.some(num => num === 1)\r\n if (has0 && has1) {\r\n console.log('NO')\r\n } else if (!has1) {\r\n console.log('YES')\r\n } else {\r\n nums.sort((a, b) => b - a)\r\n for (let i = 1; i < n; i++) {\r\n console.log(i, nums[i], nums[i - 1])\r\n if (nums[i] === nums[i - 1] - 1) {\r\n console.log('NO')\r\n continue next\r\n }\r\n }\r\n\r\n console.log('YES')\r\n }\r\n }\r\n}\r\n"}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\nconst N = Number(inputs[0])\r\ninputs.shift()\r\nmain(N, inputs)\r\nfunction main(N, inputs) {\r\n next: for (let _ = 0; _ < N; _++) {\r\n const n = Number(inputs[_ * 2]),\r\n nums = inputs[_ * 2 + 1].split(' ').map(Number)\r\n let has0 = nums.some(num => num === 0),\r\n has1 = nums.some(num => num === 1)\r\n if (has0 && has1) {\r\n console.log('NO')\r\n } else if (!has1) {\r\n console.log('YES')\r\n } else {\r\n nums.sort((a, b) => b - a)\r\n console.log(nums, n)\r\n for (let i = 1; i < n; i++) {\r\n console.log(i, nums[i], nums[i - 1])\r\n if (nums[i] === nums[i - 1] - 1) {\r\n console.log('NO')\r\n continue next\r\n }\r\n }\r\n\r\n console.log('YES')\r\n }\r\n }\r\n}\r\n"}, {"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nconst print = console.log\nconst lines = []\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst EPS = 1e-6;\n \nfunction main() {\n let T = +readline();\n while (T--){\n let [n] = readline().split(' ').map(a=>+a);\n let arr = readline().split(' ').map(a=>+a);\n let can_turn_all_to_0 = true\n let can_turn_all_to_1 = true\n let all_same = true;\n for (let a of arr){\n if (arr[0]!=a)\n all_same = false;\n if (a==1)\n can_turn_all_to_0 = false;\n if (a==2 || a==0)\n can_turn_all_to_1 = false;\n }\n print(all_same || can_turn_all_to_0 || can_turn_all_to_1 ? 'yes' : 'no')\n }\n}"}], "src_uid": "c7e4f544ec8b4972291542e66aff5df5"} {"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 × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round. ", "input_spec": "The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.", "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": "\"use strict\";\n// Object.defineProperty(exports, \"__esModule\", { value: true });\n// var lol_io_1 = require(\"lol-io\");\nfunction readNumbers() {\n return readline().split(' ').map(function (s) { return parseInt(s); });\n}\nfunction readMatrix(n) {\n var matrix = [];\n for (var i = 0; i < n; i++) {\n var row = readNumbers();\n matrix.push(row);\n }\n return matrix;\n}\nfunction readQueries(q) {\n var queries = [];\n for (var i = 0; i < q; i++) {\n var _a = readNumbers(), r = _a[0], c = _a[1];\n queries.push([r, c]);\n }\n return queries;\n}\nfunction arrayFilled(n, value) {\n var a = [];\n for (var i = 0; i < n; i++)\n a.push(value);\n return a;\n}\nfunction computeMaxForRows() {\n var maxSeqInRow = arrayFilled(n, 0);\n for (var i = 0; i < matrix.length; i++) {\n var row = matrix[i];\n var currMax = 0;\n for (var j = 0; j < row.length; j++) {\n if (row[j]) {\n currMax++;\n maxSeqInRow[i] = Math.max(maxSeqInRow[i], currMax);\n }\n else {\n currMax = 0;\n }\n }\n }\n return maxSeqInRow;\n}\nfunction computeMaxForRow(i) {\n maxSeqInRow[i] = 0;\n var row = matrix[i];\n var currMax = 0;\n for (var j = 0; j < row.length; j++) {\n if (row[j]) {\n currMax++;\n maxSeqInRow[i] = Math.max(maxSeqInRow[i], currMax);\n }\n else {\n currMax = 0;\n }\n }\n}\nvar _a = readNumbers(), n = _a[0], m = _a[1], q = _a[2];\nvar matrix = readMatrix(n);\nvar queries = readQueries(q);\nvar maxSeqInRow = computeMaxForRows();\nfunction solve() {\n for (var _i = 0, queries_1 = queries; _i < queries_1.length; _i++) {\n var _a = queries_1[_i], i = _a[0], j = _a[1];\n matrix[i - 1][j - 1] ^= 1;\n computeMaxForRow(i - 1);\n print(Math.max.apply(Math, maxSeqInRow).toString());\n }\n}\nsolve();\n"}], "negative_code": [], "src_uid": "337b6d2a11a25ef917809e6409f8edef"} {"nl": {"description": "There are $$$n$$$ students standing in a circle in some order. The index of the $$$i$$$-th student is $$$p_i$$$. It is guaranteed that all indices of students are distinct integers from $$$1$$$ to $$$n$$$ (i. e. they form a permutation).Students want to start a round dance. A clockwise round dance can be started if the student $$$2$$$ comes right after the student $$$1$$$ in clockwise order (there are no students between them), the student $$$3$$$ comes right after the student $$$2$$$ in clockwise order, and so on, and the student $$$n$$$ comes right after the student $$$n - 1$$$ in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student $$$i$$$ should be right after the student $$$i - 1$$$ in counterclockwise order (this condition should be met for every $$$i$$$ from $$$2$$$ to $$$n$$$). For example, if the indices of students listed in clockwise order are $$$[2, 3, 4, 5, 1]$$$, then they can start a clockwise round dance. If the students have indices $$$[3, 2, 1, 4]$$$ in clockwise order, then they can start a counterclockwise round dance.Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 200$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 200$$$) — the number of students. The second line of the query contains a permutation of indices $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$), where $$$p_i$$$ is the index of the $$$i$$$-th student (in clockwise order). It is guaranteed that all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i. e. they form a permutation).", "output_spec": "For each query, print the answer on it. If a round dance can be started with the given order of students, print \"YES\". Otherwise print \"NO\".", "sample_inputs": ["5\n4\n1 2 3 4\n3\n1 3 2\n5\n1 2 3 5 4\n1\n1\n5\n3 2 1 5 4"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES"], "notes": null}, "positive_code": [{"source_code": "const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nconst print = console.log\nconst write = (...args) => {\n process.stdout.write(args.join(' '));\n}\nconst lines = []\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nfunction query(arr){\n let n = arr.length;\n let arr2 = arr.concat(arr);\n let f = arr2.indexOf(1);\n for (let i=0; i+n);\n if (query(arr) || query(arr.reverse()))\n print('YES')\n else\n print('NO');\n }\n}\n"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n\n function foo (data) {\n\n function can1 (data) {\n return data.reduce((agr, value, index, array) => {\n if (!agr) return false;\n if (index === array.length - 1) return agr;\n return value === array[index + 1] - 1 || array[index + 1] === 1;\n }, true);\n }\n\n function can0 (data) {\n return data.reduceRight((agr, value, index, array) => {\n if (!agr) return false;\n if (index === 0) return agr;\n return value === array[index - 1] - 1 || array[index - 1] === 1;\n }, true);\n }\n\n return can1(data) || can0(data);\n }\n\n let testCount = 1;\n let answer = '';\n while(testCount <= +lines[0]) {\n let data = lines[testCount * 2].split(\" \").map(Number);\n //console.log(data);\n let result = foo(data);\n answer += (result ? \"YES\" : \"NO\") +\"\\n\";\n testCount++;\n }\n console.log(answer);\n})"}, {"source_code": "let i = '';\nprocess.stdin.on('data', (c) => {\n i += c;\n});\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = i.split(EOL);\n let count = 2;\n // console.log(lines);\n while (count < lines.length) {\n let input = lines[count].split(' ');\n input = input.map(str => parseInt(str, 10));\n canDance(input);\n count += 2;\n }\n});\n\nfunction canDance(arr) {\n let index = arr.indexOf(1);\n if (index === -1) {\n console.log('NO');\n return;\n }\n\n // clockwise\n const startIndex = index;\n let curr = 1;\n index++;\n while (index !== startIndex) {\n if (index === arr.length) index = 0;\n if (arr[index] === curr + 1) {\n curr++;\n index++;\n } else {\n break;\n }\n }\n\n if (index === startIndex) {\n console.log('YES');\n return;\n }\n\n curr = 1;\n index = startIndex - 1;\n while (index !== startIndex) {\n if (index === -1) index = arr.length - 1;\n if (arr[index] === curr + 1) {\n curr++;\n index--;\n } else {\n break;\n }\n }\n if (index === startIndex) {\n console.log('YES');\n } else {\n console.log('NO');\n }\n}\n"}, {"source_code": "'use strict'\n\n\nconst roundelay = (n, p) => {\n let i = 1;\n while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;\n if (i === n) return 'YES';\n i = 1;\n while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;\n if (i === n) return 'YES';\n return 'NO';\n}\n\nconst q = parseInt(readline());\nfor (let i = 0; i < q; i++) {\n write(roundelay(parseInt(readline()), readline().split(' ').map(Number)) + '\\n');\n}"}, {"source_code": "rVal = () => +readline();\nrArr = () => readline().split(' ').map(item => +item);\n\nvar q = rVal();\n\nfor(var i = 0; i < q; i++) {\n var n = rVal();\n var arr = rArr();\n \n if(n === 1) {\n print('YES');\n continue;\n }\n \n for(var j = 0; j < n; j++) {\n if(arr[j] === 1) {\n index = j;\n break;\n }\n }\n \n var j = 0;\n \n for(j = 0, k = index; j < n - 1; j++) {\n var k2 = k + 1;\n if(k2 === n) {\n k2 = 0;\n }\n if(arr[k2] - arr[k] === 1) {\n k = k2;\n } else {\n break;\n }\n }\n \n if(j === n - 1) {\n print('YES');\n continue;\n }\n \n for(var j = 0, k = index; j < n - 1; j++) {\n var k2 = k - 1;\n if(k2 < 0) {\n k2 = n - 1;\n }\n if(arr[k2] - arr[k] === 1) {\n k = k2;\n } else {\n break;\n }\n }\n \n if(j === n - 1) {\n print('YES');\n continue;\n }\n \n print('NO');\n}"}, {"source_code": "'use strict'\n\nvar t=Number(readline());\n\nwhile(t--)\n{\n var n=parseInt(readline());\n var data=readline().split(' ').map(Number);\n\n var start_idx=-1;\n for(var i=0;i=n) clockW=0;\n if((data[clockW]-tmp)!=1){\n flag=false;\n break;\n }\n }\n\n if(!flag){\n flag=true;\n clockW=start_idx;\n\n for(var i=1;i {\n let i = 1;\n while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;\n if (i === n) return 'OK';\n i = 1;\n while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;\n if (i === n) return 'OK';\n return 'NO';\n}\n\nconst q = parseInt(readline());\nfor (let i = 0; i < q; i++) {\n roundelay(parseInt(readline()), readline().split(' ').map(Number));\n}"}, {"source_code": "'use strict'\n\n\nconst roundelay = (n, p) => {\n let i = 1;\n while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;\n if (i === n) return 'OK';\n i = 1;\n while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;\n if (i === n) return 'OK';\n return 'NO';\n}\n\nconst q = parseInt(readline());\nfor (let i = 0; i < q; i++) {\n write(roundelay(parseInt(readline()), readline().split(' ').map(Number)) + '\\n');\n}"}], "src_uid": "b27436086ead93397be748d8ebdbf19a"} {"nl": {"description": "Let $$$s$$$ be a string of lowercase Latin letters. Its price is the sum of the indices of letters (an integer between 1 and 26) that are included in it. For example, the price of the string abca is $$$1+2+3+1=7$$$.The string $$$w$$$ and the integer $$$p$$$ are given. Remove the minimal number of letters from $$$w$$$ so that its price becomes less than or equal to $$$p$$$ and print the resulting string. Note that the resulting string may be empty. You can delete arbitrary letters, they do not have to go in a row. If the price of a given string $$$w$$$ is less than or equal to $$$p$$$, then nothing needs to be deleted and $$$w$$$ must be output.Note that when you delete a letter from $$$w$$$, the order of the remaining letters is preserved. For example, if you delete the letter e from the string test, you get tst.", "input_spec": "The first line of input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases in the test. The following are descriptions of $$$t$$$ test cases. Each case consists of two lines. The first of them is the string $$$w$$$, it is non-empty and consists of lowercase Latin letters. Its length does not exceed $$$2\\cdot10^5$$$. The second line contains an integer $$$p$$$ ($$$1 \\le p \\le 5\\,200\\,000$$$). It is guaranteed that the sum of string lengths $$$w$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Output exactly $$$t$$$ rows, the $$$i$$$-th of them should contain the answer to the $$$i$$$-th set of input data. Print the longest string that is obtained from $$$w$$$ by deleting letters such that its price is less or equal to $$$p$$$. If there are several answers, then output any of them. Note that the empty string  — is one of the possible answers. In this case, just output an empty string.", "sample_inputs": ["5\n\nabca\n\n2\n\nabca\n\n6\n\ncodeforces\n\n1\n\ncodeforces\n\n10\n\ncodeforces\n\n100"], "sample_outputs": ["aa\nabc\n\ncdc\ncodeforces"], "notes": null}, "positive_code": [{"source_code": "const main = () => {\r\n\t\r\n\tvar t = readInt();\r\n\tvar allans = [];\r\n\tfor (var zz = 0; zz < t; zz++) {\r\n\t\tvar s = readString();\r\n\t\tvar n = s.length;\r\n\t\tvar p = readInt();\r\n\t\t\r\n\t\tvar idxs = [];\r\n\t\tfor (var i = 0; i < 27; i++)\r\n\t\t\tidxs.push([]);\r\n\t\tfor (var i = 0; i < n; i++)\r\n\t\t\tidxs[s.charCodeAt(i) - 96].push(i);\r\n\t\t\r\n\t\tvar total = 0;\r\n\t\tvar takeIdx = [0];\r\n\t\tfor (var i = 0; i < n; i++)\r\n\t\t\ttakeIdx.push(0);\r\n\t\tfor (var i = 1; i < 27; i++) {\r\n\t\t\twhile (total + i <= p && idxs[i].length > 0) {\r\n\t\t\t\ttotal += i;\r\n\t\t\t\ttakeIdx[idxs[i][idxs[i].length - 1]] = 1;\r\n\t\t\t\tidxs[i].pop();\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar ansarr = [];\r\n\t\tfor (var i = 0; i < n; i++)\r\n\t\t\tif (takeIdx[i] === 1)\r\n\t\t\t\tansarr.push(s[i]);\r\n\t\tvar ans = ansarr.join('');\r\n\t\tallans.push(ans);\r\n\t}\r\n\tmultiLineArrayPrint(allans);\r\n\t\r\n\treturn;\r\n}\r\n \r\nconst readInt = () => parseInt(readline());\r\nconst readString = () => readline();\r\nconst readIntArr = () => readline().split(\" \").map(zzzz => parseInt(zzzz));\r\nconst parseLong = (string) => { // javascript's largest long is < (1<<62)\r\n\tvar n = string.length;\r\n\tvar res = 0;\r\n\tfor (var i = 0; i < n; i++) {\r\n\t\tres *= 10;\r\n\t\tres += parseInt(string[i]);\r\n\t}\r\n\treturn res;\r\n}\r\nconst readLong = () => parseLong(readLong());\r\nconst readLongArr = () => readline().split(\" \").map(zzzz => parseLong(zzzz));\r\nconst oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));\r\nconst multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\\n'));\r\nconst multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\\n'));\r\nconst makeArr = (defaultVal, dimensionsArr) => {\r\n\tvar n = dimensionsArr.length;\r\n\tif (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);\r\n\telse {\r\n\t\tvar temp = [];\r\n\t\tfor (var i = 0; i < dimensionsArr[0]; i++)\r\n\t\t\ttemp.push(makeArr(defaultVal, dimensionsArr.slice(1)));\r\n\t\treturn temp;\r\n\t}\r\n}\r\n \r\nfor (_ = 0; _ < 1; _++) {\r\n\tmain();\r\n}"}, {"source_code": "\r\nconst main = () => {\r\n\t\r\n\tvar t = readInt();\r\n\tvar allans = [];\r\n\tfor (var zz = 0; zz < t; zz++) {\r\n\t\tvar s = readString();\r\n\t\tvar n = s.length;\r\n\t\tvar p = readInt();\r\n\t\t\r\n\t\tvar idxs = [];\r\n\t\tfor (var i = 0; i < 27; i++)\r\n\t\t\tidxs.push([]);\r\n\t\tfor (var i = 0; i < n; i++)\r\n\t\t\tidxs[s.charCodeAt(i) - 96].push(i);\r\n\t\t\r\n\t\tvar total = 0;\r\n\t\tvar takeIdx = [0];\r\n\t\tfor (var i = 0; i < n; i++)\r\n\t\t\ttakeIdx.push(0);\r\n\t\tfor (var i = 1; i < 27; i++) {\r\n\t\t\twhile (total + i <= p && idxs[i].length > 0) {\r\n\t\t\t\ttotal += i;\r\n\t\t\t\ttakeIdx[idxs[i][idxs[i].length - 1]] = 1;\r\n\t\t\t\tidxs[i].pop();\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar ansarr = [];\r\n\t\tfor (var i = 0; i < n; i++)\r\n\t\t\tif (takeIdx[i] === 1)\r\n\t\t\t\tansarr.push(s[i]);\r\n\t\tvar ans = ansarr.join('');\r\n\t\tallans.push(ans);\r\n\t}\r\n\tmultiLineArrayPrint(allans);\r\n\t\r\n\treturn;\r\n}\r\n\r\nconst readInt = () => parseInt(readline());\r\nconst readString = () => readline();\r\nconst readIntArr = () => readline().split(\" \").map(zzzz => parseInt(zzzz));\r\nconst parseLong = (string) => { // javascript's largest long is < (1<<62)\r\n\tvar n = string.length;\r\n\tvar res = 0;\r\n\tfor (var i = 0; i < n; i++) {\r\n\t\tres *= 10;\r\n\t\tres += parseInt(string[i]);\r\n\t}\r\n\treturn res;\r\n}\r\nconst readLong = () => parseLong(readLong());\r\nconst readLongArr = () => readline().split(\" \").map(zzzz => parseLong(zzzz));\r\nconst oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));\r\nconst multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\\n'));\r\nconst multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\\n'));\r\nconst makeArr = (defaultVal, dimensionsArr) => {\r\n\tvar n = dimensionsArr.length;\r\n\tif (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);\r\n\telse {\r\n\t\tvar temp = [];\r\n\t\tfor (var i = 0; i < dimensionsArr[0]; i++)\r\n\t\t\ttemp.push(makeArr(defaultVal, dimensionsArr.slice(1)));\r\n\t\treturn temp;\r\n\t}\r\n}\r\n\r\nfor (_ = 0; _ < 1; _++) {\r\n\tmain();\r\n}\r\n\r\n// newline for testing\r\n //newline for testing\r\n// codeforces js cannot use \"let\" keyword. use \"var\" instead\r\n// codeforces js cannot destructure arrays"}, {"source_code": "T = readline()\r\n\r\nabc = 'abcdefghijklmnopqrstuvwxyz'.split('')\r\nobj = {}\r\nfor(i=0; i< abc.length; i++){\r\n obj[abc[i]] = i +1 \r\n}\r\n\r\nwhile(T--){\r\n str = readline().split('').map(el => obj[el])\r\n p = readline()\r\n\r\n sum = str.reduce(function(acc, cur){\r\n return acc + cur\r\n }, 0)\r\n \r\n clone = str.slice()\r\n clone.sort((a, b) => a - b)\r\n\r\n while(sum > p){\r\n sum = sum - clone[clone.length-1]\r\n clone.pop()\r\n }\r\n\r\n objAns = {}\r\n for(i = 0; i < clone.length; i++){\r\n if(objAns[clone[i]] === undefined)\r\n objAns[clone[i]] = 1\r\n else\r\n objAns[clone[i]]++\r\n }\r\n\r\n strAns = []\r\n\r\n for(i = 0; i< str.length; i++){\r\n if(objAns[str[i]]){\r\n objAns[str[i]]--\r\n strAns.push(str[i])\r\n }\r\n }\r\n\r\n resultObj = {}\r\n\r\n Object.keys(obj).forEach(key => {\r\n value = obj[key]\r\n resultObj[value] = key\r\n })\r\n\r\n res = strAns.map(el => resultObj[el])\r\n\r\n print(res.join(''))\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let arr = readline().trim().split(\"\");\r\n let n = arr.length;\r\n let k = parseInt(readline());\r\n let obj = {\r\n a: 1,\r\n b: 2,\r\n c: 3,\r\n d: 4,\r\n e: 5,\r\n f: 6,\r\n g: 7,\r\n h: 8,\r\n i: 9,\r\n j: 10,\r\n k: 11,\r\n l: 12,\r\n m: 13,\r\n n: 14,\r\n o: 15,\r\n p: 16,\r\n q: 17,\r\n r: 18,\r\n s: 19,\r\n t: 20,\r\n u: 21,\r\n v: 22,\r\n w: 23,\r\n x: 24,\r\n y: 25,\r\n z: 26,\r\n };\r\n let narr = [];\r\n for (let i = 0; i < n; i++) {\r\n let o = { val: obj[arr[i]], ind: i };\r\n narr.push(o);\r\n }\r\n narr.sort((a, b) => a.val - b.val);\r\n let sum = 0;\r\n for (let i = 0; i < n; i++) sum += narr[i].val;\r\n let c = {},\r\n i = n - 1;\r\n while (sum > k && i >= 0) {\r\n sum -= narr[i].val;\r\n c[narr[i].ind] = 1;\r\n i--;\r\n }\r\n let res = \"\";\r\n for (let i = 0; i < n; i++) {\r\n if (c[i]) continue;\r\n else res += arr[i];\r\n }\r\n console.log(res);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let alph = [...Array(26)].map((_, i) => String.fromCharCode(i + 97));\r\n let price = {};\r\n alph.forEach((letter, i) => price[letter] = i + 1);\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let str = readline();\r\n let target = Number(readline());\r\n\r\n if (str === '' || target === 0) {\r\n output('');\r\n continue;\r\n }\r\n\r\n let totalCost = 0;\r\n let costs = str.split('').map((letter, index) => {\r\n totalCost += price[letter];\r\n return {\r\n originalIndex: index,\r\n letter: letter,\r\n cost: price[letter]\r\n };\r\n });\r\n costs.sort((a, b) => a.cost - b.cost);\r\n\r\n while (totalCost > target) {\r\n let next = costs.pop();\r\n totalCost -= next.cost;\r\n }\r\n\r\n costs.sort((a, b) => a.originalIndex - b.originalIndex);\r\n\r\n let result = costs.map(c => c.letter).join('');\r\n\r\n output(result);\r\n }\r\n}\r\n"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n// console.log(input)\r\nvar T = readline();\r\n// var inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n // var nul = readline();\r\n var n = readline()//.split(' ').map((x) => parseInt(x));\r\n // var a = readline().split(' ').map((x) => parseInt(x));\r\n var p = readline();\r\n var c = []\r\n var f = alph();\r\n var mp = new Map();\r\n for(var i=0;i p) {\r\n // if(tc == 1) console.log(\"p\", i)\r\n break;\r\n }\r\n g += val;\r\n // ans += n[c[i][0]]\r\n }\r\n var ca = c.slice(0, i)\r\n ca.sort(function(a,b) { return a[0] - b[0] })\r\n for(var i=0;i a + b, 0);\r\n if (sum <= n) return s;\r\n const map = Array.from({\r\n length: 27\r\n }, () => []);\r\n let res = new Array(m).fill(1);\r\n for (let [i, num] of a.entries()) map[num].push(i);\r\n let i = 26;\r\n while (sum > n) {\r\n while (i >= 0 && map[i].length === 0) {\r\n i--;\r\n }\r\n if (map[i].length === 0) return '';\r\n const j = map[i].pop();\r\n res[j] = 0;\r\n sum -= i;\r\n }\r\n let ans = '';\r\n for (let i = 0; i < m; i++) {\r\n if (res[i]) ans += s[i];\r\n }\r\n return ans;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const s = await read();\r\n const n = Number(await read());\r\n res[i] = solve(n, s);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tvar alpha = \"abcdefghijklmnopqrstuvwxyz\";\r\n\tvar costmap = {};\r\n\tfor(var i = 0; i < alpha.length; i++){\r\n\t\tcostmap[alpha[i]] = i + 1;\r\n\t}\r\n\twhile(hasNext()){\r\n\t\tvar S = nextCharArray();\r\n\t\tvar N = S.length;\r\n\t\tvar P = nextInt();\r\n\t\tvar cost = 0;\r\n\t\tvar map = {};\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tcost += costmap[S[i]];\r\n\t\t\tif(map[S[i]] == null){\r\n\t\t\t\tmap[S[i]] = [];\r\n\t\t\t}\r\n\t\t\tmap[S[i]].push(i);\r\n\t\t}\r\n\t\tfor(var i = alpha.length - 1; i >= 0; i--){\r\n\t\t\tif(cost <= P){\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(map[alpha[i]] == null){\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tvar nx = map[alpha[i]];\r\n\t\t\tfor(var j = 0; j < nx.length; j++){\r\n\t\t\t\tS[nx[j]] = \"\";\r\n\t\t\t\tcost -= costmap[alpha[i]];\r\n\t\t\t\tif(cost <= P){\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(myconv(S, 0));\r\n\t}\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const str = lines[l++]\n const p = +lines[l++]\n output[i] = solve(str, p)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(str, p) {\n const arr = []\n for (let i = 0; i < str.length; i++) {\n const x = str.charCodeAt(i) - 'a'.charCodeAt(0) + 1\n arr.push([x, i])\n }\n arr.sort((a, b) => a[0] - b[0])\n //\n let now = 0\n const skip = {}\n for (let i = 0; i < arr.length; i++) {\n const [x, j] = arr[i]\n if (now + x > p) {\n // delete\n skip[j] = 1\n } else {\n now += x\n }\n }\n const ans = []\n for (let i = 0; i < str.length; i++) {\n if (!skip[i]) ans.push(str[i])\n }\n return ans.join('')\n}\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let arr = readline().trim().split(\"\");\r\n let n = arr.length;\r\n let k = parseInt(readline());\r\n let obj = {\r\n a: 1,\r\n b: 2,\r\n c: 3,\r\n d: 4,\r\n e: 5,\r\n f: 6,\r\n g: 7,\r\n h: 8,\r\n i: 9,\r\n j: 10,\r\n k: 11,\r\n l: 12,\r\n m: 13,\r\n n: 14,\r\n o: 15,\r\n p: 16,\r\n q: 17,\r\n r: 18,\r\n s: 19,\r\n t: 20,\r\n u: 21,\r\n v: 22,\r\n w: 23,\r\n x: 24,\r\n y: 25,\r\n z: 26,\r\n };\r\n let narr = [];\r\n for (let i = 0; i < n; i++) {\r\n let o = { val: obj[arr[i]], ind: i };\r\n narr.push(o);\r\n }\r\n narr.sort((a, b) => a.val - b.val);\r\n let sum = 0;\r\n for (let i = 0; i < n; i++) sum += narr[i].val;\r\n let c = {},\r\n i = n - 1;\r\n if (sum === k) {\r\n console.log(\"\");\r\n continue;\r\n }\r\n while (sum > k && i >= 0) {\r\n sum -= narr[i].val;\r\n c[narr[i].ind] = 1;\r\n i--;\r\n }\r\n let res = \"\";\r\n for (let i = 0; i < n; i++) {\r\n if (c[i]) continue;\r\n else res += arr[i];\r\n }\r\n console.log(res);\r\n }\r\n};\r\nsolve();\r\n"}], "src_uid": "cb645c794ee3916b180fc3d789cb7c27"} {"nl": {"description": "One very important person has a piece of paper in the form of a rectangle a × b.Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?", "input_spec": "The first line contains three integer numbers n, a and b (1 ≤ n, a, b ≤ 100). Each of the next n lines contain two numbers xi, yi (1 ≤ xi, yi ≤ 100).", "output_spec": "Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.", "sample_inputs": ["2 2 2\n1 2\n2 1", "4 10 9\n2 3\n1 1\n5 10\n9 11", "3 10 10\n6 6\n7 7\n20 5"], "sample_outputs": ["4", "56", "0"], "notes": "NoteIn the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.In the third example there is no such pair of seals that they both can fit on a piece of paper."}, "positive_code": [{"source_code": "ln=readline().split(\" \").map(x=>x*1);\nn=ln[0];\na=ln[1];\nb=ln[2];\nseals = [];\nfor(i=0; ix*1));\n}\n\nfunction canFit(x1,y1,x2,y2){\n if(x1>a||x2>a||y1>b||y2>b) return false;\n ox = x1+x2>a?false:true;\n oy = y1+y2>b?false:true;\n return ox||oy;\n}\n\nans = 0;\nfor(i=0; i= b[0]) && (toot[x][1]>=b[1])) || ((toot[x][1] >= b[0]) && (toot[x][0]>=b[1])) )\n{\nvar s = (+(ayin[i][0]*ayin[i][1])) + (+(ayin[r][0]*ayin[r][1]));\nif((s>round)&&(s<=xy[0]*xy[1])){round=s;}\n} \n \n\n}\n\n \n\n\n}\n\n\n\nprint(round)\n\n\n "}], "negative_code": [{"source_code": "ln=readline().split(\" \").map(x=>x*1);\nn=ln[0];\na=ln[1];\nb=ln[2];\nseals = [];\nfor(i=0; ix*1));\n}\n\nfunction canFit(x1,y1,x2,y2){\n if(x1>a||x2>a||y1>b||y2>b) return false;\n ox = x1+x2>a?true:false;\n oy = y1+y2>b?true:false;\n return ox||oy;\n}\n\nans = 0;\nfor(i=0; i=xy[0]*xy[1]){if((fps0<=lastspace)&&(seconditem[1]<=e) ){ \n e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}} \n\n\nif(fps1>=xy[0]*xy[1]){if((fps1<=lastspace)&&(seconditem[0]<=e)){\n e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}\n \n}if(z===0){z+=1;r-=1}\n}\n print(round);\n"}, {"source_code": "var rline = readline().split(\" \");var xy = [+rline[1],+rline[2]];\n\nvar round = 0;var s = 0;\nvar ayin = [];\nfor(var o=0;o= b[0]) && (toot[x][1]>=b[1])){\nvar s = (+(ayin[i][0]*ayin[i][1])) + (+(ayin[r][0]*ayin[r][1]))\nif((s>round)&&(s= b[0]) && (toot[x][0]>=b[1])){\n var s = ((+(ayin[i][0]*ayin[i][1])) + (+(ayin[r][0]*ayin[r][1])))\n if((s>round)&&(s=xy[0]*xy[1])&&(fps0<=lastspace)){\n\n var s = true ;if((fps0==lastspace)&&(seconditem[1]>e)){s=false}\n if(s==true){\n e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}} \n\n\n if((fps1>=xy[0]*xy[1])&&(fps1<=lastspace)){\n s = true ;if((fps1==lastspace)&&(seconditem[0]>e)){s=false}\n if(s==true){\n e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}\n \n }if(z===0){z+=1;r-=1}\n }\n print(round);\n \n"}, {"source_code": "var rline = readline().split(\" \");var xy = [+rline[1],+rline[2]];\nvar round = [0];\nvar ayinput = [];for(var o=0;o0){\n\n if ((toot[x][0] >= b[0]) && (toot[x][1]>=b[0])){\n round.push((+(ayinput[i][0]*ayinput[i][1])) + (+(ayinput[r][0]*ayinput[r][1])))\n if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;\n }\n \n if ((toot[x][1] >= b[0]) && (toot[x][0]>=b[1])){\n round.push((+(ayinput[i][0]*ayinput[i][1])) + (+(ayinput[r][0]*ayinput[r][1])))\n if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;\n }\n }\n\n\n}\n}\n\n\nprint(Math.max(...round))\n\n\n"}, {"source_code": "var rline = readline().split(\" \");var xy = [+rline[1],+rline[2]];\nvar round = [0];\nvar ayinput = [];for(var o=0;o0){\n\n if ((toot[x][0] >= b[0]) && (toot[x][1]>=b[1])){\n round.push((+(ayinput[i][0]*ayinput[i][1])) + (+(ayinput[r][0]*ayinput[r][1])))\n if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;\n }\n \n if ((toot[x][1] >= b[0]) && (toot[x][0]>=b[1])){\n round.push((+(ayinput[i][0]*ayinput[i][1])) + (+(ayinput[r][0]*ayinput[r][1])))\n if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;\n }\n }\n\n\n}\n}\n\n\nprint(Math.max(...round))\n\n\n"}, {"source_code": "\n var rline = readline().split(\" \");var xy = [rline[1],rline[2]];\n\n\n var temp = [];for(var o=0;o=xy[0]*xy[1]){if((fps0<=lastspace)&&(seconditem[1]<=e) ){ \n \n e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}} \n\n\n if(fps1>=xy[0]*xy[1]){if((fps1<=lastspace)&&(seconditem[0]<=e)){\n \n e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}\n \n }if(z===0){z+=1;r-=1}\n }\n print(round);\n"}], "src_uid": "1ad63f41943e40aa8c8d5c88c29c283c"} {"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  — 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$$$) — 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$$$) — 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$$$) — 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": "//↓見なくていいよ!ここから--------------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//↑見なくていいよ!ここまで--------------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = nextInt();\n\t\tvar list = nextIntArray();\n\t\tvar count = 0;\n\t\tlist.sort(function(a,b){\n\t\t\treturn a - b;\n\t\t});\n\t\tfor(var j = 0; j < N; j++){\n\t\t\tif(list[j] <= j + 1){\n\t\t\t\tcount = j + 1;\n\t\t\t}\n\t\t}\n\t\toutput[i] = count + 1;\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = [];\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString.push(inputStdin);\n});\n\nprocess.stdin.on('end', () => {\n inputString = inputString.join('').trim().split('\\n').map(string => string.trim());\n \n //withTiming(main);\n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nconst withTiming = callback => {\n const start = new Date();\n callback();\n console.log(`Took ${new Date() - start} ms`);\n}\n\nfunction main() {\n const n = Math.floor(readline());\n const inputs = [];\n\n for (let i = 0; i < n; i++) {\n const m = parseInt(readline());\n const grannies = readline().split(' ').map(granny => parseInt(granny));\n let possibleGrannies = m + 1, i = 0;\n grannies.sort((a, b) => b - a);\n\n while (grannies[i] >= possibleGrannies) {\n i++;\n possibleGrannies--;\n }\n\n console.log(possibleGrannies);\n }\n}\n\n//1 1 4 5 4 9\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x)\n arr.sort((a, b) => a-b)\n let acc = 1\n let buffer = 0\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "function ladies (n, arr) {\n arr.sort((a, b) => a > b ? 1 : -1);\n let present = 1;\n let itr = 0;\n let j = n - 1;\n\n while (j >= 0 && itr < n) {\n let now = ((j - itr) + 1);\n if (arr[j] <= (now + present - 1)) {\n present += now;\n itr = j + 1;\n j = n - 1;\n }\n else {\n if ((itr === j) || (itr === n-1) || (itr > j)) return present;\n j -= 1;\n }\n }\n return present;\n}\n\nfunction processData(input) {\n let inpArr = input.split(\"\\n\");\n let n = parseInt(inpArr[0]);\n\n for (let i = 1; i < inpArr.length - 1; i += 2) {\n console.log(ladies(parseInt(inpArr[i]), inpArr[i+1].split(' ').map(val => parseInt(val))));\n }\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\n_input = \"\";\nprocess.stdin.on(\"data\", function (input) {\n _input += input;\n});\n\nprocess.stdin.on(\"end\", function () {\n processData(_input);\n});"}], "negative_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = [];\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString.push(inputStdin);\n});\n\nprocess.stdin.on('end', () => {\n inputString = inputString.join('').trim().split('\\n').map(string => string.trim());\n \n //withTiming(main);\n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nconst withTiming = callback => {\n const start = new Date();\n callback();\n console.log(`Took ${new Date() - start} ms`);\n}\n\nfunction main() {\n const n = Math.floor(readline());\n const inputs = [];\n\n for (let i = 0; i < n; i++) {\n const m = parseInt(readline());\n const grannies = readline().split(' ').map(granny => parseInt(granny));\n let currentGrannies = 1, k = 0;\n grannies.sort();\n\n while(k < grannies.length) {\n if (grannies[k] <= currentGrannies) {\n currentGrannies++;\n k++;\n } else {\n let j = grannies[k];\n\n if (grannies[j] <= j + 1) {\n currentGrannies = j + 2;\n k = j + 1;\n } else {\n k = grannies.length;\n }\n }\n }\n console.log(currentGrannies);\n }\n}\n\n//1 1 4 5 5 9\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = [];\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString.push(inputStdin);\n});\n\nprocess.stdin.on('end', () => {\n inputString = inputString.join('').trim().split('\\n').map(string => string.trim());\n \n //withTiming(main);\n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nconst withTiming = callback => {\n const start = new Date();\n callback();\n console.log(`Took ${new Date() - start} ms`);\n}\n\nfunction main() {\n const n = Math.floor(readline());\n const inputs = [];\n\n for (let i = 0; i < n; i++) {\n const m = parseInt(readline());\n const grannies = readline().split(' ').map(granny => parseInt(granny));\n let k = 0, result = grannies.length + 1;\n grannies.sort();\n\n while(k < grannies.length) {\n if (grannies[k] <= k + 1) {\n k++;\n } else {\n let j = grannies[k];\n\n if (grannies[j] <= j + 1) {\n k = j + 1;\n } else {\n result = k + 1;\n k = grannies.length;\n }\n }\n }\n\n console.log(result);\n }\n}\n\n//1 1 4 5 4 9\n"}], "src_uid": "718cea81f609055cece58cae5310f703"} {"nl": {"description": "Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire. Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.", "input_spec": "The first line of the input contains an integer n, (1 ≤ n ≤ 100). The next line contains a list of space-separated integers a1, a2, ..., an, (0 ≤ ai ≤ 100). The third line contains an integer m, (0 ≤ m ≤ 100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1 ≤ xi ≤ n, 1 ≤ yi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment.", "output_spec": "On the i-th line of the output print the number of birds on the i-th wire.", "sample_inputs": ["5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6", "3\n2 4 1\n1\n2 2"], "sample_outputs": ["0\n12\n5\n0\n16", "3\n0\n3"], "notes": null}, "positive_code": [{"source_code": "var n = +readline();\nvar a = ('0 ' + readline() + ' 0').split(' ').map(Number);\nvar m = +readline();\nwhile( m-- ){\n\t+function(x, y){\n\t\ta[x-1] += y-1;\n\t\ta[x+1] += a[x]-y;\n\t\ta[x] = 0;\n\t}.apply(0, readline().split(' ').map(Number));\n}\na.shift();\na.pop();\nprint(a.join('\\n'));"}, {"source_code": "ip = readline().split(\" \");\nn = parseInt(ip[0]);\nA = readline().split(\" \");\nip = readline().split(\" \");\nm = parseInt(ip[0]);\nvar B = new Array();\nfor (var i = 0; i < m; i++){\n\tB[i] = readline().split(\" \");\n\tif (B[i][0]-1 > 0) A[B[i][0]-2] = parseInt(A[B[i][0]-2]) + parseInt(B[i][1]-1);\n\tif (B[i][0]-1 < n-1) A[B[i][0]] = parseInt(A[B[i][0]]) + parseInt(A[B[i][0]-1]) - parseInt(B[i][1]);\n\tA[B[i][0]-1] = 0;\n}\nfor (var i = 0; i < n; i++){\n\twrite(A[i] + \"\\n\");\n}\n"}, {"source_code": "var numberOfLines = readline()\n var lines = readline().split(' ').map(Number)\n var numberOfShoots = readline()\n\n for (var i = 0; i < numberOfShoots; i++) {\n var shootPositions = readline().split(' ').map(Number)\n var lineIndex = shootPositions[0] - 1\n var index = shootPositions[1]\n\n var currentNumberOfBirds = lines[lineIndex]\n\n if (lineIndex - 1 >= 0) lines[lineIndex - 1] += (index - 1)\n if (lineIndex + 1 < lines.length) lines[lineIndex + 1] += currentNumberOfBirds - index\n lines[lineIndex] = 0\n }\n\n for (var i = 0; i < lines.length; i++) {\n print(lines[i])\n }"}, {"source_code": ";(function () {\n\n\tvar n = +readline();\n\tvar a = readline().split(' ').map(Number);\n\tvar m = +readline();\n\tvar x = [];\n\tfor (var i = 0; i < m; i++) x.push( readline().split(' ').map(Number) );\n\n\tfor (var i = 0; i < m; i++) {\n\t\tif (x[i][0] != 1) a[x[i][0] - 2] += x[i][1] - 1;\n\t\tif (x[i][0] != n) a[x[i][0]] += a[x[i][0] - 1] - x[i][1];\n\t\ta[x[i][0] - 1] = 0; // poor bird\n\t}\n\n\tprint( a.join('\\n') );\n\n}).call(this);"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar wireNum = parseInt(readline());\n\tvar wires = tokenizeIntegers(readline());\n\twires.unshift(null);\n\n\tvar jumpNum = parseInt(readline());\n\tfor (var i = 0; i < jumpNum; i += 1) {\n\t\tvar integers = tokenizeIntegers(readline());\n\t\tvar r = integers[0], c = integers[1];\n\t\tif (r > 1) {\n\t\t\twires[r-1] += c-1;\n\t\t}\n\t\tif (r < wireNum) {\n\t\t\twires[r+1] += wires[r]-c;\n\t\t}\n\t\twires[r] = 0;\n\t}\n\n\tprint(wires.slice(1).join('\\n'));\n}\n\nmain();\n"}, {"source_code": "var n = readline(),\n\ta = readline().split(\" \").map(Number),\n\tm = readline(), x = [];\nfor (var i = 0; i < m; i++) {\n\tx[i] = readline().split(\" \").map(Number);\n\tvar v = x[i][0] - 1;\n\ta[v + 1] += a[v] - x[i][1];\n\ta[v] = 0;\n\ta[v - 1] += x[i][1] - 1;\n}\nfor (var i = 0; i < n; i++) {\n\tprint(a[i]);\n}"}, {"source_code": "var wires = parseInt(readline());\nvar arr = readline().split(\" \").map(Number);\nvar shoots = parseInt(readline());\n\nfor (var i = 0; i < shoots; i++) {\n var current = readline().split(\" \").map(Number);\n var k = current[0];\n var n = current[1];\n \n if (k !== 1) { \n arr[k - 2] += n - 1; // arr[k - 2] is nothing but arr[(k - 1) - 1]\n }\n\n if (k !== arr.length) {\n arr[k] += arr[k - 1] - n; // arr[k] is nothing but arr[(k - 1) + 1]\n }\n\n arr[k - 1] = 0;\n}\n\nprint(arr.join(\" \"));"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet lineCounter = 1;\nlet birdsPerLine = [];\nlet shotsArr = [];\nlet numOfShots;\n\nrl.on('line', (input) => {\n if (lineCounter === 1) {\n lineCounter++;\n return;\n }\n if (lineCounter === 2) {\n let line = input.split(' ');\n line.forEach(ele => {\n birdsPerLine.push(parseInt(ele));\n })\n } else if (lineCounter === 3) {\n numOfShots = parseInt(input);\n if (numOfShots === 0) {\n rl.close();\n solve(birdsPerLine, shotsArr);\n birdsPerLine.forEach(ele => {\n console.log(ele);\n })\n }\n } else if (lineCounter <= 3 + numOfShots) {\n let line = input.split(' ');\n shotsArr.push([parseInt(line[0]), parseInt(line[1])]);\n if (lineCounter === 3 + numOfShots) {\n rl.close();\n solve(birdsPerLine, shotsArr);\n birdsPerLine.forEach(ele => {\n console.log(ele);\n })\n }\n }\n lineCounter++;\n});\n\n\n\nconst solve = (birdsPerLine, shotsArr) => {\n shotsArr.forEach(shot => {\n let line = shot[0];\n let shootedBird = shot[1];\n let currentBirds = birdsPerLine[line - 1];\n let leftBird = shootedBird - 1;\n let rightBirds = currentBirds - shootedBird;\n birdsPerLine[line - 1] = 0;\n if (birdsPerLine[line - 2] || birdsPerLine[line - 2] === 0) birdsPerLine[line - 2] += leftBird;\n if (birdsPerLine[line] || birdsPerLine[line] === 0) birdsPerLine[line] += rightBirds;\n });\n\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n const n = +readline();\n const a = readline().split(' ').map(x => parseInt(x));\n const m = +readline();\n for (let i = 0; i < m; i++) {\n const [x, y] = readline().split(' ').map(x => parseInt(x));\n if (x !== 1) {\n a[x-1-1] += y - 1;\n }\n if (x !== n) {\n a[x+1-1] += a[x-1] - y;\n }\n a[x-1] = 0;\n }\n // output\n a.forEach(x => print(`${x}\\n`));\n}\n\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet wires;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c === 1) {\n c++;\n wires = d.split(' ').map(Number);\n return;\n }\n\n if (c == 2) {\n c++;\n return;\n }\n\n const [x, y] = d.split(' ').map(Number);\n let curr = x - 1;\n let up = curr - 1;\n let down = curr + 1;\n\n let birds = wires[curr];\n let upBirds = y - 1;\n let downBirds = birds - y;\n wires[curr] = 0;\n\n if (wires[up] !== undefined) {\n wires[up] = wires[up] + upBirds;\n }\n\n if (wires[down] !== undefined) {\n wires[down] = wires[down] + downBirds;\n }\n c++;\n});\n\nrl.on('close', () => {\n for (let i = 0; i < wires.length; i++) {\n console.log(wires[i]);\n }\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet wires;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c === 1) {\n c++;\n wires = [0, ...d.split(' ').map(Number), 0];\n return;\n }\n\n if (c == 2) {\n c++;\n return;\n }\n\n const [x, y] = d.split(' ').map(Number);\n\n wires[x - 1] += y - 1;\n wires[x + 1] += wires[x] - y;\n wires[x] = 0;\n\n c++;\n});\n\nrl.on('close', () => {\n for (let i = 1; i < wires.length - 1; i++) {\n console.log(wires[i]);\n }\n});\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readint() {\n let line = readline().split(' ').map(function(num) {\n return parseInt(num);\n });\n return line;\n}\n\nfunction readfloat() {\n let line = readline().split(' ').map(function(num) {\n return parseFloat(num);\n });\n return line;\n}\n\nfunction print(x) {\n console.log(x);\n}\n\nfunction write(x) {\n process.stdout.write(x);\n}\nfunction main() {\n let n = parseInt(readline());\n let a = readint();\n let m = parseInt(readline());\n let xy = [];\n for (let i = 0; i < m; i++) {\n let xly = readint();\n xy.push(xly); \n }\n for (let i = 0; i < m; i++) { \n \n let x = xy[i][0];\n let y = xy[i][1];\n x--;\n y--;\n if(x != 0) {\n a[x - 1] += y;\n }\n if(x != n - 1) {\n a[x + 1] += a[x] - y - 1;\n }\n a[x] = 0;\n }\n for (let i = 0; i < a.length; i++) {\n write(a[i] + \"\\n\"); \n } \n}"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nconst mapFunc = (arr) => {\n return arr.map((b) => parseInt(b));\n}\nlet input = [];\nreadline.on('line', line => {\n input.push(line);\n});\nprocess.stdin.on('end', () => {\nconst n = parseInt(input[0], 10);\nlet a = input[1].split(' ');\na = a.map((b) => parseInt(b));\nconst m = parseInt(input[2], 10);\nfor (let i=3; i < m+3; i++) {\n let xy = input[i].split(' ');\n xy = mapFunc(xy);\n xy[0] -= 1;\n const wentUp = xy[1] - 1;\n const wentDown = parseInt(a[xy[0]], 10) - wentUp - 1;\n if (xy[0] > 0) {\n a[xy[0] - 1] = a[xy[0] - 1] + wentUp;\n }\n if (xy[0] < n-1) {\n a[xy[0] + 1] = a[xy[0] + 1] + wentDown;\n }\n a[xy[0]] = 0;\n}\nfor (const e of a) {\n console.log(e);\n}\n});"}], "negative_code": [{"source_code": "ip = readline().split(\" \");\nn = parseInt(ip[0]);\nA = readline().split(\" \");\nip = readline().split(\" \");\nm = parseInt(ip[0]);\nvar B = new Array();\nfor (var i = 0; i < m; i++){\n\tB[i] = readline().split(\" \");\n\tif (B[i][0]-1 > 0) A[B[i][0]-2] += B[i][1]-1;\n\tif (B[i][0]-1 < n-1) A[B[i][0]] += A[B[i][0]-1] - B[i][1];\n\tA[B[i][0]-1] = 0;\n}\nfor (var i = 0; i < n; i++){\n\twrite(A[i] + \"\\n\");\n}\n"}, {"source_code": ";(function () {\n\n\tvar n = +readline();\n\tvar a = readline().split(' ').map(Number);\n\tvar m = +readline();\n\tvar x = [];\n\tfor (var i = 0; i < m; i++) x.push( readline().split(' ').map(Number) );\n\n\tfor (var i = 0; i < m; i++) {\n\t\tif (x[i][0] != 1) a[x[i][0] - 2] += x[i][1] - 1;\n\t\tif (x[i][0] != n) a[x[i][0] - 1] += a[x[i][0] - 1] - x[i][1];\n\t\ta[x[i][0] - 1] = 0; // poor bird :-(\n\t}\n\n\tprint( a.join('\\n') );\n\n}).call(this);"}, {"source_code": "var wires = parseInt(readline());\nvar arr = readline().split(\" \").map(Number);\nvar shoots = parseInt(readline());\n\nfor (var i = 0; i < shoots; i++) {\n var current = readline().split(\" \").map(Number);\n var k = current[0];\n var n = current[1];\n \n if (arr[(k -1) -1]) { \n arr[(k -1) -1] += n - 1;\n }\n\n if (arr[(k - 1) + 1]) {\n arr[(k - 1) + 1] += arr[k - 1] - n;\n }\n\n arr[k - 1] = 0;\n}\n\nprint(arr.join(\" \"));"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet lineCounter = 1;\nlet birdsPerLine = [];\nlet shotsArr = [];\nlet numOfShots;\n\nrl.on('line', (input) => {\n if (lineCounter === 1) {\n lineCounter++;\n return;\n }\n if (lineCounter === 2) {\n let line = input.split(' ');\n line.forEach(ele => {\n birdsPerLine.push(parseInt(ele));\n })\n } else if (lineCounter === 3) {\n numOfShots = parseInt(input);\n } else if (lineCounter <= 3 + numOfShots) {\n let line = input.split(' ');\n shotsArr.push([parseInt(line[0]), parseInt(line[1])]);\n if (lineCounter === 3 + numOfShots) {\n rl.close();\n solve(birdsPerLine, shotsArr);\n birdsPerLine.forEach(ele => {\n console.log(ele);\n })\n }\n }\n lineCounter++;\n});\n\n\n\nconst solve = (birdsPerLine, shotsArr) => {\n shotsArr.forEach(shot => {\n let line = shot[0];\n let shootedBird = shot[1];\n let currentBirds = birdsPerLine[line - 1];\n let leftBird = shootedBird - 1;\n let rightBirds = currentBirds - shootedBird;\n birdsPerLine[line - 1] = 0;\n if (birdsPerLine[line - 2] || birdsPerLine[line - 2] === 0) birdsPerLine[line - 2] += leftBird;\n if (birdsPerLine[line] || birdsPerLine[line] === 0) birdsPerLine[line] += rightBirds;\n });\n\n}"}], "src_uid": "859d66fc2c204a8c002012b1fb206645"} {"nl": {"description": "Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 > c_1$$$, then to some other city $$$c_3 > c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k > c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \\dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \\le b_i \\le 4 \\cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.", "output_spec": "Print one integer — the maximum beauty of a journey Tanya can choose.", "sample_inputs": ["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"], "sample_outputs": ["26", "400000", "55"], "notes": "NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$."}, "positive_code": [{"source_code": "const processData = (lines) => {\n const b = lines[1].split(' ')\n .map((x, index) => x-index)\n .reduce((r, x, index) => {r[x] = (r[x] || 0) + (x + index); return r }, {})\n console.log(Math.max.apply(null, Object.values(b)))\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}], "negative_code": [], "src_uid": "aab8d5a2d42b4199310f3f535a6b3bd7"} {"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 ≤ n ≤ 105, ) — 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 + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — 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": "var input = readline().split(\" \").map(Number), n = input[0], d = input[1], arr = [];\nfor(var i = 0; i < n; i++){\n arr.push(readline().split(\" \").map(Number));\n}\nvar ans = 0;\n\narr.sort(function(a,b){return a[0]-b[0]});\n\nvar a = 0;\nfor(var i = 0; i < n; i++){\n arr[i][1] += a;\n a = arr[i][1];\n}\ndelete a;\n\nfor(var i = 0; i < n; i++){\n var l = i;\n var r = n-1;\n\n while(r-l > 2){\n var m = Math.floor((r+l)/2);\n\n if(arr[m][0] < arr[i][0] + d){\n l = m;\n }\n else{\n r = m;\n }\n }\n\n while(l < r){\n if(arr[l][0] < arr[i][0] + d){\n l++;\n }\n else{\n r = l;\n }\n }\n\n if(arr[l][0] >= arr[i][0] + d){\n l--;\n }\n\n var numb;\n\n if(i == 0){\n numb = arr[l][1];\n }\n else{\n numb = arr[l][1] - arr[i-1][1]\n }\n\n var ans = Math.max(ans, numb);\n}\n\nwrite(ans);"}, {"source_code": "var inp = readline().split(' ');\nvar n = parseInt(inp[0], 10);\nvar d = parseInt(inp[1], 10);\nvar friends = [];\n\nfor (var i = 0; i < n; i++) {\n\tinp = readline().split(' ');\n\tfriends.push({\n\t\tm: parseInt(inp[0], 10),\n\t\ts: parseInt(inp[1], 10)\n\t});\n}\n\nfriends = friends.sort(function (a, b) {\n\treturn a.m - b.m;\n});\n\nvar result = count(friends, d);\n\nwrite(result);\n\nfunction count(friends, d) {\n\tvar maxF = 0;\n\tvar m = 0;\n\tvar s = 0;\n\tvar f = friends[s].s;\n\n\twhile (s < friends.length - 1) {\n\t\ts++;\n\t\tf += friends[s].s;\n\t\tif (friends[s].m - friends[m].m >= d) {\n\t\t\tmaxF = Math.max(maxF, f - friends[s].s);\n\t\t\twhile (friends[s].m - friends[m].m >= d) {\n\t\t\t\tf -= friends[m].s;\n\t\t\t\tm++;\n\t\t\t}\n\t\t}\n\t}\n\tmaxF = Math.max(maxF, f);\n\treturn maxF;\n}\n"}, {"source_code": "function main() {\n var line = readline().split(' ').map(Number);\n var n = line[0];\n var d = line[1];\n var friends = [];\n for(var i=0;ia[0]-b[0]);\n var startIndex = 0;\n var max = 0;\n var sum = 0;\n for(var i=0;i= d){\n sum -= friends[startIndex][1];\n startIndex++;\n \n }\n sum += friends[i][1];\n if(sum > max){\n max = sum;\n }\n }\n print(max)\n}\n\n\nmain()"}, {"source_code": "var parsedLine = readline().split(\" \");\nvar n = parseInt(parsedLine[0]);\nvar d = parseInt(parsedLine[1]);\n\nvar friends = [];\nfor (var i = 0; i < n; i++) {\n parsedLine = readline().split(\" \");\n friends.push({\n m: parseInt(parsedLine[0]),\n s: parseInt(parsedLine[1])\n });\n}\nfriends.sort(function(f1, f2) { return f1.m - f2.m; });\n\nvar sums = [0];\nfriends.forEach(function(f, i) { sums.push(f.s + sums[i]); });\n\nvar max = 0;\nfriends.forEach(function(f, i, arr) {\n var j = binarySearch(i, arr.length, function(k) {\n return arr[k].m >= arr[i].m + d;\n });\n var sum = sums[j] - sums[i];\n max = sum > max ? sum : max;\n});\n\nprint(max);\n\nfunction binarySearch(start, end, callback) {\n while(end > start + 1) {\n var mid = start + parseInt((end-start)/2);\n if (callback(mid)) {\n end = mid;\n } else {\n start = mid;\n }\n }\n return end;\n}\n"}], "negative_code": [{"source_code": "var input = readline().split(\" \").map(Number), n = input[0], d = input[1], arr = [];\nfor(var i = 0; i < n; i++){\n arr.push(readline().split(\" \").map(Number));\n}\nvar ans = 0;\n\narr.sort(function(a,b){return a[0]-b[0]});\n\nvar a = 0;\nfor(var i = 0; i < n; i++){\n arr[i][1] += a;\n a = arr[i][1];\n}\ndelete a;\n\nfor(var i = 0; i < n; i++){\n var l = i;\n var r = n-1;\n\n while(r-l > 2){\n var m = Math.floor((r+l)/2);\n\n if(arr[m][0] < arr[m][0] + d){\n l = m;\n }\n else{\n r = m;\n }\n }\n\n while(l < r){\n if(arr[l][0] < arr[i][0] + d){\n l++;\n }\n else{\n r = l;\n }\n }\n\n if(arr[l][0] >= arr[i][0] + d){\n l--;\n }\n\n var numb;\n\n if(i == 0){\n numb = arr[l][1];\n }\n else{\n numb = arr[l][1] - arr[i-1][1]\n }\n\n var ans = Math.max(ans, numb);\n}\n\nwrite(ans);"}, {"source_code": "var inp = readline().split(' ');\nvar n = parseInt(inp[0], 10);\nvar d = parseInt(inp[1], 10);\nvar friends = [];\n\nfor (var i = 0; i < n; i++) {\n\tinp = readline().split(' ');\n\tfriends.push({\n\t\tm: parseInt(inp[0], 10),\n\t\ts: parseInt(inp[1], 10)\n\t});\n}\n\nfriends = friends.sort(function (a, b) {\n\treturn a.m > b.m;\n});\n\nvar result = count(friends, d);\n\nwrite(result);\n\nfunction count(friends, d) {\n\tvar maxF = 0;\n\tvar m = 0;\n\tvar s = 0;\n\tvar f = friends[s].s;\n\n\twhile (s < friends.length - 1) {\n\t\ts++;\n\t\tf += friends[s].s;\n\t\tif (friends[s].m - friends[m].m >= d) {\n\t\t\tmaxF = Math.max(maxF, f - friends[s].s);\n\t\t\twhile (friends[s].m - friends[m].m >= d) {\n\t\t\t\tf -= friends[m].s;\n\t\t\t\tm++;\n\t\t\t}\n\t\t}\n\t}\n\tmaxF = Math.max(maxF, f);\n\treturn maxF;\n}\n"}], "src_uid": "38fe0e19974a7bc60153793b9060369a"} {"nl": {"description": "Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $$$0$$$. Also, let's say that the train will visit $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$ along its way, and that Alexey destination is the station $$$n$$$.Alexey learned from the train schedule $$$n$$$ integer pairs $$$(a_i, b_i)$$$ where $$$a_i$$$ is the expected time of train's arrival at the $$$i$$$-th station and $$$b_i$$$ is the expected time of departure.Also, using all information he has, Alexey was able to calculate $$$n$$$ integers $$$tm_1, tm_2, \\dots, tm_n$$$ where $$$tm_i$$$ is the extra time the train need to travel from the station $$$i - 1$$$ to the station $$$i$$$. Formally, the train needs exactly $$$a_i - b_{i-1} + tm_i$$$ time to travel from station $$$i - 1$$$ to station $$$i$$$ (if $$$i = 1$$$ then $$$b_0$$$ is the moment the train leave the terminal, and it's equal to $$$0$$$).The train leaves the station $$$i$$$, if both conditions are met: it's on the station for at least $$$\\left\\lceil \\frac{b_i - a_i}{2} \\right\\rceil$$$ units of time (division with ceiling); current time $$$\\ge b_i$$$. Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of arrival at the station $$$n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) — the number of stations. Next $$$n$$$ lines contain two integers each: $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i < b_i \\le 10^6$$$). It's guaranteed that $$$b_i < a_{i+1}$$$. Next line contains $$$n$$$ integers $$$tm_1, tm_2, \\dots, tm_n$$$ ($$$0 \\le tm_i \\le 10^6$$$).", "output_spec": "For each test case, print one integer — the time of Alexey's arrival at the last station.", "sample_inputs": ["2\n2\n2 4\n10 12\n0 2\n5\n1 4\n7 8\n9 10\n13 15\n19 20\n1 2 3 4 5"], "sample_outputs": ["12\n32"], "notes": "NoteIn the first test case, Alexey arrives at station $$$1$$$ without any delay at the moment $$$a_1 = 2$$$ (since $$$tm_1 = 0$$$). After that, he departs at moment $$$b_1 = 4$$$. Finally, he arrives at station $$$2$$$ with $$$tm_2 = 2$$$ extra time, or at the moment $$$12$$$.In the second test case, Alexey arrives at the first station with $$$tm_1 = 1$$$ extra time, or at moment $$$2$$$. The train, from one side, should stay at the station at least $$$\\left\\lceil \\frac{b_1 - a_1}{2} \\right\\rceil = 2$$$ units of time and from the other side should depart not earlier than at moment $$$b_1 = 4$$$. As a result, the trains departs right at the moment $$$4$$$.Using the same logic, we can figure out that the train arrives at the second station at the moment $$$9$$$ and departs at the moment $$$10$$$; at the third station: arrives at $$$14$$$ and departs at $$$15$$$; at the fourth: arrives at $$$22$$$ and departs at $$$23$$$. And, finally, arrives at the fifth station at $$$32$$$."}, "positive_code": [{"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction solve() {\r\n var n = Number(read());\r\n var a = [];\r\n var b = [];\r\n for (var i = 0; i < n; i++) {\r\n var ab = readArray(Number);\r\n a[i] = ab[0];\r\n b[i] = ab[1];\r\n }\r\n var tm = readArray(Number);\r\n var time = 0;\r\n for (var i = 0; i < n; i++) {\r\n time += tm[i] + a[i] - (b[i - 1] || 0);\r\n if (i < n - 1) {\r\n time += (b[i] - a[i] + 1) >> 1;\r\n if (time < b[i]) {\r\n time = b[i];\r\n }\r\n }\r\n }\r\n write(time);\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n var n = parseInt(readline())\r\n\r\n var x = []\r\n var y = []\r\n for (let i = 0; i < n; i++) {\r\n var [xx, yy] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n y.push(yy)\r\n x.push(xx)\r\n }\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n var ans = 0\r\n var ans1 = 0\r\n for (let i = 0; i < n; i++) {\r\n if (i === 0) {\r\n ans += x[i] - 0 + a[i]\r\n } else {\r\n ans += x[i] - y[i - 1] + a[i]\r\n }\r\n ans1 = ans\r\n ans += Math.ceil((y[i] - x[i]) / 2)\r\n\r\n ans = Math.max(y[i], ans)\r\n }\r\n\r\n // if(n>=1) ans-=a[n-1]\r\n\r\n console.log(ans1)\r\n\r\n })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = new Array(N + 1);\r\n\t\tlist[0] = {\r\n\t\t\ta : 0,\r\n\t\t\tb : 0,\r\n\t\t\tv : 0\r\n\t\t};\r\n\t\tfor(var j = 1; j <= N; j++){\r\n\t\t\tlist[j] = {\r\n\t\t\t\ta : nextInt(),\r\n\t\t\t\tb : nextInt(),\r\n\t\t\t\tv : 0\r\n\t\t\t};\r\n\t\t}\r\n\t\tfor(var j = 1; j <= N; j++){\r\n\t\t\tlist[j].v = nextInt();\r\n\t\t}\r\n\t\tvar now = 0;\r\n\t\tfor(var j = 1; j <= N; j++){\r\n\t\t\tnow += list[j].a - list[j - 1].b + list[j].v;\r\n\t\t\tif(j == N){\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tnow += Math.ceil((list[j].b - list[j].a) / 2);\r\n\t\t\tif(list[j].b > now){\r\n\t\t\t\tnow = list[j].b;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(now);\r\n\t}\r\n}\r\n"}, {"source_code": "function getInt(num){\r\n return parseInt(num, 10);\r\n }\r\nvar t = parseInt(readline(), 10);\r\nfor(var it = 0; it b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction solve() {\r\n var n = Number(read());\r\n var a = [];\r\n var b = [];\r\n for (var i = 0; i < n; i++) {\r\n var ab = readArray(Number);\r\n a[i] = ab[0];\r\n b[i] = ab[1];\r\n }\r\n var tm = readArray(Number);\r\n var total = a[0] + tm[0] + n;\r\n for (var i = 1; i < n; i++) {\r\n write(total);\r\n total += a[i] + tm[i] - b[i - 1];\r\n }\r\n write(total + '\\n' );\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}], "src_uid": "42840fc873369e0d0d6a4ad24a43f5a6"} {"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 ≤ n, k ≤ 100) — 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 — 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 — 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": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let lengthMap = new Map()\n for (let i = 0; i < numOfPasswords; i++) {\n const passwordLength = readline().length\n lengthMap.set(passwordLength, (lengthMap.get(passwordLength) || 0) + 1)\n }\n\n const correct = readline();\n\n helper(lengthMap, tries, correct.length)\n}\n\nfunction helper(lengthMap, tries, correctLength) {\n let best = 0\n for (let i = 1; i < correctLength; i++) {\n if (lengthMap.has(i)) {\n best += lengthMap.get(i)\n }\n }\n let worst = best + lengthMap.get(correctLength) - 1;\n\n best += Math.floor(best / tries) * 5\n worst += Math.floor(worst / tries) * 5\n\n console.log((best + 1) + ' ' + (worst + 1))\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const nums = readline().split(\" \").map(x => parseInt(x));\n const n = nums[0];\n const k = nums[1];\n const passwordLengths = new Map();\n for (let i=0; i a[0]-b[0])) {\n if (key {\n if (key < len_pwd) {\n min_try += value\n }\n if (key <= len_pwd) {\n max_try += value\n }\n\n});\nprint([min_try + ((min_try - 1) / k | 0) * 5, max_try + ((max_try - 1)/ k | 0) * 5].join(' '));"}, {"source_code": "function readIntTabLine() {\n var l = readline().split(' ')\n for (var i = 0 ; i < l.length ; i++) {\n l[i] = parseInt(l[i])\n }\n return l\n}\n\nvar given = readIntTabLine(),\n mdps = []\n\nfor (var i = 0 ; i < given[0] ; i++) {\n mdps.push(readline())\n}\n\nvar good = readline()\n\nmdps.sort((a,b) => a.length-b.length)\nvar imin = imax = mdps.findIndex((v,i,a) => v.length==good.length),\n min = Math.floor(imin/given[1])*5 + imin + 1\nwhile (imax < mdps.length && mdps[imax].length == good.length) imax++\nvar max = Math.floor((imax-1)/given[1])*5 + imax\n\nprint(min,max)\n"}, {"source_code": "//Define variable and get input\nvar stats = readline().split(' '), \n count = +stats[0], \n fail = +stats[1], \n i, answer,\n input = [],\n out = \"\";\n \nfor (i = 0; i < count; i++){\n input.push(readline());\n}\n\nanswer = readline();\n// Define helper function\nfunction getFail(){\n var _fail = 0;\n for(i = fail; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n//Begin\nworst = input.filter(function(a){\n return ((a).toString().length <= (answer).toString().length);\n});\ninput = input.filter(function(a){\n return ((a).toString().length < (answer).toString().length)\n || a === (answer);\n \n});\ncount = input.length;\nif (input.length < fail){\n out += input.length + \" \";\n}\nelse {\n out+= ((getFail() * 5) + count) + \" \";\n}\ncount = worst.length;\nout += (count <= fail ? count : ((getFail() * 5) + count));\n\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = fail; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n worst = input.filter(function(a){\n return ((a).toString().length <= (answer||'22').toString().length);\n });\n input = input.filter(function(a){\n return ((a).toString().length < (answer||'22').toString().length)\n || a === (answer || '22');\n \n });\n count = input.length;\n if (input.length < fail){\n out += input.length + \" \";\n }\n else {\n out+= ((getFail() * 5) + count) + \" \";\n }\n count = worst.length;\n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "//Define variable and get input\nvar stats = readline().split(' '), \n count = +stats[0], \n fail = +stats[1], \n i, answer,\n input = [],\n out = \"\";\n \nfor (i = 0; i < count; i++){\n input.push(readline());\n}\n\nanswer = readline();\n// Define helper function\nfunction getFail(){\n var _fail = 0;\n for(i = fail; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nif (count === 1){\n out = '1 1';\n} \nelse {\n worst = input.filter(function(a){\n return ((a).toString().length <= (answer||'22').toString().length);\n });\n input = input.filter(function(a){\n return ((a).toString().length < (answer||'22').toString().length)\n || a === (answer || '22');\n \n });\n count = input.length;\n if (input.length < fail){\n out += input.length + \" \";\n }\n else {\n out+= ((getFail() * 5) + count) + \" \";\n }\n count = worst.length;\n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}], "negative_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let lengthMap = new Map()\n for (let i = 0; i < numOfPasswords; i++) {\n const passwordLength = readline().length\n lengthMap.set(passwordLength, (lengthMap.get(passwordLength) || 0) + 1)\n }\n\n const correct = readline();\n\n helper(lengthMap, tries, correct.length)\n}\n\nfunction helper(lengthMap, tries, correctLength) {\n let tryTimes = 0\n for (let i = 1; i < correctLength; i++) {\n if (lengthMap.has(i)) {\n tryTimes += lengthMap.get(i)\n }\n }\n let best = tryTimes + 1 + (tryTimes + 1 > tries ? Math.floor(tryTimes + 1 / tries) * 5 : 0)\n\n tryTimes += lengthMap.get(correctLength)\n\n let worse = tryTimes + (tryTimes > tries ? Math.floor(tryTimes / tries) * 5 : 0)\n\n console.log(best + ' ' + worse)\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let passwords = []\n for (let i = 0; i < numOfPasswords; i++) {\n passwords.push(readline())\n }\n \n const correct = readline();\n\n helper(passwords, tries, correct)\n}\n\nfunction helper(passwords, tries, correct) {\n passwords.sort((p1,p2)=>p1.length - p2.length)\n\n console.log(passwords)\n\n let i = 0\n let cnt = 0\n let min = 0\n\n while (correct.length !== passwords[i].length) {\n i++\n cnt++\n min++\n if (cnt === tries) {\n min += 5\n cnt = 0\n }\n }\n\n let max = min\n while (i < passwords.length && correct.length >= passwords[i].length) {\n i++\n cnt++\n max++\n if (cnt === tries) {\n max += 5\n cnt = 0\n }\n }\n\n console.log(min + ' ' + max)\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let passwords = []\n for (let i = 0; i < numOfPasswords; i++) {\n passwords.push(readline())\n }\n \n const correct = readline();\n\n helper(passwords, tries, correct)\n}\n\nfunction helper(passwords, tries, correct) {\n passwords.sort((p1,p2)=>p1.length - p2.length)\n\n let i = 0\n let cnt = 0\n let min = 1\n\n while (correct.length !== passwords[i].length) {\n i++\n cnt++\n min++\n if (cnt === tries) {\n min += 5\n cnt = 0\n }\n }\n \n let max = min - 1\n while (i < passwords.length && correct.length >= passwords[i].length) {\n i++\n cnt++\n max++\n if (cnt === tries) {\n max += 5\n cnt = 0\n }\n }\n\n console.log(min + ' ' + max)\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let passwords = []\n for (let i = 0; i < numOfPasswords; i++) {\n passwords.push(readline())\n }\n \n const correct = readline();\n \n helper(passwords, tries, correct)\n}\n\nfunction helper(passwords, tries, correct) {\n if (passwords.length === 1) return 1\n passwords.sort((p1,p2)=>p1.length - p2.length)\n\n let i = 0\n let cnt = 0\n let min = 1\n\n while (correct.length !== passwords[i].length) {\n if (cnt === tries) {\n min += 5\n cnt = 0\n }\n i++\n cnt++\n min++\n }\n \n let max = min - 1\n while (i < passwords.length && correct.length >= passwords[i].length) {\n if (cnt === tries) {\n max += 5\n cnt = 0\n }\n i++\n cnt++\n max++\n }\n\n console.log(min + ' ' + max)\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let passwords = []\n for (let i = 0; i < numOfPasswords; i++) {\n passwords.push(readline())\n }\n \n const correct = readline();\n\n helper(passwords, tries, correct)\n}\n\nfunction helper(passwords, tries, correct) {\n passwords.sort((p1,p2)=>p1.length - p2.length)\n\n let i = 0\n let cnt = 0\n let min = 0\n do {\n i++\n cnt++\n min++\n if (cnt === tries) {\n min += 5\n cnt = 0\n }\n } while (correct.length !== passwords[i].length)\n\n let max = min\n while (i < passwords.length && correct.length >= passwords[i].length) {\n i++\n cnt++\n max++\n if (cnt === tries) {\n max += 5\n cnt = 0\n }\n }\n\n console.log(min + ' ' + max)\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let passwords = []\n for (let i = 0; i < numOfPasswords; i++) {\n passwords.push(readline())\n }\n \n const correct = readline();\n \n helper(passwords, tries, correct)\n}\n\nfunction helper(passwords, tries, correct) {\n if (passwords.length === 1) {\n console.log('1 1')\n return\n }\n passwords.sort((p1,p2)=>p1.length - p2.length)\n\n let i = 0\n let cnt = 0\n let min = 1\n\n while (correct.length !== passwords[i].length) {\n if (cnt === tries) {\n min += 5\n cnt = 0\n }\n i++\n cnt++\n min++\n }\n\n let max = min - 1\n while (i < passwords.length && correct.length >= passwords[i].length) {\n if (cnt === tries) {\n max += 5\n cnt = 0\n }\n i++\n cnt++\n max++\n }\n\n console.log(min + ' ' + max)\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let passwords = []\n for (let i = 0; i < numOfPasswords; i++) {\n passwords.push(readline())\n }\n \n const correct = readline();\n \n helper(passwords, tries, correct)\n}\n\nfunction helper(passwords, tries, correct) {\n if (passwords.length === 1) {\n console.log('1 1')\n return\n }\n passwords.sort((p1,p2)=>p1.length - p2.length)\n\n let i = 0\n let cnt = 0\n let min = 1\n\n while (correct.length !== passwords[i].length) {\n i++\n cnt++\n min++\n if (cnt === tries) {\n min += 5\n cnt = 0\n }\n }\n \n let max = min - 1\n while (i < passwords.length && correct.length >= passwords[i].length) {\n i++\n cnt++\n max++\n if (cnt === tries) {\n max += 5\n cnt = 0\n }\n }\n\n console.log(min + ' ' + max)\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(inp => parseInt(inp));\n const [numOfPasswords, tries] = input\n let passwords = []\n for (let i = 0; i < numOfPasswords; i++) {\n passwords.push(readline())\n }\n \n const correct = readline();\n\n helper(passwords, tries, correct)\n}\n\nfunction helper(passwords, tries, correct) {\n passwords.sort((p1,p2)=>p1.length - p2.length)\n\n let i = 0\n let cnt = 0\n let min = 0\n\n while (correct.length !== passwords[i].length) {\n i++\n cnt++\n min++\n if (cnt === tries) {\n min += 5\n cnt = 0\n }\n }\n\n let max = min\n while (i < passwords.length && correct.length >= passwords[i].length) {\n i++\n cnt++\n max++\n if (cnt === tries) {\n max += 5\n cnt = 0\n }\n }\n\n console.log(min + ' ' + max)\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const nums = readline().split(\" \").map(x => parseInt(x));\n const n = nums[0];\n const k = nums[1];\n const passwordLengths = new Map();\n for (let i=0; i {\n if (key < len_pwd) {\n min_try += value\n }\n if (key <= len_pwd) {\n max_try += value\n }\n});\nprint([min_try + (min_try / k | 0) * 5, max_try + (max_try / k | 0) * 5].join(' '));"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer||11).toString().length});\n count = input.length;\n \n out += input.length+1 + \" \";\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n\n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + ((getFail() * 5) + count);\n \n}\nelse {\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n \n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count < fail ? count : ((getFail() * 5) + count))\n}\nprint(out);\n\n"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer || 100).toString().length});\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n\n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + ((Math.floor(count/fail) * 5) + count);\n \n}\nelse {\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n \n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count < fail ? count : ((Math.floor(count/fail) * 5) + count))\n}\nprint(out);\n\n"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer||10).toString().length});\n input = input.sort(function(a,b){return (a).toString().length > (b).toString().length;});\n count = input.length;\n print(input.toString());\n input.forEach(function(a, i){\n if (a === answer) out += i+1 + \" \";\n });\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer||111).toString().length});\n count = input.length;\n input = input.filter(function(a){return (a).toString().length < (answer||101).toString().length});\n \n if (input.length < fail){\n out += input.length+1 + \" \";\n }\n else {\n out+= ((getFail() * 5) + count) + \" \";\n }\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer).toString().length});\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n\n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (sameLength){\n out = \"1 \" + ((Math.floor(count/fail) * 5) + count);\n \n}\nelse {\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n \n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count < fail ? count : ((Math.floor(count/fail) * 5) + count))\n}\nprint(out);\n\n"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer).toString().length});\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n count = input.length;\n input.forEach(function(a, i){\n if (a === answer) out += i+1 + \" \";\n });\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer||10).toString().length});\n count = input.length;\n input = input.filter(function(a){return (a).toString().length < (answer||10).toString().length});\n \n out += input.length+1 + \" \";\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\n\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.filter(function(a){return (a).toString().length <= (answer).toString().length});\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n count = input.length;\n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);"}, {"source_code": "var stats = readline().split(' '), count = +stats[0], fail = +stats[1], i, input = [], answer, out = \"\";\nfor (i = 0; i < count; i++){\n input.push(readline());\n}\nanswer = readline();\nfunction getFail(){\n var _fail = 0;\n for(i = 1; i < count; i+=fail){\n _fail++;\n }\n return _fail;\n}\n\nvar sameLength = input.every(function(a){\n return (a).toString().length === (input[0]).toString().length; \n});\n\nif (count === 1){\n out = '1 1';\n} \nelse if (sameLength){\n out = \"1 \" + (count <= fail ? count : ((getFail() * 5) + count));\n \n}\nelse {\n input = input.sort(function(a,b){return (a).toString() > (b).toString();});\n \n input.forEach(function(a, i){\n if (a === answer) out += i + \" \";\n });\n \n out += (count <= fail ? count : ((getFail() * 5) + count))\n}\nprint(out);\n\n"}], "src_uid": "06898c5e25de2664895f512f6b766915"} {"nl": {"description": "A pair of positive integers $$$(a,b)$$$ is called special if $$$\\lfloor \\frac{a}{b} \\rfloor = a \\bmod b$$$. Here, $$$\\lfloor \\frac{a}{b} \\rfloor$$$ is the result of the integer division between $$$a$$$ and $$$b$$$, while $$$a \\bmod b$$$ is its remainder.You are given two integers $$$x$$$ and $$$y$$$. Find the number of special pairs $$$(a,b)$$$ such that $$$1\\leq a \\leq x$$$ and $$$1 \\leq b \\leq y$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. The only line of the description of each test case contains two integers $$$x$$$, $$$y$$$ ($$$1 \\le x,y \\le 10^9$$$).", "output_spec": "For each test case print the answer on a single line.", "sample_inputs": ["9\n3 4\n2 100\n4 3\n50 3\n12 4\n69 420\n12345 6789\n123456 789\n12345678 9"], "sample_outputs": ["1\n0\n2\n3\n5\n141\n53384\n160909\n36"], "notes": "NoteIn the first test case, the only special pair is $$$(3, 2)$$$.In the second test case, there are no special pairs.In the third test case, there are two special pairs: $$$(3, 2)$$$ and $$$(4, 3)$$$."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [x, y] = readline().split(' ').map((x, i) => {\r\n // if (minA > Number(x)) minA = Number(x)\r\n return parseInt(x)\r\n })\r\n var a = 0\r\n var answer = 0\r\n\r\n var sqrt = Math.floor(Math.sqrt(x))\r\n\r\n for (var k = 1; k <= sqrt; k++) {\r\n answer += Math.max(0, Math.min(y, Math.floor(x / k) - 1) - k)\r\n }\r\n console.log(answer)\r\n })\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "efdb966e414050c5e51e8beb7bb06b20"} {"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 ≤ n ≤ 105) — the number of laptops. Next n lines contain two integers each, ai and bi (1 ≤ ai, bi ≤ n), 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": "const input = [];\n\nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n \nRL.on('line', (line) => {\n input.push(line);\n});\n\nRL.on('close', () => {\n const [n] = input[0].split(' ').map(x => parseInt(x));\n\n const pairs = [];\n for (let i = 1; i <= n; i += 1) {\n const [a, b] = input[i].split(' ').map(x => parseInt(x));\n pairs.push([a, b]);\n }\n\n pairs.sort( (a, b) => a[0] - b[0] );\n\n let flag = false;\n for (let i = 1; i < pairs.length; i += 1) {\n if (pairs[i][1] < pairs[i-1][1]) {\n flag = true; break;\n } \n }\n\n console.log(flag ? 'Happy Alex' : 'Poor Alex');\n});"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet t=+readLine()\n\tlet c=0\n\twhile(t--){\n\t\tlet [a,b] = readLine().split(\" \").map(n=>+n)\n\t\tif(b>a)\n\t\t\tc++\n\t}\n\tif(c)\n\t\tconsole.log('Happy Alex')\n\telse console.log('Poor Alex')\n}"}, {"source_code": "var n = +readline(), array = [], check = true;\nfor(i = 0; i < n; i++){\n\tarray.push(readline().split(\" \").map(Number));\n}\n\narray.sort(function(x,y){return x[0] - y[0]});\n\nfor(i = 0; i < n-1; i++){\n\tif(array[i][1] >= array[i+1][1]){\n\t\twrite(\"Happy Alex\");\n\t\tcheck = false;\n\t\tbreak;\n\t}\n}\n\nif(check){write(\"Poor Alex\")}"}, {"source_code": "function solve() {\n\tfor (var i=1; i<=n; i++) {\n\t\tvar s = new Array();\n\t\ts=readline().split(\" \");\n\t\tif (s[0]!=s[1]) {\n\t\t\tprint(\"Happy Alex\");\n\t\t\treturn;\n\t\t}\n\t}\n\tprint(\"Poor Alex\");\n}\nvar n = readline();\nvar a,b;\nsolve();"}, {"source_code": "var goodAnswer = 'Happy Alex',\n\tbadAnswer = 'Poor Alex';\n\n;(function () {\n\n\tprint((function (n) {\n\n\t\tvar map = {},\n\t\t\tprices = [];\n\n\t\tfor (var i = 0; i < n; i++) {\n\t\t\tvar str = readline().split(' '),\n\t\t\t\tprice = parseInt(str[0]),\n\t\t\t\tquality = parseInt(str[1]);\n\n\t\t\tif (map[price]) {\n\t\t\t\tmap[price] = [Math.min(map[price][0], quality), Math.max(map[price][1], quality)];\n\t\t\t} else {\n\t\t\t\tmap[price] = [quality, quality];\n\t\t\t\tprices.push(price);\n\t\t\t}\n\t\t}\n\n\t\tprices = prices.sort(function (a, b) { return a - b; });\n\t\tvar pricesLength = prices.length;\n\n\t\tfor (var i = 1; i < pricesLength; i++)\n\t\t\tif (map[prices[i - 1]][1] > map[prices[i]][0])\n\t\t\t\treturn goodAnswer;\n\n\t\treturn badAnswer;\n\n\t})(+readline()));\n\n}).call(this);"}, {"source_code": "/* jshint strict: false, node: true */\n/* globals process */\nvar collection = [],\n count = null;\n\n\nvar input = \"\", readline;\n\nif (typeof process !== \"undefined\") {\n process.stdin.resume();\n process.stdin.setEncoding(\"utf8\");\n\n process.stdin.on(\"data\", function(chunk) {\n input+=chunk;\n });\n\n process.on(\"SIGINT\", function() {\n var inputLineIndex = 0;\n\n input = input.split(\"\\n\");\n print = function(data) {process.stdout.write(data+'\\n')};\n readline = function(){return inputLineIndex>=input.length?undefined:input[inputLineIndex++]};\n\n process.exit(main() || 0);\n });\n};\n\n\nfunction parseChunks(chunk) {\n if (count === null) {\n count = parseInt(chunk, 10);\n } else {\n collection.push(new Pc(chunk));\n }\n}\n\nfunction Pc (chunk) {\n var params = chunk.split(\" \");\n\n this.price = parseInt(params[0], 10) || 0;\n this.quality = parseInt(params[1], 10) || 0;\n}\n\nfunction main() {\n var line = readline();\n\n while (line) {\n parseChunks(line);\n line = readline();\n }\n\n try {\n collection.sort(function (a, b) {\n if (a.price > b.price) {\n if (a.quality < b.quality) {\n throw \"Found\";\n }\n return 1;\n }\n if (a.price < b.price) {\n if (a.quality > b.quality) {\n throw \"Found\";\n }\n\n return -1;\n }\n\n return 0;\n });\n\n print(\"Poor Alex\");\n } catch (e) {\n print(\"Happy Alex\");\n }\n\n return 0;\n}\n\nmain();"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tlaptops = [];\n\tfor (var i = 0; i < n; ++i) {\n\t\tvar data = tokenizeIntegers(readline());\n\t\tlaptops.push({ price: data[0], quality: data[1] });\n\t}\n\tlaptops.sort(function (a, b) {\n\t\treturn a.price - b.price;\n\t});\n\tfor (var i = 1; i < n; ++i) {\n\t\tif (laptops[i-1].quality > laptops[i].quality) {\n\t\t\tprint('Happy Alex');\n\t\t\treturn;\n\t\t}\n\t}\n\tprint('Poor Alex');\n}\n\nmain();\n"}, {"source_code": "var n = readline();\nvar a =0; var b =0;\n\tfor (var i=0; i<+n; i++){\n\tvar str = readline().split(\" \");\n\t\tif (+str[1]>+str[0]) a = 1;\n\t\telse if (+str[1]<+str[0]) b = 1;\n\t}\na&&b==1? print(\"Happy Alex\"):print(\"Poor Alex\");"}, {"source_code": "var main = function(arr)\n{\n for (var i = 1; i <= arr.length - 1; i++)\n {\n if (+arr[i][0] !== +arr[i][1]) return 'Happy Alex';\n }\n return 'Poor Alex';\n}\n{\n var num = readline(),\n arrContent = [];\n for (var i = 1; i <= +num; i++)\n {\n arrContent.push(readline().split(' '));\n }\n print(main(arrContent));\n}"}, {"source_code": "var n = readline();\nvar a = [];\nvar can = false;\nfor (i = 0 ; i < n ; i ++)\n{\n a.push(readline().split(' ').map(Number));\n}\na.sort(function(x,y){return x[0] < y[0] ? -1 : (((x[0]==y[0])&&(x[1] a[i][1]){can = true ;}\n maxi = Math.max(maxi,a[i][1]);\n}\nwrite(can ? \"Happy Alex\" : \"Poor Alex\");"}, {"source_code": "\n// 456A Ноутбуки \n\nvar n = parseInt(readline());\n\n// var input_line = readline().split(' ').map(Number);\n\nvar arr = [];\nvar out;\n\nfor (var i = 0; i < n; i++) {\n arr[i] = [];\n arr[i] = readline().split(' ').map(Number);\n};\n\narr.sort(function(a,b){return a[0] - b[0];});\n\nvar flag = true;\n\nfor (var i = 0; i < n-1; i++) {\n if (arr[i][1] > arr[i+1][1]) flag = false;\n};\n\nif (flag) {\n out = 'Poor Alex\\n';\n} else {\n out = 'Happy Alex\\n';\n};\n\nprint(out);\n"}, {"source_code": "var n=+readline()\nvar T=new Array(n)\nfor (var i=0;i+x))\n}\nT.sort((l,r)=>l[0]==r[0]?(l[1]-r[1]):l[0]-r[0])\nvar happy=false\nfor (var i=0;iT[i+1][1])\n}\nprint(happy?'Happy Alex':'Poor Alex')\n\n"}], "negative_code": [{"source_code": "/* jshint strict: false, node: true */\n/* globals process */\nvar collection = [],\n count = null;\n\n\nvar input = \"\", readline;\n\nif (typeof process !== \"undefined\") {\n process.stdin.resume();\n process.stdin.setEncoding(\"utf8\");\n\n process.stdin.on(\"data\", function(chunk) {\n input+=chunk;\n });\n\n process.on(\"SIGINT\", function() {\n var inputLineIndex = 0;\n\n input = input.split(\"\\n\");\n print = function(data) {process.stdout.write(data+'\\n')};\n readline = function(){return inputLineIndex>=input.length?undefined:input[inputLineIndex++]};\n\n process.exit(main() || 0);\n });\n};\n\n\nfunction parseChunks(chunk) {\n if (count === null) {\n count = parseInt(chunk, 10);\n } else {\n collection.push(new Pc(chunk));\n }\n}\n\nfunction Pc (chunk) {\n var params = chunk.split(\" \");\n\n this.price = parseInt(params[0], 10) || 0;\n this.quality = parseInt(params[1], 10) || 0;\n}\n\nfunction main() {\n var line = readline();\n\n while (line) {\n parseChunks(line);\n line = readline();\n }\n\n try {\n collection.sort(function (a, b) {\n if (a.price > b.price) {\n if (a.quality < b.quality) {\n throw \"Found\";\n }\n return 1;\n }\n if (a.price < b.price) {\n if (a.quality > b.quality) {\n throw \"Found\";\n }\n\n return -1;\n }\n\n return 0;\n });\n\n print(\"Happy Alex\");\n } catch (e) {\n print(\"Poor Alex\");\n }\n\n return 0;\n}\n\nmain();"}, {"source_code": "function nextRound(k, guys)\n{\n var i = 0, res = 0;\n while (guys[i] >= k)\n {\n res++;\n\t\ti++;\n }\n return res;\n}\n{\n var input1 = readline();\n input1 = input1.split(' ');\n var k = parseInt(input1[1]);\n var input2 = readline();\n print(nextRound(k, input2.split(' ')));\n \n \n \n}"}, {"source_code": "var main = function(arr)\n{\n for (var i = 1; i <= arr.length - 1; i++)\n {\n if (+arr[i][0] !== arr[i][1]) return 'Happy Alex';\n }\n return 'Poor Alex';\n}\n{\n var num = readline(),\n arrContent = [];\n for (var i = 1; i <= +num; i++)\n {\n arrContent.push(readline().split(' '));\n }\n print(main(arrContent));\n}"}], "src_uid": "c21a84c4523f7ef6cfa232cba8b6ee2e"} {"nl": {"description": "After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \\times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \\times l$$$ or $$$l \\times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake \"over the top\" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) — the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \\le n,m \\le 2000$$$) — length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\\cdot10^6$$$.", "output_spec": "Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \\le k \\le 26$$$) — number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$ — coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \\le r_{1,i}, r_{2,i} \\le n$$$, $$$1 \\le c_{1,i}, c_{2,i} \\le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.", "sample_inputs": ["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"], "sample_outputs": ["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"], "notes": null}, "positive_code": [{"source_code": "const DEBUG = false;\nconst { EOL } = require('os');\nconst fs = require('fs');\n\nlet r = process.stdin;\nif (DEBUG) {\n r = fs.createReadStream('input');\n}\nlet data = '';\nfunction calc(n, m, lines) {\n const soln = [];\n const letters = [];\n let last = -1;\n\n const grid = [];\n for (let i = 0; i < 26; i += 1) {\n letters[i] = [];\n }\n for (let i = 0; i < n; i += 1) {\n grid[i] = lines[i].split('');\n }\n for (let i = 0; i < n; i += 1) {\n for (let j = 0; j < m; j += 1) {\n if (grid[i][j] == '.') {\n continue;\n }\n const idx = grid[i][j].charCodeAt() - 'a'.charCodeAt();\n letters[idx].push({ r: i, c: j });\n last = Math.max(last, idx);\n }\n }\n for (let i = last; i >= 0; i -= 1) {\n if (letters[i].length === 0) {\n soln.push(soln[soln.length - 1]);\n continue;\n }\n if (letters[i].length === 1) {\n const { r, c } = letters[i][0];\n grid[r][c] = '*';\n soln.push([r, c, r, c]);\n continue;\n }\n let H = -1;\n if (letters[i][0].r == letters[i][1].r) {\n H = 1;\n }\n if (letters[i][0].c == letters[i][1].c) {\n H = 0;\n }\n if (H == -1) {\n console.log('NO');\n return;\n }\n const curr = { r: letters[i][0].r, c: letters[i][0].c };\n grid[curr.r][curr.c] = '*';\n for (let j = 1; j < letters[i].length; j += 1) {\n if (H == 1) {\n if (letters[i][j].r != curr.r) {\n console.log('NO');\n return;\n }\n while (curr.r != letters[i][j].r || curr.c != letters[i][j].c) {\n curr.c += 1;\n if (\n grid[curr.r][curr.c].charCodeAt() - 'a'.charCodeAt() != i &&\n grid[curr.r][curr.c] != '*'\n ) {\n console.log('NO');\n return;\n }\n grid[curr.r][curr.c] = '*';\n }\n } else {\n if (letters[i][j].c != curr.c) {\n console.log('NO');\n return;\n }\n while (curr.r != letters[i][j].r || curr.c != letters[i][j].c) {\n curr.r += 1;\n if (\n grid[curr.r][curr.c].charCodeAt() - 'a'.charCodeAt() != i &&\n grid[curr.r][curr.c] != '*'\n ) {\n console.log('NO');\n return;\n }\n grid[curr.r][curr.c] = '*';\n }\n }\n }\n soln.push([letters[i][0].r, letters[i][0].c, curr.r, curr.c]);\n }\n console.log('YES');\n console.log(soln.length);\n for (let i = soln.length - 1; i >= 0; i -= 1) {\n console.log(soln[i][0] + 1, soln[i][1] + 1, soln[i][2] + 1, soln[i][3] + 1);\n }\n}\nr.on('data', c => (data += c));\nr.on('end', () => {\n const lines = data.split(EOL);\n const tests = Number(lines[0]);\n let n = 0;\n let m = 0;\n let currIdx = 1;\n for (let i = 1; i <= tests; i += 1) {\n [n, m] = lines[currIdx].split(' ').map(Number);\n calc(n, m, lines.slice(currIdx + 1, currIdx + n + 1));\n currIdx += n + 1;\n }\n});\n"}], "negative_code": [], "src_uid": "f34d21b9568c758cacc1d00af1316c86"} {"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 ≤ |s| ≤ 2·105) 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": "var s = readline().split(\"\");\n\nvar aCharCode = \"a\".charCodeAt(0);\nvar symbolCount = new Array(26).fill(0);\ns.forEach(c => ++symbolCount[c.charCodeAt(0) - aCharCode]);\nvar i = 0;\nvar j = symbolCount.length - 1;\nwhile (true) {\n while (i < j && symbolCount[i]%2 === 0) {\n ++i;\n }\n while (i < j && symbolCount[j]%2 === 0) {\n --j;\n }\n if (i === j) {\n break;\n } else {\n ++symbolCount[i];\n --symbolCount[j];\n }\n}\nvar middle = \"\";\nvar palyndromeHalf = \"\";\nsymbolCount.forEach((count, charCode) => {\n if (count % 2 !== 0) {\n middle = String.fromCharCode(charCode + aCharCode);\n }\n palyndromeHalf += String.fromCharCode(charCode + aCharCode)\n .repeat(Math.floor(count / 2));\n});\nvar palyndrome = palyndromeHalf + middle + palyndromeHalf.split(\"\").reverse().join(\"\");\nwrite(palyndrome + \"\\n\");\n"}, {"source_code": "var s = readline().split(\"\");\n\nvar aCharCode = \"a\".charCodeAt(0);\nvar symbolCount = new Array(26).fill(0);\ns.forEach(c => ++symbolCount[c.charCodeAt(0) - aCharCode]);\nvar i = 0;\nvar j = symbolCount.length - 1;\nwhile (true) {\n while (i < j && symbolCount[i]%2 === 0) {\n ++i;\n }\n while (i < j && symbolCount[j]%2 === 0) {\n --j;\n }\n if (i === j) {\n break;\n } else {\n ++symbolCount[i];\n --symbolCount[j];\n }\n}\n\nvar middle = s.length%2 !== 0 ? String.fromCharCode(i + aCharCode) : \"\";\nvar leftHalf = \"\";\nvar rightHalf = \"\";\nsymbolCount.forEach((count, charCode) => {\n var currentCharSequence = String.fromCharCode(charCode + aCharCode)\n .repeat(Math.floor(count / 2));\n leftHalf += currentCharSequence;\n rightHalf = currentCharSequence + rightHalf;\n});\nwrite(leftHalf + middle + rightHalf + \"\\n\");\n"}], "negative_code": [{"source_code": "var s = readline().split(\"\");\n\nvar aCharCode = \"a\".charCodeAt(0);\nvar symbolCount = new Array(26).fill(0);\ns.forEach(c => ++symbolCount[c.charCodeAt(0) - aCharCode]);\nvar i = 0;\nvar j = symbolCount.length - 1;\nwhile (true) {\n while (i < j && symbolCount[i]%2 === 0) {\n ++i;\n }\n while (i < j && symbolCount[j]%2 === 0) {\n --j;\n }\n if (i === j) {\n break;\n } else {\n ++symbolCount[i];\n --symbolCount[j];\n }\n}\nvar middle = \"\";\nvar palyndromeHalf = \"\";\nsymbolCount.forEach((count, charCode) => {\n if (count % 2 !== 0) {\n middle = String.fromCharCode(charCode + aCharCode)\n .repeat(count);\n } else {\n palyndromeHalf += String.fromCharCode(charCode + aCharCode)\n .repeat(Math.floor(count / 2));\n }\n});\nvar palyndrome = palyndromeHalf + middle + palyndromeHalf.split(\"\").reverse().join(\"\");\nwrite(palyndrome + \"\\n\");\n"}, {"source_code": "var s = readline().split(\"\");\n\nvar aCharCode = \"a\".charCodeAt(0);\nvar symbolCount = new Array(26).fill(0);\ns.forEach(c => ++symbolCount[c.charCodeAt(0) - aCharCode]);\nvar i = 0;\nvar j = symbolCount.length - 1;\nwhile (true) {\n while (i < j && symbolCount[i]%2 === 0) {\n ++i;\n }\n while (i < j && symbolCount[j]%2 === 0) {\n --j;\n }\n if (i === j) {\n break;\n } else {\n ++symbolCount[i];\n --symbolCount[j];\n }\n}\nvar middle = \"\";\nvar palyndromeHalf = \"\";\nsymbolCount.forEach((count, charCode) => {\n if (count % 2 !== 0) {\n middle = String.fromCharCode(charCode + aCharCode);\n } else {\n palyndromeHalf += String.fromCharCode(charCode + aCharCode)\n .repeat(Math.floor(count / 2));\n }\n});\nvar palyndrome = palyndromeHalf + middle + palyndromeHalf.split(\"\").reverse().join(\"\");\nwrite(palyndrome + \"\\n\");\n"}], "src_uid": "f996224809df700265d940b12622016f"} {"nl": {"description": "A Martian boy is named s — 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=«aba», then strings «baobab», «aabbaa», «helloabahello» make him very happy and strings «aab», «baaa» and «helloabhello» 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": "var name = readline(), str = readline(), x = 0, pos, check = true;\nvar namelength = name.length, a;\n\nfor(i=0; i=0; i--) {\n pos = str.lastIndexOf(name[i], pos);\n if (pos != -1) {\n str = str.substr(0, pos);\n } else {\n check = false;\n break;\n }\n }\n if (check) x=str.length+1;\n}\nprint(x);"}, {"source_code": "/*//deb\nvar lines = [];\nlines[0] = \"aba\";\nlines[1] = \"baobababbah\";\nvar line = 0;\nfunction readline() {\n\treturn lines[line++];\n}*/\n\n\nfunction readn() {\n\treturn +readline();\n}\nfunction parsens(s) {\n\treturn \ts.split(\" \").map(function(x) { return +x; });\n}\nfunction sortNumbers(a,b) {\n\treturn a-b;\n}\n\n\nvar s = readline();\nvar t = readline();\n\nfunction trimLeft(s, t) {\n var currentChar = 0;\n for (var i = 0; i < t.length; i++) {\n if (t.charAt(i) == s.charAt(currentChar)) {\n currentChar++;\n }\n if (currentChar == s.length) {\n return t.substr(i+1);//efficency\n }\n }\n return null;\n}\n\nfunction trimRight(s, t) {\n var currentChar = s.length-1;\n for (var i = t.length-1; i >= 0; i--) {\n if (t.charAt(i) == s.charAt(currentChar)) {\n currentChar--;\n }\n if (currentChar == -1) {\n return t.substr(0, i);//efficency\n }\n }\n return null;\n}\n\nvar t2 = trimLeft(s, t);\n//print(\"t2\", t2);\nif (t2 === null) {\n print(0);\n} else {\n var t3 = trimRight(s, t2);\n //print(\"t3\", t3);\n if (t3 === null) {\n print(0);\n } else {\n print(t3.length+1);\n }\n}"}, {"source_code": "var name = readline(), str = readline(), x = 0, pos, check = true;\nvar namelength = name.length, a;\n\nfor(i=0; i=0; i--) {\n pos = str.lastIndexOf(name[i], pos);\n if (pos != -1) {\n str = str.substr(0, pos);\n } else {\n check = false;\n break;\n }\n }\n if (check) x=str.length+1;\n}\nprint(x);"}], "negative_code": [{"source_code": "var name = readline(), str = readline(), x = 0, pos, check = true;\nvar namelength = name.length, a;\n\nwhile(check) {\n for(i=0; i=0; i--) {\n pos = str.lastIndexOf(name[i], pos);\n }\n x += pos+1;\n str = str.substr(a+1);\n}\nprint(x);"}, {"source_code": "var name = readline(), str = readline(), x = 0, pos, check = true;\nvar namelength = name.length, a;\n\nwhile(check) {\n for(i=0; i=0; i--) {\n pos = str.lastIndexOf(name[i], pos);\n if (pos != -1) {\n str = str.substr(0, pos);\n } else {\n check = false;\n break;\n }\n }\n if (!check) break;\n x+=str.length+1;\n}\nprint(x);"}], "src_uid": "724fa4b1d35b8765048857fa8f2f6802"} {"nl": {"description": "You like playing chess tournaments online.In your last tournament you played $$$n$$$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $$$0$$$ points. When you win you get $$$1$$$ or $$$2$$$ points: if you have won also the previous game you get $$$2$$$ points, otherwise you get $$$1$$$ point. If you win the very first game of the tournament you get $$$1$$$ point (since there is not a \"previous game\").The outcomes of the $$$n$$$ games are represented by a string $$$s$$$ of length $$$n$$$: the $$$i$$$-th character of $$$s$$$ is W if you have won the $$$i$$$-th game, while it is L if you have lost the $$$i$$$-th game.After the tournament, you notice a bug on the website that allows you to change the outcome of at most $$$k$$$ of your games (meaning that at most $$$k$$$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.Compute the maximum score you can get by cheating in the optimal way.", "input_spec": "Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\le t \\le 20,000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains two integers $$$n, k$$$ ($$$1\\le n\\le 100,000$$$, $$$0\\le k\\le n$$$) – the number of games played and the number of outcomes that you can change. The second line contains a string $$$s$$$ of length $$$n$$$ containing only the characters W and L. If you have won the $$$i$$$-th game then $$$s_i=\\,$$$W, if you have lost the $$$i$$$-th game then $$$s_i=\\,$$$L. It is guaranteed that the sum of $$$n$$$ over all testcases does not exceed $$$200,000$$$.", "output_spec": "For each testcase, print a single integer – the maximum score you can get by cheating in the optimal way.", "sample_inputs": ["8\n5 2\nWLWLL\n6 5\nLLLWWL\n7 1\nLWLWLWL\n15 5\nWWWLLLWWWLLLWWW\n40 7\nLLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL\n1 0\nL\n1 1\nL\n6 1\nWLLWLW"], "sample_outputs": ["7\n11\n6\n26\n46\n0\n1\n6"], "notes": "NoteExplanation of the first testcase. Before changing any outcome, the score is $$$2$$$. Indeed, you won the first game, so you got $$$1$$$ point, and you won also the third, so you got another $$$1$$$ point (and not $$$2$$$ because you lost the second game).An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $$$7=1+2+2+2$$$: $$$1$$$ point for the first game and $$$2$$$ points for the second, third and fourth game.Explanation of the second testcase. Before changing any outcome, the score is $$$3$$$. Indeed, you won the fourth game, so you got $$$1$$$ point, and you won also the fifth game, so you got $$$2$$$ more points (since you won also the previous game).An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $$$11 = 1+2+2+2+2+2$$$: $$$1$$$ point for the first game and $$$2$$$ points for all the other games."}, "positive_code": [{"source_code": "try {require('codeforces')} catch(e){console = {log:function(){}}};\n// print\n// readline\n\nvar t = parseInt(readline());\nwhile (t--) {\n var data = readline().split(' ').map(Number);\n var s = data[0];\n var n = Math.min(s, data[1]);\n var line = readline();\n var length = line.length;\n var firstW = line.indexOf('W');\n var lastW = line.lastIndexOf('W');\n var index = firstW === -1 ? 0 : firstW;\n\n var zeros = 0;\n var last = 'L'\n var score = 0\n var add = 0;\n var current;\n var map = {}\n\n while (current = line[index]) {\n if (current === 'L') {\n zeros++\n } else {\n score++\n if (last === 'W') score++\n if (zeros) {\n if (!map[zeros]) map[zeros] = 0\n map[zeros]++\n zeros = 0\n }\n }\n last = current\n index++\n }\n\n if (!score) {\n n = Math.min(n, length)\n print(n ? (n * 2 - 1) : 0)\n continue;\n }\n var cells = Object.keys(map).map(Number);\n cells.sort(function(a, b){return a - b})\n var str = line;\n while (cells.length) {\n var size = cells[0];\n var count = map[size];\n if (size > n || count <= 0) {\n cells.shift()\n } else {\n var times = Math.min((n - n % size) / size, count)\n map[size] -= times\n n -= size * times\n add += times * (size * 2 + 1)\n }\n }\n cells = Object.keys(map).filter(key => map[key] > 0)\n if (n > 0) {\n var ddd = Math.min((cells[0] || 0) + firstW + (length - lastW - 1), n)\n n -= ddd\n add += 2 * ddd\n }\n print( score + add)\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [len, k] = readLine().split(\" \").map(Number);\n const str = readLine();\n let [prevChar, streaks, countW, point, countL, numberOfFilledGaps, seenW] = [\"\", 0, 0, 0, 0, 0, false];\n const gaps = [];\n\n for (let i = 0; i < str.length; i++) {\n const currentChar = str[i];\n if (currentChar === \"W\") {\n countW++;\n seenW = true;\n }\n if (prevChar === currentChar) {\n if (currentChar === \"L\" && seenW) {\n countL++;\n }\n continue;\n } else {\n if (currentChar === \"L\" && prevChar === \"W\") countL++;\n if (currentChar === \"W\") {\n streaks++;\n seenW = true;\n }\n if (currentChar === \"W\" && prevChar === \"L\" && streaks > 1) {\n gaps.push(countL);\n countL = 0;\n }\n prevChar = currentChar;\n }\n }\n point = 2 * countW - streaks;\n\n if (k + countW >= len) {\n console.log(2 * len - 1);\n } else if (countW === 0 && k !== 0) {\n console.log(2 * k - 1);\n } else {\n gaps.sort((a, b) => a - b);\n let _k = k;\n for (let i = 0; i < gaps.length; i++) {\n const gap = gaps[i];\n _k -= gap;\n if (_k >= 0) numberOfFilledGaps++;\n else break;\n }\n console.log(2 * (countW + k) - (streaks - numberOfFilledGaps));\n }\n }\n}\n"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n a = a || 0;\n b = b || (this.length - 1);\n let prev = a;\n for (let i = a; i <= b; i++) {\n if (i == b || fn(this[i], this[i + 1])) {\n arr.push(this.slice(prev, i + 1));\n prev = i + 1;\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nfunction inv(b, m) {\n for (var a = m, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + m) % m;\n}\n\n// let MOD = 1e9 + 7\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nasync function main() {\n let inp = input.split(/\\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;\n let t = $()\n while (t--) {\n let n = +$(), k = +$(), s = $(), l = []\n let c = 0, res = 0, c0;\n For(n, i => {\n if (s[i] == 'L') c++;\n else {\n if (i == 0 || s[i - 1] == 'L') res += 1;\n else res += 2;\n if (c > 0) l.push(c);\n c = 0;\n }\n })\n if (c == n) {\n log(max(0, k * 2 - 1));\n continue;\n }\n if (s[0] == 'W') {\n l.sort(asc);\n while (l.length && k >= l[0]) {\n res += l[0] * 2 + 1;\n k -= l[0]\n l.shift()\n }\n if (l.length == 0) {\n log(res + min(k, c) * 2)\n } else {\n log(res + k * 2)\n }\n } else {\n c0 = l[0];\n l = l.slice(1).sort(asc);\n while (l.length && k >= l[0]) {\n res += l[0] * 2 + 1;\n k -= l[0]\n l.shift()\n }\n if (l.length == 0) {\n log(min(2 * n - 1, res + min(k, c + c0) * 2))\n } else {\n log(res + k * 2)\n }\n }\n }\n}\n"}, {"source_code": "'use strict';\n\nvar readline = require('readline');\n\nfunction tTwoLinesPerStdin() {\n return new Promise(resolve => {\n const stdin = readline.createInterface(process.stdin);\n let t;\n let prevLine;\n let output = [];\n stdin.on('line', line => {\n if (typeof t !== 'number') {\n t = +line;\n } else {\n if (prevLine) {\n output.push([prevLine, line]);\n prevLine = undefined;\n\n if (output.length === t) {\n resolve(output);\n stdin.close();\n }\n } else {\n prevLine = line;\n }\n }\n });\n });\n}\n\nfunction solve([n, k], s) {\n let i = 0;\n let score = 0;\n let totalLs = 0;\n const innerLGroups = []; // Ignore leading Ls, they will never result in +3 when swapped\n\n while (s[i] === 'L') {\n i++;\n }\n\n totalLs += i;\n\n while (i < s.length) {\n let w = 0;\n\n while (s[i] === 'W') {\n w++;\n i++;\n }\n\n if (w) {\n score += w * 2 - 1;\n }\n\n let l = 0;\n\n while (s[i] === 'L') {\n l++;\n i++;\n }\n\n totalLs += l; // Ignore trailing Ls, they will never result in +3 when swapped\n\n if (l && s[i] === 'W') {\n innerLGroups.push(l);\n }\n }\n\n if (totalLs <= k) {\n console.log(n * 2 - 1);\n } else if (totalLs === n) {\n console.log(Math.max(k * 2 - 1, 0));\n } else {\n for (let x of innerLGroups.sort((a, b) => a - b)) {\n if (x <= k) {\n score += x * 2 + 1;\n k -= x;\n } else {\n score += k * 2;\n k = 0;\n }\n }\n\n score += k * 2;\n console.log(score);\n }\n}\n\nasync function main() {\n const input = await tTwoLinesPerStdin();\n input.forEach(([a, b]) => solve(a.split(' ').map(Number), b));\n}\n\nmain().then();\n"}, {"source_code": "function B1427(string, insertions) {\n var lgaps = [];\n var wpos = [];\n\n var last = function last(arr) {\n return arr[arr.length - 1];\n };\n\n Array.from(string).forEach(function (x, i) {\n if (x === 'W') {\n if (wpos.length) lgaps.push({\n gap: i - last(wpos) - 1,\n start: last(wpos) + 1\n });\n wpos.push(i);\n }\n });\n var initialScore = 0;\n\n for (var i = 0; i < string.length; i++) {\n if (string[i] === 'L') continue;\n if (i > 0 && string[i - 1] === 'W') initialScore += 2;else initialScore += 1;\n }\n\n var score = 0;\n insertions = Math.min(string.length - wpos.length, insertions);\n lgaps.filter(function (x) {\n return x.gap > 0;\n }).sort(function (a, b) {\n return a.gap - b.gap;\n }).forEach(function (_ref, i) {\n var gap = _ref.gap;\n var val = gap;\n\n if (insertions >= val) {\n score += val * 2 + 1;\n insertions -= val;\n } else {\n score += 2 * insertions;\n insertions = 0;\n }\n });\n\n if (insertions > 0) {\n score += 2 * insertions - (initialScore === 0 ? 1 : 0);\n }\n\n return score + initialScore;\n}\n\nfunction execute(readline, print) {\n var iter = {\n next: function next() {\n return readline();\n }\n };\n\n var split = function split(string) {\n return string.trim().split(' ').map(Number);\n };\n\n var t = Number(iter.next());\n\n while (t--) {\n var params = split(iter.next());\n var arr = iter.next().trim();\n var out = B1427(arr, params[1]);\n print(out);\n }\n}\n\nexecute(readline, print)\n\n\n"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [len, k] = readLine().split(\" \").map(Number);\n const str = readLine();\n let [prevChar, streaks, countW, point, countL, numberOfFilledGaps, seenW] = [\"\", 0, 0, 0, 0, 0, false];\n const gaps = [];\n\n for (let i = 0; i < str.length; i++) {\n const currentChar = str[i];\n if (currentChar === \"W\") {\n countW++;\n seenW = true;\n }\n if (prevChar === currentChar) {\n if (currentChar === \"L\" && seenW) {\n countL++;\n }\n continue;\n } else {\n if (currentChar === \"L\" && prevChar === \"W\") countL++;\n if (currentChar === \"W\") {\n streaks++;\n seenW = true;\n }\n if (currentChar === \"W\" && prevChar === \"L\" && streaks > 1) {\n gaps.push(countL);\n countL = 0;\n }\n prevChar = currentChar;\n }\n }\n point = 2 * countW - streaks;\n\n if (k + countW >= len) {\n console.log(2 * len - 1);\n } else if (countW === 0) {\n console.log(2 * k - 1);\n } else {\n gaps.sort((a, b) => a - b);\n let _k = k;\n for (let i = 0; i < gaps.length; i++) {\n const gap = gaps[i];\n _k -= gap;\n if (_k >= 0) numberOfFilledGaps++;\n else break;\n }\n console.log(2 * (countW + k) - (streaks - numberOfFilledGaps));\n }\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [len, k] = readLine().split(\" \").map(Number);\n const str = readLine();\n let [prevChar, streaks, countW, point, countL, numberOfFilledGaps, seenW] = [\"\", 0, 0, 0, 0, 0, false];\n const gaps = [];\n\n for (let i = 0; i < str.length; i++) {\n const currentChar = str[i];\n if (currentChar === \"W\") {\n countW++;\n seenW = true;\n }\n if (prevChar === currentChar) {\n if (currentChar === \"L\" && seenW) {\n countL++;\n }\n continue;\n } else {\n if (currentChar === \"L\" && prevChar === \"W\") countL++;\n if (currentChar === \"W\") {\n streaks++;\n seenW = true;\n }\n if (currentChar === \"W\" && prevChar === \"L\" && streaks > 1) {\n gaps.push(countL);\n countL = 0;\n }\n prevChar = currentChar;\n }\n }\n point = 2 * countW - streaks;\n\n if (k + countW >= len) {\n console.log(2 * len - 1);\n } else {\n gaps.sort((a, b) => a - b);\n let _k = k;\n for (let i = 0; i < gaps.length; i++) {\n const gap = gaps[i];\n _k -= gap;\n if (_k >= 0) numberOfFilledGaps++;\n else break;\n }\n console.log(2 * (countW + k) - (streaks - numberOfFilledGaps));\n }\n }\n}\n"}, {"source_code": "'use strict';\n\nvar readline = require('readline');\n\nfunction tTwoLinesPerStdin() {\n return new Promise(resolve => {\n const stdin = readline.createInterface(process.stdin);\n let t;\n let prevLine;\n let output = [];\n stdin.on('line', line => {\n if (typeof t !== 'number') {\n t = +line;\n } else {\n if (prevLine) {\n output.push([prevLine, line]);\n prevLine = undefined;\n\n if (output.length === t) {\n resolve(output);\n stdin.close();\n }\n } else {\n prevLine = line;\n }\n }\n });\n });\n}\n\nfunction solve([n, k], s) {\n let i = 0;\n let score = 0;\n let totalLs = 0;\n const innerLGroups = []; // Ignore leading Ls, they will never result in +3 when swapped\n\n while (s[i] === 'L') {\n i++;\n }\n\n totalLs += i;\n\n while (i < s.length) {\n let w = 0;\n\n while (s[i] === 'W') {\n w++;\n i++;\n }\n\n if (w) {\n score += w * 2 - 1;\n }\n\n let l = 0;\n\n while (s[i] === 'L') {\n l++;\n i++;\n }\n\n totalLs += l; // Ignore trailing Ls, they will never result in +3 when swapped\n\n if (l && s[i] === 'W') {\n innerLGroups.push(l);\n }\n }\n\n if (totalLs <= k) {\n console.log(n * 2 - 1);\n } else {\n for (let x of innerLGroups.sort((a, b) => a - b)) {\n if (x <= k) {\n score += x * 2 + 1;\n k -= x;\n } else {\n score += k * 2;\n k = 0;\n }\n }\n\n score += k * 2;\n console.log(score);\n }\n}\n\nasync function main() {\n const input = await tTwoLinesPerStdin();\n input.forEach(([a, b]) => solve(a.split(' ').map(Number), b));\n}\n\nmain().then();\n"}], "src_uid": "c4c3c07b2ba6df49d5a7d6d2d0d1895f"} {"nl": {"description": "Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.", "input_spec": "Each of the eight lines contains three space-separated integers — the numbers written on the piece of paper after Nick's mischief. All numbers do not exceed 106 in their absolute value.", "output_spec": "If there is a way to restore the cube, then print in the first line \"YES\". In each of the next eight lines print three integers — the restored coordinates of the points. The numbers in the i-th output line must be a permutation of the numbers in i-th input line. The numbers should represent the vertices of a cube with non-zero length of a side. If there are multiple possible ways, print any of them. If there is no valid way, print \"NO\" (without the quotes) in the first line. Do not print anything else.", "sample_inputs": ["0 0 0\n0 0 1\n0 0 1\n0 0 1\n0 1 1\n0 1 1\n0 1 1\n1 1 1", "0 0 0\n0 0 0\n0 0 0\n0 0 0\n1 1 1\n1 1 1\n1 1 1\n1 1 1"], "sample_outputs": ["YES\n0 0 0\n0 0 1\n0 1 0\n1 0 0\n0 1 1\n1 0 1\n1 1 0\n1 1 1", "NO"], "notes": null}, "positive_code": [{"source_code": "function gao()\n{\n for( var i=0; i<8 ;i++)\n\t{\n\t var numbers = readline().split(' ');\n\t\tvar aaa = new Array();\n\t\tfor(var j=0;j {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(-1);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n if (d[i] === -1) d[i] = 0;\r\n if (d[j] === -1) d[j] = 0;\r\n e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;\r\n };\r\n for (let [u, v] of edges) {\r\n if (a[u] > t || a[v] > t) continue;\r\n add(u, v);\r\n }\r\n const topo = () => {\r\n let size = 0;\r\n const queue = [],\r\n dist = new Array(n).fill(0);\r\n for (let [u, count] of d.entries()) {\r\n if (count !== -1) size++;\r\n if (count === 0) {\r\n queue.push(u);\r\n dist[u] = 1;\r\n }\r\n }\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n d[v]--;\r\n dist[v] = Math.max(dist[v], dist[u] + 1);\r\n if (dist[v] === k) return true;\r\n if (d[v] === 0) queue.push(v);\r\n }\r\n }\r\n if (queue.length === size) return false;\r\n return true;\r\n };\r\n let res = topo();\r\n return res;\r\n };\r\n const max = Math.max(...a) + 10;\r\n let l = 0,\r\n r = max;\r\n while (l < r) {\r\n const mid = l + r >> 1;\r\n if (check(mid)) {\r\n r = mid;\r\n } else {\r\n l = mid + 1;\r\n }\r\n }\r\n console.log(l === max ? -1 : l);\r\n}\r\n\r\nasync function main(read) {\r\n const [n, m, k] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s) - 1));\r\n }\r\n solve(n, m, k, a, b);\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m, k, a, edges) {\r\n if (k === 1) {\r\n console.log(Math.min(...a));\r\n return;\r\n }\r\n let buildtime = 0,\r\n topotime = 0,\r\n all = new Date().valueOf();\r\n const check = t => {\r\n let time = new Date().valueOf();\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(-1);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n if (d[i] === -1) d[i] = 0;\r\n if (d[j] === -1) d[j] = 0;\r\n e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;\r\n };\r\n for (let [u, v] of edges) {\r\n if (a[u] > t || a[v] > t) continue;\r\n add(u, v);\r\n }\r\n buildtime += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const topo = () => {\r\n let size = 0;\r\n const queue = [],\r\n dist = new Array(n).fill(0);\r\n for (let [u, count] of d.entries()) {\r\n if (count !== -1) size++;\r\n if (count === 0) {\r\n queue.push(u);\r\n dist[u] = 1;\r\n }\r\n }\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n d[v]--;\r\n dist[v] = Math.max(dist[v], dist[u] + 1);\r\n if (dist[v] === k) return true;\r\n if (d[v] === 0) queue.push(v);\r\n }\r\n }\r\n if (queue.length === size) return false;\r\n return true;\r\n };\r\n let res = topo();\r\n topotime += new Date().valueOf() - time;\r\n return res;\r\n };\r\n const max = Math.max(...a) + 10;\r\n let l = 0,\r\n r = max;\r\n let outs = [];\r\n while (l < r) {\r\n const mid = l + r >> 1;\r\n if (n === 173070) outs.push([buildtime, topotime].join(','));\r\n if (new Date().valueOf() - all > 2500) {\r\n if (n === 173070) {\r\n console.log(outs.join('\\n'));\r\n console.log(new Date().valueOf() - all);\r\n }\r\n }\r\n if (check(mid)) {\r\n r = mid;\r\n } else {\r\n l = mid + 1;\r\n }\r\n }\r\n console.log(l === max ? -1 : l);\r\n}\r\n\r\nasync function main(read) {\r\n const [n, m, k] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s) - 1));\r\n }\r\n solve(n, m, k, a, b);\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = 1//+lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n let [n, m, k] = lines[l++].trim().split(' ')\r\n n = +n\r\n m = +m\r\n k = BigInt(k)\r\n // k = +k\r\n const arr = lines[l++].trim().split(' ').map(Number)\r\n const edges = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))\r\n l += m\r\n output[i] = solve(n, m, k, arr, edges)\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(n, m, k, arr, edges) {\r\n if (k === 1n) {\r\n let min = Infinity\r\n for (let i = 0; i < arr.length; i++) {\r\n min = Math.min(min, arr[i])\r\n }\r\n return min\r\n }\r\n arr.unshift(0)\r\n //\r\n const idx = binarySearch(1, 1e9, x => {\r\n return !check(n, k, arr, edges, x)\r\n })\r\n return idx === 1e9 ? -1 : idx + 1\r\n}\r\nfunction check(n, k, arr, edges, x) {\r\n const h = new Array(n + 1).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n + 1).fill(-1);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n if (d[i] === -1) d[i] = 0;\r\n if (d[j] === -1) d[j] = 0;\r\n e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;\r\n };\r\n for (let [u, v] of edges) {\r\n if (arr[u] > x || arr[v] > x) continue;\r\n add(u, v);\r\n }\r\n let size = 0;\r\n const queue = [],\r\n dist = new Array(n + 1).fill(0);\r\n for (let [u, count] of d.entries()) {\r\n if (count !== -1) size++;\r\n if (count === 0) {\r\n queue.push(u);\r\n dist[u] = 1;\r\n }\r\n }\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n d[v]--;\r\n dist[v] = Math.max(dist[v], dist[u] + 1);\r\n if (dist[v] == k) return true;\r\n if (d[v] === 0) queue.push(v);\r\n }\r\n }\r\n return queue.length < size\r\n}\r\nfunction binarySearch(l, r, fn) {\r\n while (l <= r) {\r\n const m = Math.floor((l + r) / 2)\r\n if (fn(m)) {\r\n l = m + 1\r\n } else {\r\n r = m - 1\r\n }\r\n }\r\n return r\r\n}\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m, k, a, edges) {\r\n if (k === 1) {\r\n console.log(Math.min(...a));\r\n return;\r\n }\r\n const check = t => {\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [];\r\n let idx = 0;\r\n const add = (i, j) => {\r\n e[idx] = j, ne[idx] = h[i], h[i] = idx++;\r\n };\r\n for (let [u, v] of edges) {\r\n if (a[u] > t || a[v] > t) continue;\r\n add(u, v);\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map(),\r\n fa = [];\r\n let loop = false;\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n const callStack = [[u]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {\r\n var _curCall;\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (!curCall) continue;\r\n const v = curCall.pop();\r\n if (dfn[v] === low[v]) {\r\n let count = 0;\r\n while (true) {\r\n count++;\r\n if (count > 1) {\r\n loop = true;\r\n return;\r\n }\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n if (j === v) break;\r\n }\r\n idx++;\r\n }\r\n const u = fa[v];\r\n low[u] = Math.min(low[u], low[v]);\r\n }\r\n if (!curCall) break;\r\n const u = curCall[curCall.length - 1];\r\n if (!dfn[u]) {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n let nextCall = [];\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n if (!dfn[v]) {\r\n fa[v] = u;\r\n nextCall.push(v);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n callStack.push(nextCall);\r\n continue;\r\n } else if (set.has(u)) {\r\n const f = fa[u];\r\n low[f] = Math.min(low[f], dfn[u]);\r\n }\r\n curCall.pop();\r\n }\r\n };\r\n for (let i = 0; i < n; i++) {\r\n if (!dfn[i]) dfs(i);\r\n if (loop) return true;\r\n }\r\n if (k > idx) return false;\r\n const h1 = new Array(n).fill(-1),\r\n e1 = [],\r\n ne1 = [],\r\n d = new Array(idx).fill(0);\r\n let idx1 = 0;\r\n const add = (i, j) => {\r\n e1[idx1] = j, ne1[idx1] = h1[i], h1[i] = idx1++;\r\n };\r\n for (let u = 0; u < n; u++) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n const a = map.get(u),\r\n b = map.get(v);\r\n add(a, b);\r\n }\r\n }\r\n const queue = [],\r\n dist = new Array(idx).fill(0);\r\n for (let [k, v] of d.entries()) if (v === 0) {\r\n queue.push(k);\r\n dist[k] = 1;\r\n }\r\n for (let u of queue) {\r\n for (let i = h1[u]; i !== -1; i = ne1[i]) {\r\n const v = e1[i];\r\n d[v]--;\r\n dist[v] = Math.max(dist[v], dist[u] + 1);\r\n if (dist[v] === k) {\r\n return true;\r\n }\r\n if (d[v] === 0) queue.push(v);\r\n }\r\n }\r\n return false;\r\n };\r\n return tarjan();\r\n };\r\n const max = Math.max(...a) + 10;\r\n let l = 0,\r\n r = max;\r\n while (l < r) {\r\n const mid = l + r >> 1;\r\n if (check(mid)) {\r\n r = mid;\r\n } else {\r\n l = mid + 1;\r\n }\r\n }\r\n console.log(l === max ? -1 : l);\r\n}\r\n\r\nasync function main(read) {\r\n const [n, m, k] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s) - 1));\r\n }\r\n solve(n, m, k, a, b);\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m, k, a, edges) {\r\n if (k === 1) {\r\n console.log(Math.min(...a));\r\n return;\r\n }\r\n let buildtime = 0,\r\n topotime = 0,\r\n all = new Date().valueOf();\r\n const check = t => {\r\n let time = new Date().valueOf();\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(-1);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n if (d[i] === -1) d[i] = 0;\r\n if (d[j] === -1) d[j] = 0;\r\n e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;\r\n };\r\n for (let [u, v] of edges) {\r\n if (a[u] > t || a[v] > t) continue;\r\n add(u, v);\r\n }\r\n buildtime += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const topo = () => {\r\n let size = 0;\r\n const queue = [],\r\n dist = new Array(n).fill(0);\r\n for (let [u, count] of d.entries()) {\r\n if (count !== -1) size++;\r\n if (count === 0) {\r\n queue.push(u);\r\n dist[u] = 1;\r\n }\r\n }\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n d[v]--;\r\n dist[v] = Math.max(dist[v], dist[u] + 1);\r\n if (dist[v] === k) return true;\r\n if (d[v] === 0) queue.push(v);\r\n }\r\n }\r\n if (queue.length === size) return false;\r\n return true;\r\n };\r\n let res = topo();\r\n topotime += new Date().valueOf() - time;\r\n return res;\r\n };\r\n const max = Math.max(...a) + 10;\r\n let l = 0,\r\n r = max;\r\n let outs = [];\r\n while (l < r) {\r\n const mid = l + r >> 1;\r\n if (n === 173070) outs.push([buildtime, topotime].join(','));\r\n if (check(mid)) {\r\n r = mid;\r\n } else {\r\n l = mid + 1;\r\n }\r\n }\r\n if (n === 173070) {\r\n console.log(outs.join('|'));\r\n console.log(new Date().valueOf() - all);\r\n }\r\n console.log(l === max ? -1 : l);\r\n}\r\n\r\nasync function main(read) {\r\n const [n, m, k] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s) - 1));\r\n }\r\n solve(n, m, k, a, b);\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m, k, a, edges) {\r\n if (k === 1) {\r\n console.log(Math.min(...a));\r\n return;\r\n }\r\n let buildtime = 0,\r\n topotime = 0,\r\n all = new Date().valueOf();\r\n const check = t => {\r\n let time = new Date().valueOf();\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(-1);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n if (d[i] === -1) d[i] = 0;\r\n if (d[j] === -1) d[j] = 0;\r\n e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;\r\n };\r\n for (let [u, v] of edges) {\r\n if (a[u] > t || a[v] > t) continue;\r\n add(u, v);\r\n }\r\n buildtime += new Date().valueOf() - time;\r\n time = new Date().valueOf();\r\n const topo = () => {\r\n let size = 0;\r\n const queue = [],\r\n dist = new Array(n).fill(0);\r\n for (let [u, count] of d.entries()) {\r\n if (count !== -1) size++;\r\n if (count === 0) {\r\n queue.push(u);\r\n dist[u] = 1;\r\n }\r\n }\r\n for (let u of queue) {\r\n for (let i = h[u]; i !== -1; i = ne[i]) {\r\n const v = e[i];\r\n d[v]--;\r\n dist[v] = Math.max(dist[v], dist[u] + 1);\r\n if (dist[v] === k) return true;\r\n if (d[v] === 0) queue.push(v);\r\n }\r\n }\r\n if (queue.length === size) return false;\r\n return true;\r\n };\r\n let res = topo();\r\n topotime += new Date().valueOf() - time;\r\n return res;\r\n };\r\n const max = Math.max(...a) + 10;\r\n let l = 0,\r\n r = max;\r\n let outs = [];\r\n while (l < r) {\r\n const mid = l + r >> 1;\r\n if (n === 173070) outs.push([buildtime, topotime].join(','));\r\n if (check(mid)) {\r\n r = mid;\r\n } else {\r\n l = mid + 1;\r\n }\r\n }\r\n if (n === 173070) {\r\n console.log(outs.join('\\n'));\r\n console.log(new Date().valueOf() - all);\r\n }\r\n console.log(l === max ? -1 : l);\r\n}\r\n\r\nasync function main(read) {\r\n const [n, m, k] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(s => Number(s) - 1));\r\n }\r\n solve(n, m, k, a, b);\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, m, k, a, edges) {\r\n if (k === 1) {\r\n console.log(Math.min(...a));\r\n return;\r\n }\r\n const check = t => {\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n for (let [u, v] of edges) {\r\n u--, v--;\r\n if (a[u] > t || a[v] > t) continue;\r\n g[u].push(v);\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map(),\r\n loops = [],\r\n fa = [];\r\n let time = 1,\r\n idx = 0;\r\n const dfs = u => {\r\n const callStack = [[u]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {\r\n var _curCall;\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (!curCall) continue;\r\n const v = curCall.pop();\r\n if (dfn[v] === low[v]) {\r\n loops.push([]);\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, idx);\r\n loops[idx].push(j);\r\n if (j === v) break;\r\n }\r\n idx++;\r\n }\r\n const u = fa[v];\r\n low[u] = Math.min(low[u], low[v]);\r\n }\r\n if (!curCall) break;\r\n const u = curCall[curCall.length - 1];\r\n if (!dfn[u]) {\r\n dfn[u] = low[u] = time++;\r\n stack.push(u);\r\n set.add(u);\r\n let nextCall = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n fa[v] = u;\r\n nextCall.push(v);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n callStack.push(nextCall);\r\n continue;\r\n } else if (set.has(u)) {\r\n const f = fa[u];\r\n low[f] = Math.min(low[f], dfn[u]);\r\n }\r\n curCall.pop();\r\n }\r\n };\r\n for (let i = 0; i < n; i++) {\r\n if (!dfn[i]) dfs(i);\r\n }\r\n for (let nums of loops) {\r\n if (nums.length > 1) return true;\r\n }\r\n const g1 = Array.from({\r\n length: idx\r\n }, () => new Set()),\r\n d = new Array(idx).fill(0);\r\n for (let [u, children] of g.entries()) {\r\n for (let v of children) {\r\n if (g1[u].has(v)) continue;\r\n g1[u].add(v);\r\n d[v]++;\r\n }\r\n }\r\n const queue = [],\r\n dist = new Array(idx).fill(0);\r\n for (let [k, v] of d.entries()) if (v === 0) {\r\n queue.push(k);\r\n dist[k] = 1;\r\n }\r\n for (let u of queue) {\r\n for (let v of g1[u]) {\r\n d[v]--;\r\n dist[v] = Math.max(dist[v], dist[u] + 1);\r\n if (dist[v] === k - 1) return true;\r\n if (d[v] === 0) queue.push(v);\r\n }\r\n }\r\n return false;\r\n };\r\n return tarjan();\r\n };\r\n const max = Math.max(...a) + 10;\r\n let l = 0,\r\n r = max;\r\n while (l < r) {\r\n const mid = l + r >> 1;\r\n if (check(mid)) {\r\n r = mid;\r\n } else {\r\n l = mid + 1;\r\n }\r\n }\r\n console.log(l === max ? -1 : l);\r\n}\r\n\r\nasync function main(read) {\r\n const [n, m, k] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n solve(n, m, k, a, b);\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction _defineProperty(obj, key, value) {\r\n if (key in obj) {\r\n Object.defineProperty(obj, key, {\r\n value: value,\r\n enumerable: true,\r\n configurable: true,\r\n writable: true\r\n });\r\n } else {\r\n obj[key] = value;\r\n }\r\n\r\n return obj;\r\n}\r\n\r\nfunction solve(n, m, k, a, edges) {\r\n const g = Array.from({\r\n length: n\r\n }, () => []);\r\n for (let [u, v] of edges) {\r\n u--, v--;\r\n g[u].push(v);\r\n }\r\n const tarjan = () => {\r\n const dfn = [],\r\n low = [],\r\n stack = [],\r\n set = new Set(),\r\n map = new Map(),\r\n loops = [],\r\n fa = [];\r\n let idx = 1;\r\n const dfs = u => {\r\n const callStack = [[u]];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {\r\n var _curCall;\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (!curCall) continue;\r\n const v = curCall.pop();\r\n if (dfn[v] === low[v]) {\r\n loops.push([]);\r\n let k = loops.length - 1;\r\n while (true) {\r\n const j = stack.pop();\r\n set.delete(j);\r\n map.set(j, k);\r\n loops[k].push(j);\r\n if (j === v) break;\r\n }\r\n }\r\n const u = fa[v];\r\n low[u] = Math.min(low[u], low[v]);\r\n }\r\n if (!curCall) break;\r\n const u = curCall[curCall.length - 1];\r\n if (!dfn[u]) {\r\n dfn[u] = low[u] = idx++;\r\n stack.push(u);\r\n set.add(u);\r\n let nextCall = [];\r\n for (let v of g[u]) {\r\n if (!dfn[v]) {\r\n fa[v] = u;\r\n nextCall.push(v);\r\n } else if (set.has(v)) {\r\n low[u] = Math.min(low[u], dfn[v]);\r\n }\r\n }\r\n callStack.push(nextCall);\r\n continue;\r\n } else if (set.has(u)) {\r\n const f = fa[u];\r\n low[f] = Math.min(low[f], dfn[u]);\r\n }\r\n curCall.pop();\r\n }\r\n };\r\n for (let i = 0; i < n; i++) {\r\n if (!dfn[i]) dfs(i);\r\n }\r\n let res = Infinity;\r\n for (let nums of loops) {\r\n if (nums.length > 1) {\r\n let max = -Infinity;\r\n for (let i of nums) {\r\n max = Math.max(max, a[i]);\r\n }\r\n res = Math.min(max);\r\n }\r\n }\r\n return res;\r\n };\r\n let res = tarjan();\r\n if (k > n) {\r\n console.log(res === Infinity ? -1 : res);\r\n return;\r\n }\r\n const dfs = (i, set = new Set(), path = [], bst = new BinarySearchTree()) => {\r\n bst.insert(a[i]);\r\n path.push(i);\r\n set.add(i);\r\n if (path.length > k) {\r\n const b = path[path.length - k - 1];\r\n bst.delete(b);\r\n }\r\n if (path.length >= k) {\r\n res = Math.min(res, bst.getMax());\r\n }\r\n for (let j of g[i]) {\r\n if (set.has(j)) continue;\r\n dfs(j, set, path, bst);\r\n }\r\n bst.delete(a[i]);\r\n if (path.length > k) {\r\n const b = path[path.length - k - 1];\r\n bst.insert(b);\r\n }\r\n set.delete(i);\r\n path.pop();\r\n };\r\n dfs(0);\r\n console.log(res === Infinity ? -1 : res);\r\n}\r\nclass BinarySearchTree {\r\n constructor(_compare = (a, b) => a - b) {\r\n _defineProperty(this, \"root\", null);\r\n _defineProperty(this, \"length\", 0);\r\n _defineProperty(this, \"min\", null);\r\n _defineProperty(this, \"max\", null);\r\n _defineProperty(this, \"minCache\", true);\r\n _defineProperty(this, \"maxCache\", true);\r\n this._compare = _compare;\r\n this.compare = this.compare.bind(this);\r\n }\r\n isT(t) {\r\n return t !== undefined && t !== null;\r\n }\r\n compare(a, b) {\r\n const {\r\n isT\r\n } = this;\r\n if (isT(a) && isT(b)) return this._compare(a, b);\r\n if (isT(a)) return 1;\r\n if (isT(b)) return -1;\r\n return 0;\r\n }\r\n isEmpty() {\r\n return !this.root;\r\n }\r\n size() {\r\n return this.root ? this.root.size : 0;\r\n }\r\n getRoot() {\r\n return this.root;\r\n }\r\n getMin() {\r\n if (this.minCache) {\r\n return this.min;\r\n }\r\n const min = this.searchKth(this.size());\r\n this.min = min;\r\n this.minCache = true;\r\n return min;\r\n }\r\n getMax() {\r\n if (this.maxCache) {\r\n return this.max;\r\n }\r\n const max = this.searchKth(1);\r\n this.max = max;\r\n this.maxCache = true;\r\n return max;\r\n }\r\n balance(node) {\r\n node.height = this.getHeight(node);\r\n const blance = this.getBalance(node);\r\n let res;\r\n if (Math.abs(blance) === 2) {\r\n if (blance > 0) {\r\n var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;\r\n const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRight(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeftRight(node);\r\n }\r\n } else {\r\n var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;\r\n const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRightLeft(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeft(node);\r\n }\r\n }\r\n }\r\n return res ? res : node;\r\n }\r\n rotateRight(node) {\r\n const left = node.left;\r\n const leftRight = left.right;\r\n left.right = node;\r\n node.left = leftRight;\r\n node.height = this.getHeight(node);\r\n left.height = this.getHeight(left);\r\n node.size = this.getSize(node);\r\n left.size = this.getSize(left);\r\n return left;\r\n }\r\n rotateLeft(node) {\r\n const right = node.right;\r\n const rightLeft = right.left;\r\n right.left = node;\r\n node.right = rightLeft;\r\n node.height = this.getHeight(node);\r\n right.height = this.getHeight(right);\r\n node.size = this.getSize(node);\r\n right.size = this.getSize(right);\r\n return right;\r\n }\r\n rotateLeftRight(node) {\r\n node.left = this.rotateLeft(node.left);\r\n return this.rotateRight(node);\r\n }\r\n rotateRightLeft(node) {\r\n node.right = this.rotateRight(node.right);\r\n return this.rotateLeft(node);\r\n }\r\n getBalance(node) {\r\n return this.getHeight(node.left) - this.getHeight(node.right);\r\n }\r\n getHeight(node) {\r\n var _node$left$height, _node$left3, _node$right$height, _node$right3;\r\n if (!node) return 0;\r\n return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;\r\n }\r\n getSize(node) {\r\n var _node$left$size, _node$left4, _node$right$size, _node$right4;\r\n if (!node) return 0;\r\n return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;\r\n }\r\n createNode(val) {\r\n return {\r\n id: Math.random() * new Date().valueOf(),\r\n val,\r\n left: null,\r\n right: null,\r\n size: 1,\r\n height: 1,\r\n count: 1\r\n };\r\n }\r\n insert(val) {\r\n let cur = this.createNode(val);\r\n if (this.isEmpty()) {\r\n this.root = cur;\r\n this.length++;\r\n } else {\r\n [, cur] = this.insertNode(this.root, cur);\r\n }\r\n if (this.min === null || this.compare(this.min, val) > 0) {\r\n this.min = val;\r\n }\r\n if (this.max === null || this.compare(this.max, val) < 0) {\r\n this.max = val;\r\n }\r\n }\r\n insertNode(node, cur, parent = null) {\r\n node.size++;\r\n const compareResult = this.compare(cur.val, node.val);\r\n let res;\r\n if (compareResult === 0) {\r\n node.count++;\r\n return [false, node];\r\n } else if (compareResult > 0) {\r\n if (node.right) {\r\n res = this.insertNode(node.right, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.right = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n } else {\r\n if (node.left) {\r\n res = this.insertNode(node.left, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.left = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n }\r\n let preHeight = node.height;\r\n const newNode = this.balance(node);\r\n if (newNode === node && node.height === preHeight) {\r\n res = [false, res[1]];\r\n } else if (newNode !== node) {\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n res = [false, res[1]];\r\n }\r\n return res;\r\n }\r\n delete(val) {\r\n if (!this.root) return;\r\n this.deleteNode(val, this.root, null);\r\n }\r\n deleteNode(val, node, parent) {\r\n if (!node) return null;\r\n let res = this.compare(val, node.val);\r\n if (res === 0) {\r\n node.count--;\r\n node.size--;\r\n if (node.count > 0) return node;\r\n if (!node.left || !node.right) {\r\n if (this.min === val) {\r\n this.minCache = false;\r\n }\r\n if (this.max === val) {\r\n this.maxCache = false;\r\n }\r\n this.length--;\r\n if (!parent) {\r\n var _node$left5;\r\n this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;\r\n return this.root;\r\n } else {\r\n var _node$left6;\r\n return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;\r\n }\r\n } else {\r\n const selectLeft = node.left.height > node.right.height;\r\n let replaceNode = selectLeft ? this.pre(node) : this.next(node),\r\n name = selectLeft ? 'left' : 'right';\r\n node.val = replaceNode.val;\r\n node.count = replaceNode.count;\r\n replaceNode.count = 0;\r\n node[name] = this.deleteNode(replaceNode.val, node[name], node);\r\n }\r\n } else if (res > 0) {\r\n node.right = this.deleteNode(val, node.right, node);\r\n } else {\r\n node.left = this.deleteNode(val, node.left, node);\r\n }\r\n node.size = this.getSize(node);\r\n node.height;\r\n const newNode = this.balance(node);\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n return newNode;\r\n }\r\n next(node) {\r\n let next = node.right;\r\n while ((_next = next) !== null && _next !== void 0 && _next.left) {\r\n var _next;\r\n next = next.left;\r\n }\r\n return next;\r\n }\r\n pre(node) {\r\n let pre = node.left;\r\n while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {\r\n var _pre;\r\n pre = pre.right;\r\n }\r\n return pre;\r\n }\r\n search(val, compare) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);\r\n return node.val;\r\n }\r\n searchCeilingNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.searchCeilingNode(node.right, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n const [p, value] = this.searchCeilingNode(node.left, val, compare, node);\r\n if (compare(value.val, val) < 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n ceiling(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) >= 0 ? node.val : null;\r\n }\r\n searchFloorNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n const [p, value] = this.searchFloorNode(node.right, val, compare, node);\r\n if (compare(value.val, val) > 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n return this.searchFloorNode(node.left, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n floor(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchFloorNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) <= 0 ? node.val : null;\r\n }\r\n searchKth(k) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n if (k <= 0 || k > this.size()) {\r\n return null;\r\n }\r\n const node = this.searchNodeKth(this.root, k);\r\n return node.val;\r\n }\r\n searchNodeKth(node, k) {\r\n var _node$right$size2, _node$right5, _node$right$size3, _node$right6;\r\n const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;\r\n if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;\r\n if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);\r\n }\r\n countGreaterThanEq(val) {\r\n if (!this.root) return 0;\r\n return this.countCompare(val, (a, b) => this._compare(a, b), this.root);\r\n }\r\n countCompare(val, compare, node, pre = 0) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n var _node$right$size4, _node$right7;\r\n return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.countCompare(val, compare, node.right, pre);\r\n } else {\r\n return pre;\r\n }\r\n } else {\r\n var _node$right$size5, _node$right8;\r\n let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;\r\n if (node.left) {\r\n return this.countCompare(val, compare, node.left, count);\r\n } else {\r\n return count;\r\n }\r\n }\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n const [n, m, k] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = m;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n solve(n, m, k, a, b);\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n let [n, m, k] = lines[l++].trim().split(' ')\n n = +n\n m = +m\n // k = BigInt(k)\n k = +k\n const arr = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))\n l += m\n output[i] = solve(n, m, k, arr, edges)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nclass Queue {\n constructor() {\n this.map = {}\n this.first = 0\n this.last = -1\n }\n push(...args) {\n let i = 0\n if (!this.length) {\n this.first = this.last = 0\n this.map[this.first] = args[i++]\n }\n for (; i < args.length; i++) {\n this.map[++this.last] = args[i]\n }\n }\n unshift(...args) {\n let i = 0\n if (!this.length) {\n this.first = this.last = 0\n this.map[this.first] = args[i++]\n }\n for (; i < args.length; i++) {\n this.map[--this.first] = args[i]\n }\n }\n pop() {\n const r = this.map[this.last]\n delete this.map[this.last]\n this.last--\n return r\n }\n shift() {\n const r = this.map[this.first]\n delete this.map[this.first]\n this.first++\n return r\n }\n get length() {\n if (this.first > this.last) return 0\n return this.last - this.first + 1\n }\n forEach(fn) {\n for (let i = this.first; i <= this.last; i++) {\n fn(this.map[i], i - this.first)\n }\n }\n}\n\nfunction solve(n, m, k, arr, edges) {\n arr.unshift(0)\n //\n const idx = binarySearch(1, 1e9, x => {\n // let x = 10\n return !check2(n, k, arr, edges, x)\n })\n return idx === 1e9 ? -1 : idx + 1\n}\nfunction check2(n, k, arr, edges, x) {\n const h = new Array(n).fill(-1),\n e = [],\n ne = [],\n d = new Array(n).fill(-1);\n let idx = 0;\n const add = (i, j) => {\n if (d[i] === -1) d[i] = 0;\n if (d[j] === -1) d[j] = 0;\n e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;\n };\n for (let [u, v] of edges) {\n if (arr[u] > x || arr[v] > x) continue;\n add(u, v);\n }\n // const ins = Array(n + 1).fill(0)\n // const outs = Array(n + 1).fill(0)\n // const adj = {}\n // // const radj = {}\n // edges.forEach(([a, b]) => {\n // if (arr[a] > x || arr[b] > x) return\n // adj[a] = adj[a] || []\n // adj[a].push(b)\n // // radj[b] = radj[b] || []\n // // radj[b].push(a)\n // ins[b]++\n // })\n let size = 0;\n let queue = new Queue(),//[],\n dist = new Array(n).fill(0);\n for (let [u, count] of d.entries()) {\n if (count !== -1) size++;\n if (count === 0) {\n queue.push(u);\n dist[u] = 1;\n }\n }\n // for (let u of queue) {\n // for (let i = h[u]; i !== -1; i = ne[i]) {\n // const v = e[i];\n // d[v]--;\n // dist[v] = Math.max(dist[v], dist[u] + 1);\n // if (dist[v] === k) return true;\n // if (d[v] === 0) queue.push(v);\n // }\n // }\n let level = 1n\n let count = 0\n while (queue.length) {\n // if (level >= k) return true\n const nq = new Queue()\n // while (queue.length) {\n queue.forEach(u => {\n // const u = queue.shift()\n count++\n for (let i = h[u]; i !== -1; i = ne[i]) {\n const v = e[i];\n d[v]--;\n if (level + 1n >= k) return true\n if (d[v] === 0) nq.push(v);\n }\n // }\n })\n queue = nq\n level++\n }\n return count < size\n\n // let q = new Queue()\n // let total = 0\n // for (let u = 1; u <= n; u++) {\n // outs[u] = adj[u] ? adj[u].length : 0\n // // ins[u] = (radj[u] || []).length\n // if (ins[u] || outs[u]) {\n // total++\n // if (!ins[u]) q.push(u)\n // }\n // }\n // if (!total) return false\n // let count = 0\n // const dist = Array(n + 1).fill(1)\n // while (q.length) {\n // if (level >= k) return true\n // const nq = new Queue()\n // q.forEach(u => {\n // count++\n // ;(adj[u] || []).forEach(v => {\n // if (!--ins[v]) nq.push(v)\n // })\n // })\n // q = nq\n // level++\n // }\n // console.log(x, level, count)\n // return count < total\n}\nfunction check(n, k, a, edges, t) {\n const h = new Array(n).fill(-1),\n e = [],\n ne = [],\n d = new Array(n).fill(-1);\n let idx = 0;\n const add = (i, j) => {\n if (d[i] === -1) d[i] = 0;\n if (d[j] === -1) d[j] = 0;\n e[idx] = j, ne[idx] = h[i], d[j]++, h[i] = idx++;\n };\n for (let [u, v] of edges) {\n if (a[u] > t || a[v] > t) continue;\n add(u, v);\n }\n const topo = () => {\n let size = 0;\n const queue = [],\n dist = new Array(n).fill(0);\n for (let [u, count] of d.entries()) {\n if (count !== -1) size++;\n if (count === 0) {\n queue.push(u);\n dist[u] = 1;\n }\n }\n return 1\n for (let u of queue) {\n for (let i = h[u]; i !== -1; i = ne[i]) {\n const v = e[i];\n d[v]--;\n dist[v] = Math.max(dist[v], dist[u] + 1);\n if (dist[v] === k) return true;\n if (d[v] === 0) queue.push(v);\n }\n }\n if (queue.length === size) return false;\n return true;\n };\n let res = topo();\n return res;\n };\nfunction binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n let [n, m, k] = lines[l++].trim().split(' ')\n n = +n\n m = +m\n k = BigInt(k)\n const arr = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))\n l += m\n output[i] = solve(n, m, k, arr, edges)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nclass Queue {\n constructor() {\n this.map = {}\n this.first = 0\n this.last = -1\n }\n push(...args) {\n let i = 0\n if (!this.length) {\n this.first = this.last = 0\n this.map[this.first] = args[i++]\n }\n for (; i < args.length; i++) {\n this.map[++this.last] = args[i]\n }\n }\n unshift(...args) {\n let i = 0\n if (!this.length) {\n this.first = this.last = 0\n this.map[this.first] = args[i++]\n }\n for (; i < args.length; i++) {\n this.map[--this.first] = args[i]\n }\n }\n pop() {\n const r = this.map[this.last]\n delete this.map[this.last]\n this.last--\n return r\n }\n shift() {\n const r = this.map[this.first]\n delete this.map[this.first]\n this.first++\n return r\n }\n get length() {\n if (this.first > this.last) return 0\n return this.last - this.first + 1\n }\n}\n\nfunction solve(n, m, k, arr, edges) {\n arr.unshift(0)\n //\n const idx = binarySearch(1, 1e9, x => {\n // let x = 10\n return !check(n, k, arr, edges, x)\n })\n return idx === 1e9 ? -1 : idx + 1\n}\nfunction check(n, k, arr, edges, x) {\n const ins = Array(n + 1).fill(0)\n const outs = Array(n + 1).fill(0)\n const adj = {}\n const radj = {}\n edges.forEach(([a, b]) => {\n if (arr[a] > x || arr[b] > x) return\n adj[a] = adj[a] || []\n adj[a].push(b)\n radj[b] = radj[b] || []\n radj[b].push(a)\n })\n let q = new Queue()\n let total = 0\n for (let u = 1; u <= n; u++) {\n outs[u] = (adj[u] || []).length\n ins[u] = (radj[u] || []).length\n if (arr[u] <= x) {\n total++\n if (!ins[u]) q.push(u)\n }\n }\n let level = 1n\n let count = 0\n while (q.length) {\n const nq = new Queue()\n while (q.length) {\n const u = q.shift()\n count++\n ;(adj[u] || []).forEach(v => {\n if (!--ins[v]) nq.push(v)\n })\n }\n if (level >= k) return count\n q = nq\n level++\n }\n // console.log(level, count)\n return count && count < total\n}\nfunction binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}\n"}], "src_uid": "1b36b12307b1a324b84e878d11efbbec"} {"nl": {"description": "Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $$$n$$$ stairs, then it is made of $$$n$$$ columns, the first column is $$$1$$$ cell high, the second column is $$$2$$$ cells high, $$$\\ldots$$$, the $$$n$$$-th column if $$$n$$$ cells high. The lowest cells of all stairs must be in the same row.A staircase with $$$n$$$ stairs is called nice, if it may be covered by $$$n$$$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $$$7$$$ stairs looks like: Find out the maximal number of different nice staircases, that can be built, using no more than $$$x$$$ cells, in total. No cell can be used more than once.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 1000)$$$  — the number of test cases. The description of each test case contains a single integer $$$x$$$ $$$(1 \\le x \\le 10^{18})$$$  — the number of cells for building staircases.", "output_spec": "For each test case output a single integer  — the number of different nice staircases, that can be built, using not more than $$$x$$$ cells, in total.", "sample_inputs": ["4\n1\n8\n6\n1000000000000000000"], "sample_outputs": ["1\n2\n1\n30"], "notes": "NoteIn the first test case, it is possible to build only one staircase, that consists of $$$1$$$ stair. It's nice. That's why the answer is $$$1$$$.In the second test case, it is possible to build two different nice staircases: one consists of $$$1$$$ stair, and another consists of $$$3$$$ stairs. This will cost $$$7$$$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $$$2$$$.In the third test case, it is possible to build only one of two nice staircases: with $$$1$$$ stair or with $$$3$$$ stairs. In the first case, there will be $$$5$$$ cells left, that may be used only to build a staircase with $$$2$$$ stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is $$$1$$$. If Jett builds a staircase with $$$3$$$ stairs, then there are no more cells left, so the answer is $$$1$$$ again."}, "positive_code": [{"source_code": "\"use strict\";\nvar input = '';\nvar inputResolve;\nvar inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => {\n inputResolve();\n});\n(async () => {\n // var time = Date.now();\n await inputPromise;\n var inputs = input.split(/\\r?\\n/);\n var arr = [BigInt(1)];\n var x = BigInt(1);\n while (true) {\n x = x * BigInt(2) + BigInt(1);\n arr.push(arr[arr.length - 1] + BigInt(x) * BigInt(x + BigInt(1)) / BigInt(2));\n if (x > 1e10)\n break;\n }\n // console.log(arr);\n var t = +inputs[0];\n for (let i = 0; i < t; i++) {\n console.log(arr.filter(v => v <= BigInt(inputs[i + 1])).length);\n }\n})();\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this); }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this); }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this); }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0); };\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n};\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {});\n};\n"}], "negative_code": [], "src_uid": "f0806ab99cf4da228abe3cd8073884d9"} {"nl": {"description": "It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.", "input_spec": "The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.", "output_spec": "Print a single line with the winner's name. If Alice wins print \"Alice\", otherwise print \"Bob\" (without quotes).", "sample_inputs": ["2\n2 3", "2\n5 3", "3\n5 6 7"], "sample_outputs": ["Alice", "Alice", "Bob"], "notes": "NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice."}, "positive_code": [{"source_code": "function gcd(a,b)\n{\n if (b==0)return a\n if (a==0)return b\n return gcd(b,a%b)\n}\n\nfunction cmp(a,b){return b-a;}\n\nn=+readline()\ng=0\ns=readline().split(' ')\ns.map(function(x){g=gcd(+x,g);return g;})\ns.sort(cmp)\nprint((s[0]/g-s.length)%2?\"Alice\":\"Bob\")"}], "negative_code": [], "src_uid": "3185ae6b4b681a10a21d02e67f08fd19"} {"nl": {"description": "One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold: x occurs in sequence a. Consider all positions of numbers x in the sequence a (such i, that ai = x). These numbers, sorted in the increasing order, must form an arithmetic progression. Help Jeff, find all x that meet the problem conditions.", "input_spec": "The first line contains integer n (1 ≤ n ≤ 105). The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 105). The numbers are separated by spaces.", "output_spec": "In the first line print integer t — the number of valid x. On each of the next t lines print two integers x and px, where x is current suitable value, px is the common difference between numbers in the progression (if x occurs exactly once in the sequence, px must equal 0). Print the pairs in the order of increasing x.", "sample_inputs": ["1\n2", "8\n1 2 1 3 1 2 1 5"], "sample_outputs": ["1\n2 0", "4\n1 2\n2 4\n3 0\n5 0"], "notes": "NoteIn the first test 2 occurs exactly once in the sequence, ergo p2 = 0."}, "positive_code": [{"source_code": "var prev = new Int32Array(1e5 + 5);\nvar diff = new Int32Array(1e5 + 5);\nprint(function(n, a) {\n\n\tfor (var i = 1; i <= n; i++) {\n\t\tif (prev[a[i]] < 0) {\n\t\t\tcontinue;\n\t\t} else if (prev[a[i]] === 0) {\n\t\t\tprev[a[i]] = i;\n\t\t} else if (diff[a[i]] === 0) {\n\t\t\tdiff[a[i]] = i - prev[a[i]];\n\t\t\tprev[a[i]] = i;\n\t\t} else if (diff[a[i]] === i - prev[a[i]]) {\n\t\t\tprev[a[i]] = i;\n\t\t} else {\n\t\t\tprev[a[i]] = -1;\n\t\t}\n\t}\n\n\tvar ans = [];\n\tfor (var i = 0; i <= 1e5; i++)\n\t\tif (prev[i] > 0) ans.push(i + ' ' + diff[i]);\n\n\treturn ans.length + '\\n' + ans.join('\\n');\n\n}(+readline(), ('0 ' + readline()).split(' ').map(Number)));"}, {"source_code": "var elem = function(lastpos,isNew,prog){\n this.lastpos=-1;\n this.isNew=isNew;\n this.prog=prog;\n}\nvar n = parseInt(readline());\nvar a = readline().trim().split(' ').map((x)=>parseInt(x));\n\nvar map =[];\nvar N_MAX = 100006;\nfor(var i=0;i=0 && map[i].prog!==''){\n print(i+\" \"+map[i].prog);\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\n\nfunction main() {\n const len = +readLine();\n const arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const map = {};\n\n for (let i = 0; i < len; i++) {\n const num = arr[i];\n if (!map[num]) {\n map[num] = { count: 1, index: i, diff: 0, status: true };\n } else {\n let { count, index, diff, status } = map[num];\n if (status) {\n if (count === 1) {\n map[num] = { count: count + 1, index: i, diff: i - index, status: true };\n } else {\n map[num] = { count: count + 1, index: i, diff: i - index, status: diff === i - index };\n }\n }\n }\n }\n\n let count = 0,\n result = [];\n\n for (let key in map) {\n if (map[key].status) {\n const r = `${key} ${map[key].diff}`;\n result.push(r);\n count++;\n }\n }\n\n console.log(count);\n console.log(result.join(\"\\n\"));\n}\n"}, {"source_code": ";(function () {\n\n\tprint(function (n) {\n\n\t\tvar m = {alphabet: []};\n\t\treadline().split(' ').forEach(function (e, i) {\n\t\t\tif (m[e = parseInt(e)]) return m[e].push(i);\n\t\t\tm[e] = [i]; m.alphabet.push(e);\n\t\t});\n\n\t\tm.alphabet.map(function (e) { return e; }).forEach(function (e, i) {\n\t\t\tvar a = m[e];\n\n\t\t\tif (a.length === 1) return m[e] = e + ' 0';\n\n\t\t\tvar d = a[1] - a[0], flag = true;\n\t\t\tfor (var i = 2, _i = a.length; i < _i; i++) {\n\t\t\t\tif (a[i] - a[i - 1] !== d) {\n\t\t\t\t\tflag = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (flag) m[e] = e + ' ' + d;\n\t\t\telse m.alphabet.splice(m.alphabet.indexOf(e), 1);\n\n\t\t});\n\n\t\tif (m.alphabet.length === 0) return 0;\n\n\t\tm.alphabet.sort(function (a, b) { return a - b; });\n\n\t\treturn [m.alphabet.length].concat(m.alphabet.map(function (e) { return m[e]; })).join('\\n');\n\n\t}(+readline()));\n\n}.call(this));\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tnumbers = tokenizeIntegers(readline()),\n\t\toccur = {}, unique = [];\n\tfor (var i = 0; i < n; ++i) {\n\t\tvar x = numbers[i];\n\t\tif (occur[x] === undefined) {\n\t\t\toccur[x] = [i];\n\t\t\tunique.push(x);\n\t\t} else {\n\t\t\toccur[x].push(i);\n\t\t}\n\t}\n\tunique.sort(function (a, b) {\n\t\treturn a-b;\n\t});\n\tvar parts = [];\n\tfor (var i = 0; i < unique.length; ++i) {\n\t\tvar where = occur[unique[i]];\n\t\tif (where.length == 1) {\n\t\t\tparts.push(unique[i]+' '+0);\n\t\t} else {\n\t\t\tvar d = where[1]-where[0], okay = true;\n\t\t\tfor (var j = 2; okay && j < where.length; ++j) {\n\t\t\t\tif (where[j]-where[j-1] != d) {\n\t\t\t\t\tokay = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (okay) {\n\t\t\t\tparts.push(unique[i]+' '+d);\n\t\t\t}\n\t\t}\n\t}\n\tprint(parts.length);\n\tif (parts.length != 0) {\n\t\tprint(parts.join('\\n'));\n\t}\n}\n\nmain();\n"}], "negative_code": [{"source_code": "var n = parseInt(readline());\nvar a = readline().trim().split(' ').map((x)=>parseInt(x));\n\nvar map = {};\n\nfor(var i in a){\n if(map[a[i]]==undefined){\n map[a[i]]=[]; \n }\n map[a[i]].push(i);\n}\nvar ans = [];\nfor(var i in map){\n if(map[i].length==1)\n ans.push([i,0]);\n else if(map[i].length==2){\n ans.push([i,(map[i][1]-map[i][0])]);\n }else{\n var pro = map[i][1]-map[i][0];\n var not = false;\n for(var j=1;jparseInt(x));\n\nvar map = {};\n\nfor(var i in a){\n if(map[a[i]]==undefined){\n map[a[i]]=[]; \n }\n map[a[i]].push(i);\n}\nvar ans = [];\nfor(var i in map){\n if(map[i].length==1)\n ans.push([i,0]);\n else if(map[i].length==2){\n ans.push([i,(map[i][1]-map[i][0])]);\n }else{\n var pro = map[i][1]-map[i][0];\n var not = false;\n for(var j=1;jparseInt(x));\n\nvar map = {};\n\nfor(var i in a){\n if(map[a[i]]==undefined){\n map[a[i]]=[]; \n }\n map[a[i]].push(i);\n}\nvar ans = [];\nfor(var i in map){\n if(map[i].length==1)\n ans.push(i+' 0');\n else if(map[i].length==2){\n ans.push(i+' '+(map[i][1]-map[i][0]));\n }else{\n var pro = map[i][1]-map[i][0];\n var not = false;\n for(var j=1;j {\nvar readInts = () => {\n return readline().split(\" \").map(function(x) { return parseInt(x); });\n};\n\n/////////////////////////////////////////////////////////////// BEGIN\n\nvar nums = readInts();\nvar n = nums[0];\nvar k = nums[1];\n\nvar a = readInts();\nvar t = readInts();\n\nvar always = 0;\n\nt.forEach((_, i) => {\n if (t[i] == 1) {\n always += a[i];\n a[i] = 0;\n }\n});\n\nvar s = new Array(n).fill(0);\n\nfor (var i = 0; i < n; ++i) {\n s[i] = a[i] + (i == 0 ? 0 : s[i - 1]);\n}\n\nvar best = 0;\nfor (var i = 0; i < n; ++i) {\n var current = always + s[i] - (i - k >= 0 ? s[i - k] : 0);\n if (best < current) best = current;\n}\n\nprint(best + \"\\n\");\n\n/////////////////////////////////////////////////////////////// END OF CODE\n};\n\nif (isNodeJS) {\n var stdin = process.stdin;\n var stdout = process.stdout;\n var lines, currentLine = 0;\n stdin.resume();\n stdin.once('data', function(data) {\n data = data.toString().trim();\n lines = data.split(\"\\n\");\n var readline = () => {\n return lines[currentLine++];\n };\n doWork(readline, stdout.write.bind(stdout));\n });\n} else {\n doWork(readline, print);\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const [n, k] = readline().split(\" \").map(x => parseInt(x));\n const a = readline().split(\" \").map(x => parseInt(x));\n const t = readline().split(\" \").map(x => parseInt(x));\n let awake = t.reduce((acc,curr,index) => acc += a[index]*curr, 0);\n let extra = 0;\n for (let i=0; i n || sqSide > m) {\n print(-1);\n }\n else {\n for (var i = u; i<=d; i++) {\n for (var j = l; j<=r; j++) {\n if (arr[i][j] === 'W') {\n white++;\n }\n }\n }\n res = white + (sqSide - recSide) * sqSide;\n print(res);\n }\n}\n"}, {"source_code": "var data = readline().split(' '),\n m = parseInt(data[0]),\n n = parseInt(data[1]);\n \nvar b = 0,\n Xmin = -1,\n Ymin = -1,\n Xmax = -1,\n Ymax = -1;\n\nfor(var i = 0; i < m; i++) {\n var line = readline();\n \n for(var j = 0; j < n; j++) {\n if(line.charAt(j) === 'B') {\n if(b === 0) {\n Xmin = i;\n Ymin = j;\n Xmax = i;\n Ymax = j;\n } else {\n if(Xmin > i) {\n Xmin = i;\n }\n if(Ymin > j) {\n Ymin = j;\n }\n if(Xmax < i) {\n Xmax = i;\n }\n if(Ymax < j) {\n Ymax = j;\n }\n }\n b++;\n }\n }\n}\n\nif(b === 0) {\n print(1);\n} else if(b === 1){\n print(0);\n} else if(b === m * n && m === n) {\n print(0);\n} else if (b === m * n && m !== n) {\n print(-1);\n} else if(m === 1 || n === 1) {\n print(-1);\n} else {\n var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));\n if(a > n || a > m) {\n print(-1);\n } else {\n var s = a * a;\n var output = s - b;\n print(output);\n }\n\n}"}, {"source_code": "var s = readline().split(' ').map(Number);\nvar n = s[0], m = s[1];\n\nvar leftExt = null, rightExt = null, topExt = null, bottomExt = null;\nvar blacksCount = 0;\n\nfor (var i = 0; i < n; i++) {\n var currString = readline();\n var count = 0;\n\n for (var j = 0; j < m; j++) {\n if (currString[j] === 'B') {\n blacksCount += 1;\n count++;\n\n if (leftExt === null) {\n leftExt = j;\n } else if (j < leftExt) {\n leftExt = j;\n }\n\n if (rightExt === null) {\n rightExt = j;\n } else if (j > rightExt) {\n rightExt = j;\n }\n }\n }\n \n if (count > 0) { \n \tif (topExt === null) {\n topExt = i;\n } else if (i < topExt) {\n topExt = i;\n }\n\n if (bottomExt === null) {\n bottomExt = i;\n } else if (i > bottomExt) {\n bottomExt = i;\n }\n }\n}\n\nvar verticalSideLength = bottomExt - topExt + 1;\nvar horizontalSideLength = rightExt - leftExt + 1;\nvar maxSideLength = Math.max(horizontalSideLength, verticalSideLength);\n\nif (maxSideLength > n || maxSideLength > m) {\n print('-1');\n} else {\n print(maxSideLength * maxSideLength - blacksCount);\n};"}], "negative_code": [{"source_code": "var data = readline().split(' '),\n m = parseInt(data[0]),\n n = parseInt(data[1]);\n \nvar b = 0,\n Xmin = -1,\n Ymin = -1,\n Xmax = -1,\n Ymax = -1;\n\nfor(var i = 0; i < m; i++) {\n var line = readline();\n \n for(var j = 0; j < n; j++) {\n if(line.charAt(j) === 'B') {\n if(b === 0) {\n Xmin = i;\n Ymin = j;\n Xmax = i;\n Ymax = j;\n } else {\n if(Xmin > i) {\n Xmin = i;\n }\n if(Ymin > j) {\n Ymin = j;\n }\n if(Xmax < i) {\n Xmax = i;\n }\n if(Ymax < j) {\n Ymax = j;\n }\n }\n b++;\n }\n }\n}\n\nif(b === 0) {\n print(1);\n} else if(b === 1){\n print(0);\n} else if(b === m * n) {\n print(0);\n} else if(m === 1 || n === 1) {\n print(-1);\n} else {\n var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));\n if(a > n || a > m) {\n print(-1);\n } else {\n var s = a * a;\n var output = s - b;\n print(output);\n }\n\n}"}, {"source_code": "var data = readline().split(' '),\n m = parseInt(data[0]),\n n = parseInt(data[1]);\n \nvar b = 0,\n Xmin = -1,\n Ymin = -1,\n Xmax = -1,\n Ymax = -1;\n\nfor(var i = 0; i < m; i++) {\n var line = readline();\n \n for(var j = 0; j < n; j++) {\n if(line.charAt(j) === 'B') {\n if(b === 0) {\n Xmin = i;\n Ymin = j;\n Xmax = i;\n Ymax = j;\n } else {\n if(Xmin > i) {\n Xmin = i;\n }\n if(Ymin > j) {\n Ymin = j;\n }\n if(Xmax < i) {\n Xmax = i;\n }\n if(Ymax < j) {\n Ymax = j;\n }\n }\n b++;\n }\n }\n}\n\nif(b === 0) {\n print(1);\n} else if(b === 1){\n print(0);\n} else if(b === m * n) {\n print(-1);\n} else if(m === 1 || n === 1) {\n print(-1);\n} else {\n var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));\n if(a > n || a > m) {\n print(-1);\n } else {\n var s = a * a;\n var output = s - b;\n print(output);\n }\n\n}"}, {"source_code": "var data = readline().split(' '),\n m = data[0],\n n = data[1];\n \nvar b = 0,\n Xmin = -1,\n Ymin = -1,\n Xmax = -1,\n Ymax = -1;\n\nfor(var i = 0; i < m; i++) {\n var line = readline();\n \n for(var j = 0; j < n; j++) {\n if(line.charAt(j) === 'B') {\n if(b === 0) {\n Xmin = i;\n Ymin = j;\n Xmax = i;\n Ymax = j;\n } else {\n if(Xmin > i) {\n Xmin = i;\n }\n if(Ymin > j) {\n Ymin = j;\n }\n if(Xmax < i) {\n Xmax = i;\n }\n if(Ymax < j) {\n Ymax = j;\n }\n }\n b++;\n }\n }\n}\n\nif(b === 0) {\n print(1);\n} else if(b === 1){\n print(0);\n} else if(b === m * n) {\n print(-1);\n} else {\n var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));\n var s = a * a;\n var output = s - b;\n print(output);\n}"}, {"source_code": "var data = readline().split(' '),\n m = parseInt(data[0]),\n n = parseInt(data[1]);\n \nvar b = 0,\n Xmin = -1,\n Ymin = -1,\n Xmax = -1,\n Ymax = -1;\n\nfor(var i = 0; i < m; i++) {\n var line = readline();\n \n for(var j = 0; j < n; j++) {\n if(line.charAt(j) === 'B') {\n if(b === 0) {\n Xmin = i;\n Ymin = j;\n Xmax = i;\n Ymax = j;\n } else {\n if(Xmin > i) {\n Xmin = i;\n }\n if(Ymin > j) {\n Ymin = j;\n }\n if(Xmax < i) {\n Xmax = i;\n }\n if(Ymax < j) {\n Ymax = j;\n }\n }\n b++;\n }\n }\n}\n\nif(b === 0) {\n print(1);\n} else if(b === 1){\n print(0);\n} else if(b === m * n) {\n print(-1);\n} else if(m === 1 || n === 1) {\n print(-1);\n} else {\n var a = Math.max((Xmax - Xmin + 1), (Ymax - Ymin + 1));\n var s = a * a;\n var output = s - b;\n print(output);\n}"}, {"source_code": "var s = readline().split(' ').map(Number);\nvar n = s[0], m = s[1];\n\nvar leftExt = null, rightExt = null, topExt = null, bottomExt = null;\nvar blacksCount = 0;\n\nfor (var i = 0; i < n; i++) {\n var currString = readline();\n\n for (var j = 0; j < m; j++) {\n if (currString[j] === 'B') {\n blacksCount += 1;\n\n if (leftExt === null) {\n leftExt = j;\n } else if (j < leftExt) {\n leftExt = j;\n }\n\n if (rightExt === null) {\n rightExt = j;\n } else if (j > rightExt) {\n rightExt = j;\n }\n }\n }\n\n if (topExt === null) {\n topExt = i;\n } else if (i < topExt) {\n topExt = i;\n }\n\n if (bottomExt === null) {\n bottomExt = i;\n } else if (i > bottomExt) {\n bottomExt = i;\n }\n} \n\n\nvar horizontalSideLength = bottomExt - topExt + 1;\nvar verticalSideLength = rightExt - leftExt + 1;\nvar maxSideLength = Math.max(horizontalSideLength, verticalSideLength);\n\nprint(bottomExt);\nprint(topExt);\n\nif (bottomExt + 1 - maxSideLength < 0) {\n print(\"-1\");\n} else if (rightExt + 1 - maxSideLength < 0) {\n print(\"-1\");\n} else {\n print(maxSideLength * maxSideLength - blacksCount);\n}"}, {"source_code": "var s = readline().split(' ').map(Number);\nvar n = s[0], m = s[1];\n\nvar leftExt = null, rightExt = null, topExt = null, bottomExt = null;\nvar blacksCount = 0;\n\nfor (var i = 0; i < n; i++) {\n var currString = readline();\n var count = 0;\n\n for (var j = 0; j < m; j++) {\n if (currString[j] === 'B') {\n blacksCount += 1;\n count++;\n\n if (leftExt === null) {\n leftExt = j;\n } else if (j < leftExt) {\n leftExt = j;\n }\n\n if (rightExt === null) {\n rightExt = j;\n } else if (j > rightExt) {\n rightExt = j;\n }\n }\n }\n \n if (count > 0) { \n \tif (topExt === null) {\n topExt = i;\n } else if (i < topExt) {\n topExt = i;\n }\n\n if (bottomExt === null) {\n bottomExt = i;\n } else if (i > bottomExt) {\n bottomExt = i;\n }\n }\n} \n\nvar verticalSideLength = bottomExt - topExt + 1;\nvar horizontalSideLength = rightExt - leftExt + 1;\nvar maxSideLength = Math.max(horizontalSideLength, verticalSideLength);\n\nif (bottomExt + 1 - maxSideLength < 0) {\n print(\"-1\");\n} else if (rightExt + 1 - maxSideLength < 0) {\n print(\"-1\");\n} else {\n print(maxSideLength * maxSideLength - blacksCount);\n}"}], "src_uid": "cd6bc23ea61c43b38c537f9e04ad11a6"} {"nl": {"description": "Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.", "input_spec": "The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000). ", "output_spec": "In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.", "sample_inputs": ["2 10 3\n100 3\n99 1", "2 100 10\n100 11\n90 9"], "sample_outputs": ["NO", "YES\n19 2\n0 1\n10 2"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nlet N = lll[0]\nlet H = lll[1]\nlet R = lll[2]\nlet h = H\nlet d = 0\n\nlet ss = []\n\nwhile (lll = readline()) {\n ss.push(lll.split(' ').map(v => parseInt(v)))\n}\n\nlet fail = false\nlet t = 0\nlet uss = []\nlet i = 0\nwhile (h > 0) {\n h = Math.min(h - d + R, H)\n let bs = gbs()\n let bsi = ss.indexOf(bs)\n if (bs && h > 0) {\n d += bs[1]\n bs[0] = -1\n uss.push([t, bsi + 1])\n } else if (h == H) {\n fail = true\n break\n }\n t++\n}\n\nif (fail) {\n print('NO')\n} else {\n print('YES')\n print(t - 1 + ' ' + uss.length)\n uss.forEach(v => print(v.join(' ')))\n}\n\nfunction gbs () {\n let lim = h / H * 100\n return ss.filter(s => s[0] >= lim)\n .sort((a, b) => b[1] - a[1])\n [0]\n}"}], "negative_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nlet N = lll[0]\nlet H = lll[1]\nlet R = lll[2]\nlet h = H\nlet d = 0\n\nlet ss = []\n\nwhile (lll = readline()) {\n ss.push(lll.split(' ').map(v => parseInt(v)))\n}\n\nlet fail = false\nlet t = 0\nlet uss = []\nlet i = 0\nwhile (h > 0 && !fail) {\n h -= d\n h = Math.min(h + R, H)\n let bs = gbs()\n let bsi = ss.indexOf(bs)\n if (bs) {\n d += bs[1]\n bs[0] = -1\n uss.push([t, bsi + 1])\n } else if (h == H) {\n fail = true\n }\n t++\n}\n\nif (fail) {\n print('NO')\n} else {\n print('YES')\n print(t - 1 + ' ' + uss.length)\n uss.forEach(v => print(v.join(' ')))\n}\n\nfunction gbs () {\n let lim = h / H * 100\n return ss.filter(s => s[0] >= lim)\n .sort((a, b) => b[1] - a[1])\n [0]\n}"}, {"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nlet N = lll[0]\nlet H = lll[1]\nlet R = lll[2]\nlet h = H\nlet d = 0\n\nlet ss = []\n\nwhile (lll = readline()) {\n ss.push(lll.split(' ').map(v => parseInt(v)))\n}\n\nlet fail = false\nlet t = 0\nlet uss = []\nlet i = 0\nwhile (true) {\n h -= d\n if (h < 0) break\n h = Math.min(h + R, H)\n let bs = gbs()\n let bsi = ss.indexOf(bs)\n if (bs) {\n d += bs[1]\n bs[0] = -1\n uss.push([t, bsi + 1])\n } else if (h == H) {\n fail = true\n break\n }\n t++\n}\n\nif (fail) {\n print('NO')\n} else {\n print('YES')\n print(t + ' ' + uss.length)\n uss.forEach(v => print(v.join(' ')))\n}\n\nfunction gbs () {\n let lim = h / H * 100\n return ss.filter(s => s[0] >= lim)\n .sort((a, b) => b[1] - a[1])\n [0]\n}"}], "src_uid": "e9c486e2d942700e0644dff29b6e3be6"} {"nl": {"description": "This is an interactive problem.Vasya and Petya are going to play the following game: Petya has some positive integer number $$$a$$$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $$$(x, y)$$$. Petya will answer him: \"x\", if $$$(x \\bmod a) \\geq (y \\bmod a)$$$. \"y\", if $$$(x \\bmod a) < (y \\bmod a)$$$. We define $$$(x \\bmod a)$$$ as a remainder of division $$$x$$$ by $$$a$$$.Vasya should guess the number $$$a$$$ using no more, than 60 questions.It's guaranteed that Petya has a number, that satisfies the inequality $$$1 \\leq a \\leq 10^9$$$.Help Vasya playing this game and write a program, that will guess the number $$$a$$$.", "input_spec": null, "output_spec": null, "sample_inputs": ["start\nx\nx\nstart\nx\nx\ny\nstart\nx\nx\ny\ny\nend"], "sample_outputs": ["? 0 0\n? 10 1\n! 1\n? 0 0\n? 3 4\n? 2 5\n! 2\n? 2 4\n? 2 5\n? 3 10\n? 9 1\n! 3"], "notes": "NoteIn the first test, you should play $$$3$$$ games with Petya's numbers $$$1$$$, $$$2$$$ and $$$3$$$.In the first game, Petya will answer \"x\" (without quotes) to any question, because $$$(x \\bmod 1) = 0$$$ for any integer $$$x$$$. In the second game, if you will ask pair $$$(0, 0)$$$, the answer will be \"x\" (without quotes), because $$$(0 \\bmod 2) \\geq (0 \\bmod 2)$$$. But if you will ask pair $$$(2, 5)$$$, the answer will be \"y\" (without quotes), because $$$(2 \\bmod 2) < (5 \\bmod 2)$$$, because $$$(2 \\bmod 2) = 0$$$ and $$$(5 \\bmod 2) = 1$$$."}, "positive_code": [{"source_code": "var x, y, mid;\n\nfunction q(a, b) {\n print('? ' + a + ' ' + b);\n}\n\nwhile(true) {\n var s = readline();\n\n if(s === 'start') {\n x = 1, y = 2;\n while(true) {\n q(x, y)\n c = readline();\n if(c === 'y') {\n x *= 2;\n y *= 2;\n }\n else {\n break;\n }\n }\n\n while(y - x > 1) {\n mid = Math.floor((x + y) / 2);\n q(x, mid);\n c = readline();\n if(c === 'y') {\n x = mid;\n }\n else {\n y = mid;\n }\n }\n\n q(y, x);\n\n c = readline();\n\n if(c === 'x') {\n print('! ' + x);\n }\n else {\n print('! ' + y);\n }\n }\n else {\n break;\n }\n}"}], "negative_code": [], "src_uid": "eab8e5ac203d9f10c893ea35d249fe84"} {"nl": {"description": "The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of $$$m$$$ pages.Polycarp also has $$$n$$$ cups of coffee. The coffee in the $$$i$$$-th cup Polycarp has $$$a_i$$$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).Let's consider some day of Polycarp's work. Consider Polycarp drinks $$$k$$$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $$$a_{i_1}, a_{i_2}, \\dots, a_{i_k}$$$. Then the first cup he drinks gives him energy to write $$$a_{i_1}$$$ pages of coursework, the second cup gives him energy to write $$$max(0, a_{i_2} - 1)$$$ pages, the third cup gives him energy to write $$$max(0, a_{i_3} - 2)$$$ pages, ..., the $$$k$$$-th cup gives him energy to write $$$max(0, a_{i_k} - k + 1)$$$ pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m \\le 10^9$$$) — the number of cups of coffee and the number of pages in the coursework. 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 caffeine dosage of coffee in the $$$i$$$-th cup.", "output_spec": "If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.", "sample_inputs": ["5 8\n2 3 1 1 2", "7 10\n1 3 4 2 1 4 2", "5 15\n5 5 5 5 5", "5 16\n5 5 5 5 5", "5 26\n5 5 5 5 5"], "sample_outputs": ["4", "2", "1", "2", "-1"], "notes": "NoteIn the first example Polycarp can drink fourth cup during first day (and write $$$1$$$ page), first and second cups during second day (and write $$$2 + (3 - 1) = 4$$$ pages), fifth cup during the third day (and write $$$2$$$ pages) and third cup during the fourth day (and write $$$1$$$ page) so the answer is $$$4$$$. It is obvious that there is no way to write the coursework in three or less days.In the second example Polycarp can drink third, fourth and second cups during first day (and write $$$4 + (2 - 1) + (3 - 2) = 6$$$ pages) and sixth cup during second day (and write $$$4$$$ pages) so the answer is $$$2$$$. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15$$$ pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) = 14$$$ pages of coursework and during second day he will write $$$5$$$ pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1."}, "positive_code": [{"source_code": "var nums = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = nums[0], m = nums[1];\nvar s = readline().split(\" \").map(function(x) { return parseInt(x); });\n\n//var sum = 0;\n//for (var i=0; idown) {\n//write(\" down = \", down, \"\\n\");\n//write(\" up = \", up, \"\\n\\n\");\n\tvar mid = Math.floor((up+down)/2);\n\t//var res = sum;\n\tvar dvv = Math.floor(n/mid);\n\tvar rem = n % mid;\n\n\tvar res = 0;\n\tvar fr = 0;\n\tif (rem > 0) {\n\t\tfor (var i=0; i 0)\n\t//\tres -= rem * dvv;\n\t\n\tif (res >= m) up = mid;\n\telse down = mid + 1;\n}\nif (down > Math.min(n,m)) write(\"-1\");\nelse write(down);"}], "negative_code": [{"source_code": "var nums = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = nums[0], m = nums[1];\nvar s = readline().split(\" \").map(function(x) { return parseInt(x); });\n\nvar sum = 0;\nfor (var i=0; idown) {\n\tvar mid = Math.floor((up+down)/2);\n\tvar res = sum;\n\tvar dvv = Math.floor(n/mid);\n\t//0...dvv-1\n\tres -= Math.floor(dvv*(dvv-1)/2);\n\tvar rem = n % mid;\n\tif (rem > 0)\n\t\tres -= rem * dvv;\n\tif (res >= m) up = mid;\n\telse down = mid + 1;\n}\nif (down > Math.min(n,m)) write(\"-1\");\nelse write(down);"}], "src_uid": "1b79ff21b5c1df4c54236071a585a52e"} {"nl": {"description": "You are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.Segment [l1, r1] lies within segment [l2, r2] iff l1 ≥ l2 and r1 ≤ r2.Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.", "input_spec": "The first line contains one integer n (1 ≤ n ≤ 3·105) — the number of segments. Each of the next n lines contains two integers li and ri (1 ≤ li ≤ ri ≤ 109) — the i-th segment.", "output_spec": "Print two distinct indices i and j such that segment ai lies within segment aj. If there are multiple answers, print any of them. If no answer exists, print -1 -1.", "sample_inputs": ["5\n1 10\n2 9\n3 9\n2 3\n2 9", "3\n1 5\n2 6\n6 20"], "sample_outputs": ["2 1", "-1 -1"], "notes": "NoteIn the first example the following pairs are considered correct: (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders; (3, 2), (4, 2), (3, 5), (4, 5) — touch one border; (5, 2), (2, 5) — match exactly. "}, "positive_code": [{"source_code": "var n = readline(), arr = []; ansl = -1, ansr = -1;\nfor(var i = 0; i < n; i++) {\n var tp = readline().split(' ');\n arr[i] = {id: i + 1, li: parseInt(tp[0]), ri: parseInt(tp[1])}; \n}\narr.sort((p1, p2) => {\n if(p1.li === p2.li) return p2.ri - p1.ri;\n return p1.li - p2.li\n});\nfor(var i = 1, tl = arr[0].id, max = arr[0].ri; i < n; i++) {\n if(arr[i].ri > max) tl = arr[i].id, max = arr[i].ri;\n else {\n ansl = tl, ansr = arr[i].id;\n break;\n }\n}\nprint(ansr, ansl);"}], "negative_code": [{"source_code": "var n = readline(), arr = []; ansl = -1, ansr = -1;\nfor(var i = 0; i < n; i++) {\n var tp = readline().split(' ');\n arr[i] = {id: i + 1, li: parseInt(tp[0]), ri: parseInt(tp[1])}; \n}\narr.sort((p1, p2) => p1.li - p2.li);\nfor(var i = 1, tl = arr[0].id, max = arr[0].ri; i < n; i++) {\n if(arr[i].ri > max) tl = arr[i].id, max = arr[i].ri;\n else {\n ansl = tl, ansr = arr[i].id;\n break;\n }\n}\nprint(ansr, ansl);"}, {"source_code": "var nq = readline().split(' ');\nvar n = +nq[0], q = +nq[1], ai = [], ki = [];\nai = readline().split(' ').map(item => Math.floor(+item));\nki = readline().split(' ').map(item => Math.floor(+item));\nfor(var i = 1; i < n; i++) ai[i] += ai[i - 1];\nfor(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {\n lo = n - ans, key = ki[i] + sum;\n sum += ki[i];\n while(lo <= hi) {\n var mid = Math.floor( hi- (hi - lo) / 2 );\n if(ai[mid] > key) hi = mid - 1;\n else lo = mid + 1;\n }\n if(hi === n - 1) sum = 0, ans = n;\n else if(hi === -1) ans = n;\n else ans = n - hi - 1;\n print(ans);\n}"}, {"source_code": "var n = readline(), arr = []; ansl = -1, ansr = -1;\nfor(var i = 0; i < n; i++) {\n var tp = readline().split(' ');\n arr[i] = {id: i + 1, li: parseInt(tp[0]), ri: parseInt(tp[1])}; \n}\narr.sort((p1, p2) => p1.li - p2.li);\nfor(var i = 1, tl = arr[0].id, max = arr[0].ri; i < n; i++) {\n if(arr[i].ri > max) tl = arr[i].id, max = arr[i].ri;\n else {\n ansl = tl, ansr = arr[i].id;\n break;\n }\n}\nprint(ansl, ansr);"}], "src_uid": "0148aed9b07c4f65b2507fcb8b837360"} {"nl": {"description": "You've got an array a, consisting of n integers: a1, a2, ..., an. Your task is to find a minimal by inclusion segment [l, r] (1 ≤ l ≤ r ≤ n) such, that among numbers al,  al + 1,  ...,  ar there are exactly k distinct numbers.Segment [l, r] (1 ≤ l ≤ r ≤ n; l, r are integers) of length m = r - l + 1, satisfying the given property, is called minimal by inclusion, if there is no segment [x, y] satisfying the property and less then m in length, such that 1 ≤ l ≤ x ≤ y ≤ r ≤ n. Note that the segment [l, r] doesn't have to be minimal in length among all segments, satisfying the given property.", "input_spec": "The first line contains two space-separated integers: n and k (1 ≤ n, k ≤ 105). The second line contains n space-separated integers a1, a2, ..., an — elements of the array a (1 ≤ ai ≤ 105).", "output_spec": "Print a space-separated pair of integers l and r (1 ≤ l ≤ r ≤ n) such, that the segment [l, r] is the answer to the problem. If the sought segment does not exist, print \"-1 -1\" without the quotes. If there are multiple correct answers, print any of them.", "sample_inputs": ["4 2\n1 2 2 3", "8 3\n1 1 2 2 3 3 4 5", "7 4\n4 7 7 4 7 4 7"], "sample_outputs": ["1 2", "2 5", "-1 -1"], "notes": "NoteIn the first sample among numbers a1 and a2 there are exactly two distinct numbers.In the second sample segment [2, 5] is a minimal by inclusion segment with three distinct numbers, but it is not minimal in length among such segments.In the third sample there is no segment with four distinct numbers."}, "positive_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(Number)\n const [length, distinct] = input\n const nums = readline().split(' ').map(Number)\n helper(nums, length, distinct)\n}\n\nfunction helper(nums, length, distinct) {\n let cnt = new Map()\n let unique = 0\n let j = 0\n \n for (let i = 0; i < length; i++) {\n const num = nums[i]\n if (!cnt.has(num))\n unique++\n cnt.set(num, (cnt.get(num) || 0) + 1)\n while (unique === distinct) {\n cnt.set(nums[j], cnt.get(nums[j])-1);\n if (cnt.get(nums[j]) === 0) {\n console.log((j + 1) + ' ' + (i + 1))\n return\n }\n j++\n }\n }\n \n console.log('-1 -1')\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array(100010);\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n\nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array(100010).fill(0);\n // for (let i = 0; i <= 100010; i++) {\n // counts[i] = 0;\n // }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = [];\n // const counts = new Array(100010);\n // for (let i = 0; i <= 100010; i++) {\n // counts[i] = 0;\n // }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array(100010);\n // for (let i = 0; i <= 100010; i++) {\n // counts[i] = 0;\n // }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment2(n, k, arr);\n printResult(result);\n}\n\nconst countSegment = (n, k, ar) => {\n // const counts = new Array(100010).fill(0);\n const counts = [];\n for (let i = 0; i <= 100010; i++) {\n counts.push(0);\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[start] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n\n return end ? `${start} ${end}` : `-1 -1`;\n}\n\nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n}\n\nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ');\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array(100001);\n // const counts = new Array(100010);\n // for (let i = 0; i <= 100010; i++) {\n // counts[i] = 0;\n // }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[parseInt(ar[i], 10)]) {\n counts[parseInt(ar[i], 10)] = `${i}`;\n if (ar[i] == ar[start]) {\n while (counts[parseInt(ar[start], 10)] != start) {\n start++;\n }\n }\n continue;\n }\n counts[parseInt(ar[i], 10)] = `${i}`;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n \n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array(100001).fill(0);\n // const counts = new Array(100010);\n // for (let i = 0; i <= 100010; i++) {\n // counts[i] = 0;\n // }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n \n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n // const counts = new Array(100010).fill(0);\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array();\n // const counts = new Array(100010);\n // for (let i = 0; i <= 100010; i++) {\n // counts[i] = 0;\n // }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n\n const result = countSegment(n, k, arr);\n printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n const counts = new Array(100001);\n // for (let i = 0; i <= 100010; i++) {\n // counts[i] = 0;\n // }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "function giaiBai(inp1, inp2) {\n inp1 = inp1.split(' ').map(e => parseInt(e))\n inp2 = inp2.split(' ').map(e => parseInt(e))\n inp2.unshift(0)\n\n let n = inp1[0],\n k = inp1[1],\n a = inp2,\n c = new Array(10e5).fill(0),\n count = 0,\n j = 0\n\n for(var i = 1; i <= n; i++) {\n c[a[i]]++\n if (c[a[i]] === 1) {\n count++\n }\n while (count === k) {\n j++\n c[a[j]]--\n if(c[a[j]] === 0) {\n console.log(j, i)\n break\n }\n }\n if(count === k) {\n break\n }\n }\n if (count === k) {\n return\n }\n console.log('-1 -1')\n}\n\nvar readline = require('readline');\n// Get process.stdin as the standard input object.\nvar standard_input = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\n// Set input character encoding.\n// standard_input.setEncoding('utf-8');\n\n// Prompt user to input data in console.\n// console.log(\"Please input text in command line.\");\n\n// When user input data and click enter key.\nstandard_input.on('line', function (inp1) {\n// console.log(inp1);\n standard_input.on('line', function (inp2) {\n // Print user input in console.\n inp1 = inp1.trim()\n inp2 = inp2.trim()\n giaiBai(inp1, inp2)\n process.exit();\n });\n});\n"}], "negative_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(Number)\n const [length, distinct] = input\n const nums = readline().split(' ').map(Number)\n helper(nums, length, distinct)\n}\n\nfunction helper(nums, length, distinct) {\n let cnt = new Map()\n let unique = 0\n let j = 0\n\n for (let i = 0; i < length; i++) {\n const num = nums[i]\n if (!cnt.has(num))\n unique++\n cnt.set(num, (cnt.get(num) || 0) + 1)\n while (unique === distinct) {\n cnt.set(num, cnt.get(num)-1);\n if (cnt.get(num) === 0) {\n console.log((j + 1) + ' ' + (i + 1))\n return\n }\n j++\n }\n }\n\n console.log('-1 -1')\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// Make a Snippet for the code above this and then write your logic in main()\nfunction main() {\n const input = readline().split(' ').map(Number)\n const [length, distinct] = input\n const nums = readline().split(' ').map(Number)\n helper(nums, length, distinct)\n}\n\nfunction helper(nums, length, distinct) {\n let cnt = new Map()\n let unique = 0\n let j = 0\n\n for (let i = 0; i < length; i++) {\n const num = nums[i]\n if (!cnt.has(num))\n unique++\n cnt.set(num, (cnt.get(num) || 0) + 1)\n while (unique === distinct) {\n cnt.set(num, cnt.get(num)-1);\n if (cnt.get(num) === 0) {\n console.log(i + ' ' + j)\n return\n }\n j++\n }\n }\n\n console.log('-1 -1')\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main();\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n \nfunction main() {\n // const nk = parseInt(readLine(), 10);\n const nk = readLine().split(' ').map(Number);\n const arr = `0 ${readLine()}`.split(' ').map(Number);\n const n = nk[0];\n const k = nk[1];\n // console.log(n, k, arr)\n \n const result = countSegment(n, k, arr);\n // printResult(result);\n}\n \nconst countSegment = (n, k, ar) => {\n // const counts = new Array(100010).fill(0);\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n counts[ar[i]] = i;\n if (ar[i] === ar[start]) {\n while (counts[ar[start]] !== start) {\n start++;\n }\n }\n continue;\n }\n counts[ar[i]] = i;\n sum++;\n if (sum === k) {\n end = i;\n break;\n }\n }\n \n return end ? `${start} ${end}` : `-1 -1`;\n};\n \nconst countSegment2 = (n, k, ar) => {\n const counts = new Array(100010);\n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n let start = 1;\n let end = 0;\n let sum = 0;\n let f;\n for (let i = 1; i <= n; i++) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n end = i;\n f = 1;\n break;\n }\n }\n \n for (let i = 0; i <= 100010; i++) {\n counts[i] = 0;\n }\n sum = 0;\n for (let i = end; i >= 1; i--) {\n if (counts[ar[i]]) {\n continue;\n }\n counts[ar[i]] = 1;\n sum++;\n if (sum === k) {\n start = i;\n break;\n }\n }\n return f ? `${start} ${end}` : `-1 -1`;\n};\n \nfunction printResult(x) {\n process.stdout.write(x);\n}"}, {"source_code": "function giaiBai(inp1, inp2) {\n inp1 = inp1.split(' ').map(e => parseInt(e))\n inp2 = inp2.split(' ').map(e => parseInt(e))\n inp2.unshift(0)\n\n let n = inp1[0],\n k = inp1[1],\n a = inp2,\n c = new Array(10e5).fill(0),\n count = 0,\n j = 0\n\n for(var i = 1; i <= n; i++) {\n c[a[i]]++\n if (c[a[i]] === 1) {\n count++\n }\n while (count === k) {\n j++\n c[a[j]]--\n if(c[a[j]] === 0) {\n console.log(j, i)\n break\n }\n }\n if(count === k) {\n break\n }\n }\n if (count === k) {\n return\n }\n console.log('-1 -1')\n}\n\n// var readline = require('readline');\n// Get process.stdin as the standard input object.\n// var standard_input = readline.createInterface({\n// input: process.stdin,\n// output: process.stdout,\n// terminal: false\n// });\nvar standard_input = process.stdin;\n// Set input character encoding.\n// standard_input.setEncoding('utf-8');\n\n// Prompt user to input data in console.\n// console.log(\"Please input text in command line.\");\n\n// When user input data and click enter key.\nstandard_input.on('line', function (inp1) {\n// console.log(inp1);\n standard_input.on('line', function (inp2) {\n // Print user input in console.\n inp1 = inp1.trim()\n inp2 = inp2.trim()\n giaiBai(inp1, inp2)\n process.exit();\n });\n});\n"}, {"source_code": "function giaiBai(inp1, inp2) {\n inp1 = inp1.split(' ').map(e => parseInt(e))\n inp2 = inp2.split(' ').map(e => parseInt(e))\n inp2.unshift(0)\n\n let n = inp1[0],\n k = inp1[1],\n a = inp2,\n c = new Array(10e5).fill(0),\n count = 0,\n j = 0\n\n for(var i = 1; i <= n; i++) {\n c[a[i]]++\n if (c[a[i]] === 1) {\n count++\n }\n while (count === k) {\n j++\n c[a[j]]--\n if(c[a[j]] === 0) {\n console.log(j, i)\n break\n }\n }\n if(count === k) {\n break\n }\n }\n if (count === k) {\n return\n }\n console.log('-1 -1')\n}\n\nvar readline = require('readline');\n// Get process.stdin as the standard input object.\nvar standard_input = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n// Set input character encoding.\n// standard_input.setEncoding('utf-8');\n\n// Prompt user to input data in console.\n// console.log(\"Please input text in command line.\");\n\n// When user input data and click enter key.\nstandard_input.on('data1', function (inp1) {\n standard_input.on('data2', function (inp2) {\n // Print user input in console.\n inp1 = inp1.trim()\n inp2 = inp2.trim()\n giaiBai(inp1, inp2)\n process.exit();\n });\n});"}], "src_uid": "4b423274448ff3f0dee7644203706805"} {"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$$$) — 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 — 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 inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let n = +readLine();\n let count = 0;\n\n while (n > 1 && n < Number.MAX_SAFE_INTEGER) {\n if (n % 6 === 0) {\n while (n % 6 === 0) {\n n /= 6;\n count++;\n }\n } else {\n n *= 2;\n count++;\n }\n }\n if (n === 1) console.log(count);\n else console.log(-1);\n }\n}\n"}, {"source_code": "//↓見なくていいよ!ここから--------------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n \n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n\n//↑見なくていいよ!ここまで--------------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar n = nextInt();\n\t\tif(n == 1){\n\t\t\toutput[i] = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tvar two = 0;\n\t\tvar three = 0;\n\t\twhile(n % 3 == 0){\n\t\t\tn /= 3;\n\t\t\tthree++;\n\t\t}\n\t\twhile(n % 2 == 0){\n\t\t\tn /= 2;\n\t\t\ttwo++;\n\t\t}\n\t\tif(n != 1){\n\t\t\toutput[i] = -1;\n\t\t}else{\n\t\t\tif(three >= two){\n\t\t\t\toutput[i] = two + (three - two) * 2;\n\t\t\t}else{\n\t\t\t\toutput[i] = -1;\n\t\t\t}\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}\nfunction getPrimeFactorization(val){\n var primeMap = {};\n var div = 2;\n while(val != 1){\n if(val % div == 0){\n var count = 2;\n while(val % Math.pow(div, count) == 0){\n count++;\n }\n (primeMap[div] == null) ? primeMap[div] = (count - 1) : primeMap[div] += (count - 1);\n val /= Math.pow(div, count - 1);\n if(isPrime(val)){\n (primeMap[val] == null) ? primeMap[val] = 1 : primeMap[val]++;\n break;\n }\n }\n div = (div == 2) ? div + 1 : div + 2;\n }\n return primeMap;\n}\nfunction isPrime(val){\n if(val == null || val <= 1 || (val != 2 && val % 2 == 0)){\n return false;\n }else if(val == 2){\n return true;\n }\n var root = Math.floor(Math.sqrt(val));\n for(var i = 3; i <= root; i += 2){\n if(val % i == 0){\n return false;\n }\n }\n return true;\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 1;\n let i = 1;\n while (i <= testCases) {\n let n = +data[i];\n let check = false;\n let count = 0;\n while (true) {\n const mod = n % 6;\n if (n === 1) {\n console.log(count);\n break; \n } else if (mod && check) {\n console.log(-1);\n break;\n } else if (!mod) {\n n /= 6;\n check = false;\n }\n else {\n n *= 2;\n check = true;\n }\n count += 1;\n }\n i += 1;\n }\n }"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet ans = '';\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let n = BigInt(d);\n\n if (n === 1n) {\n ans += '0\\n';\n }\n else {\n let test = 0;\n for (let i = 0; i < 50; i++) {\n if (n % 6n === 0n) {\n n = n / 6n;\n }\n else {\n n = n * 2n;\n }\n\n if (n === 1n) {\n test = i + 1;\n break;\n }\n }\n\n if (test) {\n ans += `${test}\\n`;\n }\n else {\n ans += `-1\\n`;\n }\n }\n\n c++;\n});\n\nrl.on('close', () => {\n console.log(ans);\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n function solve(x, moves) {\n if (x === 1) { return moves; }\n else if (x%2 === 1) { return solve(2*x, moves+1); }\n else if (x%6 === 0) { return solve(Math.floor(x/6), moves+1); }\n else { return -1; }\n }\n const testCases = parseInt(readline());\n for (var i=0; i {\n if (lineCount == 0) {\n // first line\n testCount = parseInt(input)\n }\n else if (lineCount >= testCount) {\n outputStr += compute(input) + '\\n'\n console.log(outputStr)\n rl.close()\n }\n else {\n // data\n outputStr += compute(input) + '\\n'\n }\n lineCount++\n});\n\nfunction compute(str) {\n var n = parseInt(str)\n var temp = n\n var timesOfTwo = 0\n var timesOfThree = 0\n while(temp%2==0){\n temp = temp / 2\n timesOfTwo+=1\n }\n while(temp%3==0){\n temp = temp / 3\n timesOfThree+=1\n }\n // console.log(timesOfTwo, timesOfThree)\n if(temp==1&×OfTwo<=timesOfThree){\n return timesOfThree*2 - timesOfTwo\n }\n else return -1\n}"}, {"source_code": "var n = readline();\nvar map = [];\nfor (var i = 0; i1e18)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tanswer++;\n\t}\n\tif(flag==0)\n\t{\n\t\tprint(-1);\n\t}\n}\n"}, {"source_code": "function solve() {\n var n = Number(read());\n var c2 = 0;\n var c3 = 0;\n while (n % 2 === 0) {\n n /= 2;\n c2++;\n }\n while (n % 3 === 0) {\n n /= 3;\n c3++;\n }\n if (n !== 1) {\n write(-1);\n return;\n }\n if (c2 > c3) {\n write(-1);\n } else {\n write(c3 * 2 - c2);\n }\n}\n\nfunction init() {\n var T;\n T = 1;\n T = Number(read());\n for (var t = 0; t < T; t++) {\n solve();\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n \n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n \n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n init();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', init);\n }\n} else {\n init();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n function solve(x, moves) {\n console.log(x);\n if (x === 1) { return moves; }\n else if (x%2 === 1) { return solve(2*x, moves+1); }\n else if (x%6 === 0) { return solve(Math.floor(x/6), moves+1); }\n else { return -1; }\n }\n const testCases = parseInt(readline());\n for (var i=0; i readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const s = 'R' + getLine() + 'R'\n const n = s.length\n let last = 0\n let ans = 0\n for (let i = 1; i < n; ++i) {\n if (s[i] === 'R') {\n ans = Math.max(ans, i - last)\n last = i\n }\n }\n print(ans)\n }\n}"}, {"source_code": "var t = Number(readline());\nfor (var k=0;km){m=r;}\n r=1;\n }\n else{\n r++;\n }\n }\n print((r>m)?r:m);\n}\n"}, {"source_code": "Main();\nfunction myout(t){print(t);}//standard output\nfunction next(){return readline();}\nfunction nextInt(){return myconv(next(),1);}\nfunction nextStrArray(){return myconv(next(),2);}//半角スペース分割\nfunction nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化\nfunction nextCharArray(){return myconv(next(),6);}//1文字分割\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す\n//6:1文字に分割 7:1文字に分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\n//atcoderのサンプルは最後に改行入れること\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map((a)=>Number(a));case 6:return i.split(\"\");case 7:return i.split(\"\").map((a)=>Number(a));case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main() {\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var s = nextCharArray();\n var len = s.length;\n var max = 0;//renzokuLnoMax + 1\n var count = 0;\n for(var j = 0; j < len; j++){\n if(s[j] == \"L\"){\n count++;\n }else{\n max = Math.max(max,count + 1);\n count = 0;\n }\n }\n \tmax = Math.max(max,count + 1);\n output[i] = max;\n }\n myout(myconv(output,9));\n}\n"}, {"source_code": "var t = parseInt(readline());\n\nfor (var i = 0; i < t; i++) {\n var s = readline();\n\n var ara = [];\n ara.push(0);\n for (var j = 0; j < s.length; j++) {\n if (s[j] == \"R\") ara.push(j + 1);\n }\n ara.push(s.length + 1);\n\n var max = ara[1] - ara[0];\n for (var j = 0; j < ara.length - 1; j++) {\n var diff = ara[j + 1] - ara[j];\n if (diff > max) max = diff;\n }\n\n print(max);\n}"}, {"source_code": "// Problem Link: https://codeforces.com/contest/1324/problem/C\n// Solution Link: \n\n'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\nconst INF = Math.pow(10, 12);\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n\nlet results = [];\n\nconst getInput = () => {\n const lineInput = readline();\n const testCase = parseInt(lineInput);\n\n for(let i = 0; i < testCase; i++){\n const lineInput = readline() + \"R\";\n results.push(calculateJumpRange(lineInput));\n }\n \n};\n\nconst isPossible = (moveSequence, jumpRange) => {\n let currentPos = -1\n while(currentPos < moveSequence.length - 1){\n let nextPos = -1;\n for(let i = currentPos + 1; i < Math.min(currentPos + jumpRange + 1, moveSequence.length); i++){\n if(moveSequence[i] === \"R\"){\n nextPos = i;\n break;\n }\n }\n\n if(nextPos === -1)\n return false;\n currentPos = nextPos;\n }\n\n return true;\n}\n\nconst calculateJumpRange = (moveSequence) => {\n \n let low = 1, high = moveSequence.length + 1;\n let len = high;\n while(low <= high) {\n let mid = Math.floor((low + high) / 2);\n\n if(isPossible(moveSequence, mid))\n len = mid, high = mid - 1;\n else\n low = mid + 1;\n } \n\n return len;\n}\n\nfunction main() {\n getInput();\n for(let r of results)\n console.log(r);\n}"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nlet arr = ''\nlet ptr = 0\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main(arr)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a) {\n return parseInt(a[ptr++])\n}\n\nfunction readString(a) {\n return a[ptr++]\n}\n\nfunction readStrings(a) {\n return a[ptr++].split(' ')\n}\n\nfunction readInts(a) {\n return a[ptr++].split(' ').map(a => parseInt(a))\n}\n\nfunction main(input) {\n let t = readInt(input)\n while(t--) {\n let s = readString(input) + 'R'\n let min = -Infinity\n let count = 0\n const length = s.length\n for(let i = 0; i < length; i++) {\n // console.log(i, count, min)\n if(s[i] === 'L') count++\n else {\n min = min < count + 1 ? count + 1 : min\n count = 0\n }\n }\n wr(min)\n }\n}"}, {"source_code": "const readline = require('readline')\nconst rl = readline.createInterface(process.stdin, process.stdout)\n\nconst input = []\n\nrl.on('line', line => input.push(line.toString()))\n\nrl.on('close', () => {\n solve()\n})\n\nconst solve = () => {\n const t = Number(input[0])\n\n for (let testCase = 1; testCase <= t; testCase++) {\n const s = 'R' + input[testCase] + 'R'\n\n const arr = s\n .split('')\n .map((char, index) => (char === 'R' ? index : -1))\n .filter(num => ~num)\n\n d = 0\n\n for (let i = 1; i < arr.length; i++) {\n d = Math.max(d, arr[i] - arr[i - 1])\n }\n\n console.log(d)\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8')\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', input => { inputString += input })\nprocess.stdin.on('end', _ => { inputString = inputString.trim().split('\\n').map(str => str.trim()); main() })\nconst readline = () => { return inputString[currentLine++] }\n\n\nfunction main(){\n\tlet tests = parseInt(readline());\n\twhile(tests--){\n\t\tlet path = readline();\n\t\tlet cntL = 0;\n\t\tlet mx = 0;\n\t\tfor(let i = 0; i < path.length; i++){\n\t\t\tlet char = path[i];\n\t\t\tif(char == 'R'){\n\t\t\t\tcntL = 0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcntL++;\n\t\t\t\tmx = Math.max(mx, cntL);\n\t\t\t}\n\t\t}\n\t\tconsole.log(mx + 1);\n\t}\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8')\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', input => { inputString += input })\nprocess.stdin.on('end', _ => { inputString = inputString.trim().split('\\n').map(str => str.trim()); main() })\nconst readline = () => { return inputString[currentLine++] }\n\n\nfunction main(){\n\tlet tests = parseInt(readline());\n\twhile(tests--){\n\t\tlet path = readline();\n\t\tlet cntL = 0;\n\t\tlet mx = 0;\n\t\t[...path].forEach(char => {\n\t\t\tif(char == 'R'){\n\t\t\t\tcntL = 0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcntL++;\n\t\t\t\tmx = Math.max(mx, cntL);\n\t\t\t}\n\t\t});\n\t\tconsole.log(mx + 1);\n\t}\n}\n"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){return Math.max(...this)},Array.prototype.min=function(){return Math.min(...this)},Array.prototype.sum=function(){let t=0;for(let e=0;e{if(l)return s=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),void o.default.writeFileSync(\"output.txt\",a);process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{u+=t})),process.stdin.on(\"end\",(e=>{s=u.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(a)}))};function f(){return s[i++]}function p(){return f().split(\" \").map((t=>parseFloat(t)))}function d(){return f().split(\"\")}e.default={runMain:c,runEachTest:t=>{c((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:f,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r0;)\"R\"==t[e-1]?r=1:(r++,r>n&&(n=r)),e--;o.default.puts(n)}))},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}], "negative_code": [{"source_code": "var t = parseInt(readline());\n\nfor (var i = 0; i < t; i++) {\n var s = readline();\n\n var ara = [];\n ara.push(0);\n for (var i = 0; i < s.length; i++) {\n if (s[i] == \"R\") ara.push(i + 1);\n }\n ara.push(s.length + 1);\n\n var max = ara[1] - ara[0];\n for (var j = 0; j < ara.length - 1; j++) {\n var diff = ara[j + 1] - ara[j];\n if (diff > max) max = diff;\n }\n\n print(max);\n}"}, {"source_code": "var t = parseInt(readline());\n\nfor (var i = 0; i < t; i++) {\n var s = readline();\n\n var ara = [];\n ara.push(0);\n for (var i = 0; i < s.length; i++) {\n if (s[i] == \"R\") ara.push(i + 1);\n }\n ara.push(s.length + 1);\n\n var max = ara[1] - ara[0];\n for (var i = 0; i < ara.length - 1; i++) {\n var diff = ara[i + 1] - ara[i];\n if (diff > max) max = diff;\n }\n\n print(max);\n}"}, {"source_code": "const readline = require('readline')\nconst rl = readline.createInterface(process.stdin, process.stdout)\n\nconst input = []\n\nrl.on('line', line => input.push(line.toString()))\n\nrl.on('close', () => {\n solve()\n})\n\nconst binarySearch = s => {\n const isFeasible = maxStep => {\n let visited = Array(s.length + 1).fill(false)\n\n const dfs = u => {\n visited[u] = true\n\n if (s[u] === 'R') {\n for (let step = 1; step <= maxStep; step++) {\n const v = u + step\n\n if (v < s.length && v >= 0 && !visited[v]) {\n dfs(v)\n }\n }\n }\n }\n\n dfs(0)\n return visited[s.length]\n }\n\n let low = 0\n let high = s.length\n let d = -1\n\n while (low <= high) {\n const mid = Math.floor((low + high) / 2)\n\n if (isFeasible(mid)) {\n d = mid\n high = mid - 1\n } else {\n low = mid + 1\n }\n }\n\n return d\n}\n\nconst solve = () => {\n const t = Number(input[0])\n\n for (let testCase = 1; testCase <= t; testCase++) {\n const s = input[testCase]\n const d = binarySearch('R' + s)\n console.log(d)\n }\n}\n"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){return Math.max(...this)},Array.prototype.min=function(){return Math.min(...this)},Array.prototype.sum=function(){let t=0;for(let e=0;e{if(a)return s=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),void o.default.writeFileSync(\"output.txt\",l);process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{u+=t})),process.stdin.on(\"end\",(e=>{s=u.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return s[i++]}function p(){return f().split(\" \").map((t=>parseFloat(t)))}function d(){return f().split(\"\")}e.default={runMain:c,runEachTest:t=>{c((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:f,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;r0;)\"R\"==t[e-1]?r=1:(console.log(e),console.log(t),r++,r>n&&(n=r)),e--;o.default.puts(n)}))},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}], "src_uid": "6451507b21854d5b81aeaf0491ddf584"} {"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 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — 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 — 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": "function intersection (a, b) {\n\tfor (var i = 0, _i = a.length; i < _i; i++)\n\t\tif (b.indexOf(a[i]) !== -1) return true;\n\treturn false;\n}\n\nfunction merge (a, b) {\n\tfor (var i = 0, _i = a.length; i < _i; i++)\n\t\tif (b.indexOf(a[i]) === -1) b.push(a[i]);\n\treturn b;\n}\n\n;(function () {\n\n\tprint((function (n, m) {\n\n\t\tfor (var i = 0, a = []; i <= m; i++) a[i] = [];\n\n\t\tfor (var i = 0; i < n; i++) {\n\t\t\tvar s = readline();\n\t\t\tif (s[0] == '0') a[0].push(i);\n\t\t\telse for (var j = 1, s = s.split(' '), _j = s.length; j < _j; j++) a[+s[j]].push(i);\n\t\t}\n\n\t\tvar sub = a[0].length;\n\t\ta.shift(0);\n\n\t\ta = a.filter(function (e) { return e.length; });\n\n\t\tvar flag = true;\n\t\twhile (flag) {\n\t\t\tflag = false;\n\t\t\tfor (var i = 0, _i = a.length; i < _i; i++) {\n\t\t\t\tfor (var j = 0; j < _i; j++)\n\t\t\t\t\tif (i !== j && intersection(a[i], a[j])) {\n\t\t\t\t\t\ta[i] = merge(a[i], a[j]);\n\t\t\t\t\t\ta.splice(j, 1);\n\t\t\t\t\t\tflag = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tif (flag) break;\n\t\t\t}\n\t\t}\n\n\t\treturn sub + a.length - !!a.length;\n\n\t}).apply(this, readline().split(' ').map(Number)));\n\n}).call(this);"}, {"source_code": "const readline = require('readline');\nconst fs = require('fs');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n // input: fs.createReadStream('src/0.input1.json'),\n output: process.stdout,\n terminal: false,\n});\n\nlet lines = [];\n\n/**\n * Time complexity:\n * Space complexity:\n */\nrl.on('line', function (line) {\n lines.push(line.trim().split(' ').map(Number));\n}).on('close', () => {\n const n = lines[0][0];\n const graph = {};\n\n let noOneKnow = true;\n // cover edge case, no one know any language\n for (let i = 1; i <= n; i++) {\n if (lines[i][0] > 0) {\n noOneKnow = false;\n }\n }\n if (noOneKnow) {\n console.log(n);\n return;\n }\n\n for (let i = 1; i < lines.length; i++) {\n lines[i].shift();\n graph[`${i}E`] = (graph[`${i}E`] || []).concat(lines[i]);\n for (let j = 0; j < lines[i].length; j++) {\n graph[lines[i][j]] = (graph[lines[i][j]] || []).concat(`${i}E`);\n }\n }\n\n const visited = {};\n for (let v in graph) {\n visited[v] = false;\n }\n\n const bfs = (s, graph) => {\n const queue = [s];\n\n while (queue.length > 0) {\n const u = queue.shift();\n for (let i = 0; i < graph[u].length; i++) {\n const v = graph[u][i];\n if (!visited[v]) {\n visited[v] = true;\n queue.push(v);\n }\n }\n }\n };\n\n let count = 0;\n for (let i = 1; i <= n; i++) {\n if (!visited[`${i}E`]) {\n count++;\n bfs(`${i}E`, graph);\n }\n }\n\n console.log(count - 1);\n});\n"}], "negative_code": [{"source_code": "function intersection (a, b) {\n\tfor (var i = 0, _i = a.length; i < _i; i++)\n\t\tif (b.indexOf(a[i]) !== -1) return true;\n\treturn false;\n}\n\nfunction merge (a, b) {\n\tfor (var i = 0, _i = a.length; i < _i; i++)\n\t\tif (b.indexOf(a[i]) === -1) b.push(a[i]);\n\treturn b;\n}\n\n;(function () {\n\n\tprint((function (n, m) {\n\n\t\tfor (var i = 0, a = []; i <= m; i++) a[i] = [];\n\n\t\tfor (var i = 0; i < n; i++) {\n\t\t\tvar s = readline().split(' ');\n\t\t\tif (s[0] === '0') a[0].push(i);\n\t\t\telse for (var j = 1, _j = s.length; j < _j; j++) a[+s[j]].push(i);\n\t\t}\n\n\t\tvar sub = a[0].length;\n\t\ta[0] = false;\n\n\t\tvar flag = true;\n\t\twhile (flag) {\n\t\t\tflag = false;\n\t\t\tfor (var i = 1, _i = a.length; i < _i; i++) {\n\t\t\t\tif (intersection(a[i - 1], a[i])) {\n\t\t\t\t\ta[i] = merge(a[i], a[i - 1]);\n\t\t\t\t\ta[i - 1] = false;\n\t\t\t\t\tflag = true;\n\t\t\t\t\ta = a.filter(function (e) { return e !== false; });\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ta = a.filter(function (e) { return e.length; });\n\n\t\treturn sub + a.length - 1;\n\n\t}).apply(this, readline().split(' ').map(Number)));\n\n}).call(this);"}, {"source_code": "function intersection (a, b) {\n\tfor (var i = 0, _i = a.length; i < _i; i++)\n\t\tif (b.indexOf(a[i]) !== -1) return true;\n\treturn false;\n}\n\nfunction merge (a, b) {\n\tfor (var i = 0, _i = a.length; i < _i; i++)\n\t\tif (b.indexOf(a[i]) === -1) b.push(a[i]);\n\treturn b;\n}\n\n;(function () {\n\n\tprint((function (n, m) {\n\n\t\tfor (var i = 0, a = []; i <= m; i++) a[i] = [];\n\n\t\tfor (var i = 0; i < n; i++) {\n\t\t\tvar s = readline().split(' ');\n\t\t\tif (s[0] === '0') a[0].push(i);\n\t\t\telse for (var j = 1, _j = s.length; j < _j; j++) a[+s[j]].push(i);\n\t\t}\n\n\t\tvar sub = a[0].length;\n\t\ta[0] = false;\n\n\t\tvar flag = true;\n\t\twhile (flag) {\n\t\t\tflag = false;\n\t\t\tfor (var i = 1, _i = a.length; i < _i; i++) {\n\t\t\t\tif (intersection(a[i - 1], a[i])) {\n\t\t\t\t\ta[i] = merge(a[i], a[i - 1]);\n\t\t\t\t\ta[i - 1] = false;\n\t\t\t\t\tflag = true;\n\t\t\t\t\ta = a.filter(function (e) { return e !== false; });\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ta = a.filter(function (e) { return e.length; });\n\n\t\treturn sub + a.length - !!a.length;\n\n\t}).apply(this, readline().split(' ').map(Number)));\n\n}).call(this);"}, {"source_code": "const readline = require('readline');\nconst fs = require('fs');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n // input: fs.createReadStream('src/0.input1.json'),\n output: process.stdout,\n terminal: false,\n});\n\nlet lines = [];\n\nconst calculate = (arr) => {\n const sortedArr = arr.map((value, idx) => ({ value, idx: idx + 1 })).sort((a, b) => a.value - b.value);\n\n const result = [];\n const originalSorted = [sortedArr[0].idx];\n\n for (let i = 0; i < sortedArr.length - 1; i++) {\n originalSorted.push(sortedArr[i + 1].idx);\n if (sortedArr[i].value === sortedArr[i + 1].value) {\n const newArr = [];\n // clone a new arr\n for (let j = 0; j < sortedArr.length; j++) {\n if (j !== i) {\n newArr.push(sortedArr[j].idx);\n } else {\n newArr.push(sortedArr[j + 1].idx);\n newArr.push(sortedArr[j].idx);\n j++;\n }\n }\n result.push(newArr);\n }\n }\n\n result.push(originalSorted);\n return result;\n};\n\n/**\n * Time complexity:\n * Space complexity:\n */\nrl.on('line', function (line) {\n lines.push(line.trim().split(' ').map(Number));\n}).on('close', () => {\n const arr = lines[1];\n\n if (arr.length < 3) {\n console.log('NO');\n }\n\n const result = calculate(arr);\n\n if (result && result.length >= 3) {\n console.log('YES');\n result.forEach((item) => console.log(item.join(' ')));\n } else {\n console.log('NO');\n }\n});\n"}], "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 — 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": "const predicate = (x, y, a, b, n) => {\r\n try {\r\n let l = -1; let h = n + 1;\r\n\r\n while (h - l > 1) {\r\n const mid = Math.ceil((l + h) / 2);\r\n\r\n // p+ q = n\r\n const p = mid;\r\n const q = n - mid;\r\n const t1 = p * a + q * b;\r\n const t2 = p * b + q * a;\r\n\r\n if (t1 <= x && t2 <= y) {\r\n return true;\r\n }\r\n\r\n if (t1 > x) {\r\n if (a > b) {\r\n h = mid;\r\n } else {\r\n l = mid;\r\n }\r\n } else if (a > b) {\r\n l = mid;\r\n } else {\r\n h = mid;\r\n }\r\n }\r\n return false;\r\n } catch (ex) {\r\n console.log('predicate ex:', ex);\r\n }\r\n};\r\n\r\nconst giftSet = ([x, y, a, b]) => {\r\n try {\r\n let low = -1; let high = 1000000001;\r\n let ans = 0;\r\n\r\n\r\n while (high - low > 1) {\r\n const mid = Math.ceil((low + high) / 2);\r\n\r\n if (predicate(x, y, a, b, mid)) {\r\n ans = mid;\r\n low = mid;\r\n } else {\r\n high = mid;\r\n }\r\n }\r\n // console.log('ans:', ans);\r\n return ans;\r\n } catch (ex) {\r\n console.log('ex:', ex);\r\n }\r\n};\r\n\r\n\r\nvar readline = require('readline');\r\n\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvar lines = [];\r\nrl.on('line', function(input) {\r\n lines.push(input);\r\n});\r\nrl.on('close', function() {\r\n var t = parseInt(lines[0]);\r\n var l = 1;\r\n for (var i = 0; i < t; i++) {\r\n console.log(giftSet(lines[l++].split(' ').map(Number)));\r\n }\r\n});\r\n\r\n\r\n"}], "negative_code": [], "src_uid": "e6eb839ef4e688796050b34f1ca599a5"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$m$$$ and an array $$$a$$$ of $$$n$$$ integers. For each $$$1 \\le i \\le n$$$ it holds that $$$1 \\le a_i \\le m$$$.Your task is to count the number of different arrays $$$b$$$ of length $$$n$$$ such that: $$$1 \\le b_i \\le m$$$ for each $$$1 \\le i \\le n$$$, and $$$\\gcd(b_1,b_2,b_3,...,b_i) = a_i$$$ for each $$$1 \\le i \\le n$$$. Here $$$\\gcd(a_1,a_2,\\dots,a_i)$$$ denotes the greatest common divisor (GCD) of integers $$$a_1,a_2,\\ldots,a_i$$$.Since this number can be too large, print it modulo $$$998\\,244\\,353$$$.", "input_spec": "Each test consist of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m \\le 10^9$$$) — the length of the array $$$a$$$ and the maximum possible value of the element. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le m$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer — the number of different arrays satisfying the conditions above. Since this number can be large, print it modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["5\n\n3 5\n\n4 2 1\n\n2 1\n\n1 1\n\n5 50\n\n2 3 5 2 3\n\n4 1000000000\n\n60 30 1 1\n\n2 1000000000\n\n1000000000 2"], "sample_outputs": ["3\n1\n0\n595458194\n200000000"], "notes": "NoteIn the first test case, the possible arrays $$$b$$$ are: $$$[4,2,1]$$$; $$$[4,2,3]$$$; $$$[4,2,5]$$$. In the second test case, the only array satisfying the demands is $$$[1,1]$$$.In the third test case, it can be proven no such array exists."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const [n, m] = rns(),\r\n a = rns();\r\n let res = 1;\r\n for (let i = 1; i < n; i++) {\r\n if (a[i - 1] % a[i] !== 0) return 0;\r\n if (a[i - 1] === 1) {\r\n res = mul(res, m);\r\n } else {\r\n let b = Math.floor(m / a[i]),\r\n c = calc(b, a[i - 1] / a[i]);\r\n res = mul(res, c);\r\n }\r\n }\r\n return res;\r\n}\r\nfunction calc(a, b) {\r\n if (b === 1) return a;\r\n const p = [];\r\n for (let i = 2; i <= b / i; i++) {\r\n if (b % i === 0) {\r\n p.push(i);\r\n while (b % i === 0) {\r\n b /= i;\r\n }\r\n }\r\n }\r\n if (b > 1) p.push(b);\r\n let res = 0;\r\n for (let i = 1; i < 1 << p.length; i++) {\r\n let cnt = 0,\r\n ans = 1;\r\n for (let j = 0; j < p.length; j++) {\r\n if (i & 1 << j) {\r\n cnt++;\r\n ans *= p[j];\r\n }\r\n }\r\n if (cnt & 1) {\r\n res += Math.floor(a / ans);\r\n } else {\r\n res -= Math.floor(a / ans);\r\n }\r\n }\r\n return a - res;\r\n}\r\nconst MOD = 998244353;\r\nfunction mul(...args) {\r\n if (args.length === 0) throw new Error('参数不能为空');\r\n if (args.length === 1) return args[0];\r\n const [a, b] = args;\r\n if (args.length > 2) return mul(mul(a, b), ...args.slice(2));\r\n return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n let s = solve(r);\r\n if (s === undefined) s = '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "116dd636a4f2547aef01a68f98c46ca2"} {"nl": {"description": "You are given four integer values $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$.Check if there exists a string that contains: $$$a$$$ letters 'A'; $$$b$$$ letters 'B'; $$$c$$$ letters 'C'; no other letters; exactly $$$m$$$ pairs of adjacent equal letters (exactly $$$m$$$ such positions $$$i$$$ that the $$$i$$$-th letter is equal to the $$$(i+1)$$$-th one). ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of testcases. Each of the next $$$t$$$ lines contains the description of the testcase — four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$ ($$$1 \\le a, b, c \\le 10^8$$$; $$$0 \\le m \\le 10^8$$$).", "output_spec": "For each testcase print \"YES\" if there exists a string that satisfies all the requirements. Print \"NO\" if there are no such strings. 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\n2 2 1 0\n1 1 1 1\n1 2 3 2"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteIn the first testcase strings \"ABCAB\" or \"BCABA\" satisfy the requirements. There exist other possible strings.In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice.In the third testcase string \"CABBCC\" satisfies the requirements. There exist other possible strings."}, "positive_code": [{"source_code": "/* Common Template Starts */\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n\t return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n/* Common Template Ends */\r\nfunction main() {\r\n let Q = +(readline()); // Read Input\r\n\r\n for (let i = 0; i < Q; i++) {\r\n const N = readline();\r\n\r\n const [a, b, c, m] = N.split(\" \").map((n) => parseInt(n));\r\n const sorted = [a, b, c].sort((a, b) => a - b);\r\n\r\n const max = (a-1) + (b-1) + (c-1);\r\n const min = (sorted[2] - 1) - (sorted[0] + sorted[1]); \r\n //console.log(\"min max\", min, max);\r\n \r\n if (m >= min && m <= max) {\r\n console.log(\"YES\");\r\n } else {\r\n console.log(\"NO\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\n\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [a, b, c, m] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let max = a + b + c - 3;\r\n let arr = [a, b, c];\r\n let min;\r\n arr.sort((a, b) => b - a);\r\n let n = a + b + c;\r\n if (2 * (arr[1] + arr[2]) >= n) min = 0;\r\n else min = n - 2 * (arr[1] + arr[2]) - 1;\r\n if (m >= min && m <= max) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "function readStringArray() {\r\n return readline().split(\" \");\r\n }\r\n function readNumArray() {\r\n return readStringArray().map(Number);\r\n }\r\n \r\n function main() {\r\n var testCasesNum = +readline();\r\n for (var i = 0; i < testCasesNum; i++) {\r\n var abcm = readNumArray();\r\n var a = abcm[0];\r\n var b = abcm[1];\r\n var c = abcm[2];\r\n var m = abcm[3];\r\n var max = Math.max(a, b, c);\r\n var minPairs = max - (a + b + c - max) - 1;\r\n if (m > a - 1 + b - 1 + c - 1 || m < minPairs) {\r\n print('NO');\r\n continue;\r\n }\r\n \r\n print('YES');\r\n }\r\n }\r\n \r\n main();"}], "negative_code": [{"source_code": "/* Common Template Starts */\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n\t return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n/* Common Template Ends */\r\nfunction main() {\r\n let Q = +(readline()); // Read Input\r\n\r\n for (let i = 0; i < Q; i++) {\r\n const N = readline();\r\n\r\n const [a, b, c, m] = N.split(\" \").map((n) => parseInt(n));\r\n const sorted = [a, b, c].sort();\r\n\r\n const max = (a-1) + (b-1) + (c-1);\r\n const min = (sorted[2] - 1) - (sorted[0] + sorted[1]); \r\n //console.log(\"min max\", min, max);\r\n \r\n if (m >= min && m <= max) {\r\n console.log(\"YES\");\r\n } else {\r\n console.log(\"NO\");\r\n }\r\n }\r\n}\r\n"}], "src_uid": "fc547fc83ebbcc3c058a069ef9fef62c"} {"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 ≤ n ≤ 5000) — 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 ≤ ai ≤ bi ≤ 366), 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, 128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140."}, "positive_code": [{"source_code": "var n = +readline();\nvar arr = [];\nfor(var i=0;i -1;\n}\n\nfor (var i = 0; i < n; i++) {\n\tavail[i] = readline().split(' ');\n\n\tif (isInArray(avail[i][1], days) === false) {\n\t\tdays.push(avail[i][1]);\n\t}\n\tif (isInArray(avail[i][2], days) === false) {\n\t\tdays.push(avail[i][2]);\n\t}\n}\n\n//sorting the days\ndays.sort(function(a, b) {return a - b});\n\nvar count_M = 0;\nvar count_F = 0;\nvar guests = 0;\nvar max_guests = 0;\n\n// each iteration in this loop is a new day\nfor (var i = 0; i < days.length; i++) {\n\n\t// setting counters back to 0 each new day\n\tcount_M = 0;\n\tcount_F = 0;\n\n\t// each iteration in this loop is a new person --> checking every person on each day\n\tfor (var j = 0; j < n; j++) {\n\t\t// checking availability of each person\n\t\tif (Number(days[i]) >= Number(avail[j][1]) && Number(days[i]) <= Number(avail[j][2])) {\n\t\t\t//for each person available that day check if male or female and add counter\n\t\t\tif (avail[j][0] == 'M') {\n\t\t\t\tcount_M += 1;\n\t\t\t} else {\n\t\t\t\tcount_F += 1;\n\t\t\t}\n\t\t}\n\t}\n\t// determining number of Female + Male pairs (*2 to get # of people)\n\tguests = Math.min(count_M, count_F) * 2;\n\tif (guests > max_guests) {\n\t\tmax_guests = guests;\n\t}\n}\n\nprint(max_guests);\n\n\n"}, {"source_code": "'use strict';\n\nconst n = Number(readline());\nlet dates = Array(400).fill(0);\n\nfor (let i = 0; i < n; i++) {\n const line = readline().split(' ')\n\n for (let j = Number(line[1]); j < Number(line[2])+1; j++) {\n dates[j] += line[0] === 'M' ? 1 : 10000;\n }\n}\n\nlet _dates = [...new Set(dates)]\n\nlet result = 0;\nwhile (_dates.length !== 0) {\n let _result = _dates.pop(); \n result = Math.max(result, Math.min(_result/10000|0, _result%10000));\n}\n\nprint(result * 2);\n"}, {"source_code": "var n = Number(readline());\nvar sex = new Array(n);\nvar l = new Array(n);\nvar r = new Array(n);\nfor (var i = 0; i < n; ++i) {\n var str = readline().split(\" \", 3);\n sex[i] = str[0];\n l[i] = Number(str[1]);\n r[i] = Number(str[2]);\n}\n\nvar ans = 0;\nfor (var i = 1; i <= 366; ++i) {\n var a = 0, b = 0;\n for (var j = 0; j < n; ++j) {\n if (l[j] <= i && r[j] >= i) {\n if (sex[j] == \"M\") {\n ++a;\n } else {\n ++b;\n }\n }\n }\n ans = Math.max(ans, Math.min(a, b) * 2);\n}\nprint(ans);"}, {"source_code": "var readInt = () => parseInt(readline())\nvar readIntArray = () => readline().split(' ').forEach(item => parseInt(item))\nArray.prototype.fill = function(value) {\n for (var i = 0; i < this.length; i++)\n this[i] = value\n return this\n}\n\nvar N = readInt()\nvar boys = (new Array(366)).fill(0)\nvar girls = new Array(366).fill(0)\n\nfor (var i = 0; i < N; i++) {\n var f = readline().split(' ')\n var a = (f[0] === 'M' ? boys : girls)\n\n for (var n = parseInt(f[2]), j = parseInt(f[1])-1; j < n; j++) {\n a[j] += 1\n }\n}\nvar ans = 0\nfor (var i = 0; i < 366; i++) {\n ans = Math.max(ans, 2*Math.min(boys[i], girls[i]))\n}\nprint(ans)"}], "negative_code": [{"source_code": "var n = +readline();\nvar arr = [];\nfor(var i=0;i= i) {\n if (sex[j] == \"M\") {\n ++a;\n } else {\n ++b;\n }\n }\n }\n ans = Math.max(ans, Math.min(a, b));\n}\nprint(ans);"}], "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 — 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 — to allocate n bytes of the memory and return the allocated block's identifier x; erase x — to erase the block with the identifier x; defragment — 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 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), 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": "var l = readline().split(' ')\nvar i, j\nvar t = l[0]\nvar mt = l[1]\nvar m = []\nvar b = []\nvar bn = 0\nvar r\n\nfor (i = 0; i < mt; i++) m[i] = 0\n\nfor (i = 0; i < t; i++) {\n l = readline().split(' ')\n var op = l[0]\n var n = l[1]\n if (op == 'alloc') {\n print(r = alloc(n))\n } else if (op == 'erase') {\n r = erase(n)\n if (r) print(r)\n } else if (op == 'defragment') {\n defragment()\n }\n}\n\nfunction alloc (n) {\n var i, j = 0\n for (i = 0; i < mt; i++) {\n if (!m[i]) {\n j++\n if (j == n) {\n b[++bn] = [i - j + 1, i]\n while (j > 0) {\n m[i - j + 1] = 1\n j--\n }\n return bn\n }\n } else {j = 0}\n }\n return 'NULL'\n}\n\nfunction erase (n) {\n if (b[n]) {\n for (var i = b[n][0]; i <= b[n][1]; i++) m[i] = 0\n b[n] = null\n } else {\n return 'ILLEGAL_ERASE_ARGUMENT'\n }\n}\n\nfunction defragment () {\n var j = 0\n for (var i = 0; i < mt; i++) {\n if (!m[i]) {j++}\n else if (j) {\n var mmb\n for (var t = 0; t <= bn; t++) {\n if (b[t] && b[t][0] == i) {\n mmb = b[t]\n break\n }\n }\n for (var k = mmb[0]; k <= mmb[1]; k++) {\n m[k] = 0\n m[k - j] = 1\n }\n mmb[0] -= j\n mmb[1] -= j\n j = 0\n }\n }\n}"}, {"source_code": "var a = readline().split(' ').map(function (e){\n\treturn parseInt(e);\n});\nvar n = a[0], m = a[1];\nvar mem = [{\n\t'id': NaN,\n\t'begin': 0,\n\t'end': 0\n}], cnt = 0;\nfunction alloc(i, len) {\n\tmem.splice(i, 0, {\n\t\t'id': ++cnt,\n \t'begin': mem[i - 1].end + 1,\n \t'end': mem[i - 1].end + len,\n });\n print(cnt);\n}\nfor (var i = 0; i < n; ++i) {\n\ta = readline().split(' ');\n\tswitch (a[0]) {\n \tcase 'alloc': {\n \t\tvar find = false;\n \tvar len = parseInt(a[1]);\n \tfor (var j = 0; j < mem.length - 1; ++j) {\n \t if (mem[j + 1].begin - 1 - mem[j].end >= len) {\n \talloc(j + 1, len);\n \tfind = true; break;\n }\n } \n if (!find) {\n \tif (m - mem[mem.length - 1].end >= len) {\n\t \talloc(mem.length, len);\n\t } else {\n print('NULL');\n }\n }\n } break;\n case 'erase': {\n \tvar id = parseInt(a[1]);\n \tvar find = false;\n \tfor (var j = 0; j < mem.length; ++j) {\n \tif (mem[j]['id'] === id) {\n \tmem.splice(j, 1);\n \tfind = true; break;\n }\n }\n if (!find) {\n \tprint('ILLEGAL_ERASE_ARGUMENT');\n }\n } break;\n case 'defragment': {\n \tfor (var j = 1; j < mem.length; ++j) {\n \t\tvar len = mem[j].end - mem[j].begin;\n \tmem[j].begin = mem[j - 1].end + 1 || 1;\n \tmem[j].end = mem[j].begin + len;\n }\n } break;\n }\n}\n"}, {"source_code": "var s = readline().split( ' ' ),\n size = s[1] - '';\n\nvar mem = [];\n\nfor (; s = readline(); ) {\n switch (s.charAt( 0 )) {\n case 'a': alloc( s.replace( 'alloc ', '' ) - '' ); break;\n case 'e': erase( s.replace( 'erase ', '' ) - '' ); break;\n default: defragment();\n }\n}\n\nfunction alloc(x) {\n var next = alloc._ = alloc._ || 1;\n for (var i=1, j=0; i 0) {\n m[i - j + 1] = 1\n j--\n }\n return bn\n }\n } else {j = 0}\n }\n return 'NULL'\n}\n\nfunction erase (n) {\n if (b[n]) {\n for (var i = b[n][0]; i <= b[n][1]; i++) m[i] = 0\n b[n] = null\n } else {\n return 'ILLEGAL_ERASE_ARGUMENT'\n }\n}\n\nfunction defragment () {\n var j = 0\n for (var i = 0; i < mt; i++) {\n if (!m[i]) {j++}\n else if (j) {\n var mmb\n for (var t = 0; t <= bn; t++) {\n if (b[t] && b[t][0] == i) {\n mmb = b[t]\n break\n }\n }\n for (var k = mmb[0]; k < mmb[1]; k++) {\n m[k] = 0\n m[k - j] = 1\n }\n mmb[0] -= j\n mmb[1] -= j\n j = 0\n }\n }\n}"}, {"source_code": "var a = readline().split(' ').map(function (e){\n\treturn parseInt(e);\n});\nvar n = a[0], m = a[1];\nvar mem = [{\n\t'id': NaN,\n\t'begin': 0,\n\t'end': 0\n}], cnt = 0;\nfunction alloc(i, len) {\n\tmem.splice(i, 0, {\n\t\t'id': ++cnt,\n \t'begin': mem[i - 1].end + 1,\n \t'end': mem[i - 1].end + len,\n });\n print(cnt);\n}\nfor (var i = 0; i < n; ++i) {\n\ta = readline().split(' ');\n\tswitch (a[0]) {\n \tcase 'alloc': {\n \t\tvar find = false;\n \tvar len = parseInt(a[1]);\n \tfor (var j = 0; j < mem.length - 1; ++j) {\n \t if (mem[j + 1].begin - mem[j].end > len) {\n \talloc(j + 1, len);\n \tfind = true; break;\n }\n } \n if (m - mem[mem.length - 1].end >= len) {\n \talloc(mem.length, len);\n \tfind = true;\n }\n if (!find) {\n \tprint('NULL');\n }\n } break;\n case 'erase': {\n \tvar id = parseInt(a[1]);\n \tvar find = false;\n \tfor (var j = 0; j < mem.length; ++j) {\n \tif (mem[j]['id'] === id) {\n \tmem.splice(j, 1);\n \tfind = true; break;\n }\n }\n if (!find) {\n \tprint('ILLEGAL_ERASE_ARGUMENT');\n }\n } break;\n case 'defragment': {\n \tfor (var j = 1; j < mem.length; ++j) {\n \t\tvar len = mem[j].end - mem[j].begin;\n \tmem[j].begin = mem[j - 1].end + 1 || 1;\n \tmem[j].end = mem[j].begin + len;\n }\n } break;\n }\n}\n"}, {"source_code": "var a = readline().split(' ').map(function (e){\n\treturn parseInt(e);\n});\nvar n = a[0], m = a[1];\nvar tot = 0, top = 0;\nvar arr = [null];\nfor (var i = 0; i < n; ++i) {\n\ta = readline().split(' ');\n\tswitch (a[0]) {\n \tcase 'alloc': {\n \tvar len = parseInt(a[1]);\n \tif (top + len <= m && len > 0) {\n \ttot += len; top += len;\n \tprint(arr.length);\n \tarr.push(len);\n \t} else {\n \tprint('NULL');\n }\n } break;\n case 'erase': {\n \tvar id = parseInt(a[1]);\n \tif (!arr[id]) {\n \tprint('ILLEGAL_ERASE_ARGUMENT');\n } else {\n \t tot -= arr[id];\n \tif (id === arr.length - 1) {\n \ttop -= arr.pop();\n } else {\n arr[id] = null;\n }\n }\n } break;\n case 'defragment': {\n \ttop = tot;\n } break;\n }\n}\n"}, {"source_code": "var a = readline().split(' ').map(function (e){\n\treturn parseInt(e);\n});\nvar n = a[0], m = a[1];\nvar tot = 0, top = 0;\nvar arr = [null];\nfor (var i = 0; i < n; ++i) {\n\ta = readline().split(' ');\n\tswitch (a[0]) {\n \tcase 'alloc': {\n \tvar len = parseInt(a[1]);\n \tif (top + len <= m && len > 0) {\n \ttot += len; top += len;\n \tprint(arr.length);\n \tarr.push(len);\n \t} else {\n \tprint('NULL');\n }\n } break;\n case 'erase': {\n \tvar id = parseInt(a[1]);\n \tif (!arr[id]) {\n \tprint('ILLEGAL_ERASE_ARGUMENT');\n } else {\n \t tot -= arr[id];\n \tif (id === arr.length - 1) {\n \ttop -= arr[id];\n }\n arr[id] = null;\n }\n } break;\n case 'defragment': {\n \ttop = tot;\n } break;\n }\n}\n"}, {"source_code": "var a = readline().split(' ').map(function (e){\n\treturn parseInt(e);\n});\nvar n = a[0], m = a[1];\nvar tot = 0, top = 0;\nvar arr = [null];\nfor (var i = 0; i < n; ++i) {\n\ta = readline().split(' ');\n\tswitch (a[0]) {\n \tcase 'alloc': {\n \tvar len = parseInt(a[1]);\n \tif (top + len <= m) {\n \ttot += len; top += len;\n \tprint(arr.length);\n \tarr.push(len);\n \t} else {\n \tprint('NULL');\n }\n } break;\n case 'erase': {\n \tvar id = parseInt(a[1]);\n \tif (!arr[id]) {\n \tprint('ILLEGAL_ERASE_ARGUMENT');\n } else {\n \ttot -= arr[id];\n arr[id] = null;\n }\n } break;\n case 'defragment': {\n \ttop = tot;\n } break;\n }\n}\n"}, {"source_code": "var a = readline().split(' ').map(function (e){\n\treturn parseInt(e);\n});\nvar n = a[0], m = a[1];\nvar mem = [{\n\t'id': NaN,\n\t'begin': 0,\n\t'end': 0\n}], cnt = 0;\nfunction alloc(i, len) {\n\tmem.splice(i, 0, {\n\t\t'id': ++cnt,\n \t'begin': mem[i - 1].end + 1,\n \t'end': mem[i - 1].end + len,\n });\n print(cnt);\n}\nfor (var i = 0; i < n; ++i) {\n\ta = readline().split(' ');\n\tswitch (a[0]) {\n \tcase 'alloc': {\n \t\tvar find = false;\n \tvar len = parseInt(a[1]);\n \tfor (var j = 0; j < mem.length - 1; ++j) {\n \t if (mem[j + 1].begin - mem[j].end > len) {\n \talloc(j + 1, len);\n \tfind = true; break;\n }\n } \n if (m - mem[mem.length - 1].end > len) {\n \talloc(mem.length, len);\n \tfind = true;\n }\n if (!find) {\n \tprint('NULL');\n }\n } break;\n case 'erase': {\n \tvar id = parseInt(a[1]);\n \tvar find = false;\n \tfor (var j = 0; j < mem.length; ++j) {\n \tif (mem[j]['id'] === id) {\n \tmem.splice(j, 1);\n \tfind = true; break;\n }\n }\n if (!find) {\n \tprint('ILLEGAL_ERASE_ARGUMENT');\n }\n } break;\n case 'defragment': {\n \tfor (var j = 1; j < mem.length; ++j) {\n \t\tvar len = mem[j].end - mem[j].begin;\n \tmem[j].begin = mem[j - 1].end + 1 || 1;\n \tmem[j].end = mem[j].begin + len;\n }\n } break;\n }\n}\n"}, {"source_code": "var a = readline().split(' ').map(function (e){\n\treturn parseInt(e);\n});\nvar n = a[0], m = a[1];\nvar tot = 0, top = 0;\nvar arr = [-1];\nfor (var i = 0; i < n; ++i) {\n\ta = readline().split(' ');\n\tswitch (a[0]) {\n \tcase 'alloc': {\n \tvar len = parseInt(a[1]);\n \tif (top + len <= m) {\n \ttot += len; top += len;\n \tprint(arr.length);\n \tarr.push(len);\n \t} else {\n \tprint('NULL');\n }\n } break;\n case 'erase': {\n \tvar id = parseInt(a[1]);\n \tif (!arr[id]) {\n \tprint('ILLEGAL_ERASE_ARGUMENT');\n } else {\n \ttot -= arr[id];\n arr[id] = null;\n }\n } break;\n case 'defragment': {\n \ttop = tot;\n } break;\n }\n}\n"}], "src_uid": "a6cba17c5ddb93f6741e00280fb6c54c"} {"nl": {"description": "You are given a multiset (i. e. a set that can contain multiple equal integers) containing $$$2n$$$ integers. Determine if you can split it into exactly $$$n$$$ pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by $$$2$$$, the remainder is $$$1$$$).", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\\leq t\\leq 100$$$) — 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$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1,a_2,\\dots, a_{2n}$$$ ($$$0\\leq a_i\\leq 100$$$) — the numbers in the set.", "output_spec": "For each test case, print \"Yes\" if it can be split into exactly $$$n$$$ pairs so that the sum of the two elements in each pair is odd, and \"No\" otherwise. You can print each letter in any case.", "sample_inputs": ["5\n2\n2 3 4 5\n3\n2 3 4 5 5 5\n1\n2 4\n1\n2 3\n4\n1 5 3 2 6 7 3 4"], "sample_outputs": ["Yes\nNo\nNo\nYes\nNo"], "notes": "NoteIn the first test case, a possible way of splitting the set is $$$(2,3)$$$, $$$(4,5)$$$.In the second, third and fifth test case, we can prove that there isn't any possible way.In the fourth test case, a possible way of splitting the set is $$$(2,3)$$$."}, "positive_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction print(x) {\r\n console.log(x);\r\n}\r\n\r\nfunction oddSet() {\r\n const n = readline();\r\n const arr = readline().split(' ').map(elem => +elem);\r\n\r\n return (arr.filter(elem => elem % 2 === 0).length === (arr.length >> 1)) ? 'Yes' : 'No';\r\n}\r\n\r\nfunction main() {\r\n const t = +readline();\r\n for (let i = 0; i < t; i++) {\r\n print(oddSet());\r\n }\r\n}\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var e = 0;\n for(var j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j];\n }else{\n var k = lines[j].split(' ').map(Number);\n var odd = 0;\n var even = 0;\n for(var l = 0; l < k.length; l++){\n if(k[l] % 2 == 1){\n odd++;\n }else{\n even++;\n }\n }\n if(odd % e === 0 && odd !== 0 && even % e === 0 && even !== 0){\n console.log('YES');\n }else{\n console.log('NO');\n }\n }\n }\n});"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n if (c % 2 !== 0) {\n c++;\n return;\n }\n\n const numbers = d.split(\" \").map(Number);\n let ans = 0;\n\n for (let i = 0; i < numbers.length; i++) {\n if (numbers[i] % 2) {\n ans++;\n } else {\n ans--;\n }\n }\n\n if (ans === 0) {\n console.log(\"YES\");\n } else {\n console.log(\"NO\");\n }\n\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var e = 0;\n for(var j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j];\n }else{\n var k = lines[j].split(' ').map(Number);\n var odd = 0;\n var even = 0;\n for(var l = 0; l < k.length; l++){\n if(k[l] % 2 == 1){\n odd++;\n }else{\n even++;\n }\n }\n if(odd % e === 0 && odd !== 0 && even % e === 0 && even !== 0){\n console.log('YES');\n }else{\n console.log('NO');\n }\n }\n }\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n solve();\r\n }\r\n}\r\nfunction solve() {\r\n let n = parseInt(readLine());\r\n let arr = readLine().split(\" \");\r\n let even = 0, odd = 0;\r\n for (let i = 0; i < arr.length; i++) {\r\n let num = parseInt(arr[i]);\r\n if (num % 2 == 0) even++;\r\n else odd++;\r\n }\r\n if (even == odd) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n\r\n let t = parseInt(readLine());\r\n while (t--) {\r\n\r\n let n = parseInt(readLine());\r\n let a = readLine().split(\" \").map(x => parseInt(x));\r\n solve(n, a);\r\n\r\n }\r\n}\r\n\r\nfunction solve(n, a) {\r\n let odd = 0, even = 0;\r\n for (let i of a) {\r\n if (i % 2) odd++;\r\n else even++;\r\n }\r\n if (odd == even) console.log(\"Yes\");\r\n else console.log(\"No\");\r\n}"}, {"source_code": "\r\n'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet input = '';\r\nprocess.stdin.on('data', inputStdin => {\r\n input += inputStdin;\r\n});\r\nprocess.stdin.on('end', _ => {\r\n main(input);\r\n});\r\n\r\nfunction main(input) {\r\n var args = input.split(\"\\n\");\r\n const t = parseInt(args[0], 10);\r\n for (var i = 1; i <= t; i++) {\r\n var n = parseInt(args[2 * i - 1], 10);\r\n var v = args[2 * i].split(\" \").map((n) => parseInt(n, 10));\r\n var cnt = 0;\r\n for (var j = 0; j < 2 * n; j++) {\r\n if (v[j] % 2 === 1) {\r\n cnt++;\r\n }\r\n }\r\n if (cnt === n) {\r\n console.log(\"Yes\");\r\n } else {\r\n console.log(\"No\");\r\n }\r\n }\r\n}"}, {"source_code": "const stdin = process.openStdin();\r\nlet content = '';\r\n\r\nstdin.addListener('data', (data) => {\r\n content += data;\r\n})\r\n\r\nstdin.addListener('end', () => {\r\n content = content.split('\\n');\r\n content.shift();\r\n content = content.map((string) => string.substring(0, string.length - 1));\r\n content.pop();\r\n content.forEach((str, i) => {\r\n if (i % 2 === 1) {\r\n str = str.split(' ').map(str => parseInt(str));\r\n if (oddSet(str)) {\r\n console.log('Yes');\r\n } else {\r\n console.log('No');\r\n }\r\n }\r\n });\r\n})\r\n\r\nconst oddSet = (arr) => {\r\n let oddNums = 0;\r\n arr.forEach((num) => {\r\n if (num % 2 === 1) {\r\n oddNums++;\r\n }\r\n });\r\n return oddNums === Math.floor(arr.length / 2);\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\n \r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\n \r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\n \r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(str => str.trim());\r\n\r\n \r\n\r\n main();\r\n});\r\n\r\n \r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\nvar gcd = function(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n \r\n return gcd(b, a % b);\r\n}\r\n\r\nfunction main()\r\n{\r\n //const name=readLine();\r\n //console.log(name);\r\n\r\n let test=readLine();\r\n while(test--)\r\n {\r\n n=parseInt(readLine());\r\n ara=readLine();\r\n ara=ara.split(\" \");\r\n cnt=0;\r\n for(i=0;i<2*n;i++)\r\n {\r\n val=parseInt(ara[i]);\r\n if(val&1)\r\n cnt++;\r\n }\r\n if(cnt===n)\r\n {\r\n console.log(\"YES\");\r\n }\r\n else\r\n {\r\n console.log(\"NO\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet n = nl.num();\n\t\tlet a = nl.nums();\n\t\tlet x = 0;\n\t\ta.forEach(e => {\n\t\t\tif (e%2 === 1) {\n\t\t\t\tx++;\n\t\t\t}\n\t\t});\n\t\tans.push(x == n);\n\t}\n\tconsole.log(ans.map(e => e?'Yes':'No').join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "function gcd(x, y) {\r\n if (y === 0) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction div(a, b) {\r\n return Math.floor(a / b);\r\n}\r\n\r\nfunction solve() {\r\n var n = Number(read());\r\n var c = 0;\r\n readArray((x) => { if (Number(x) & 1) {\r\n c++;\r\n }});\r\n write(c === n ? 'Yes' : 'No');\r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "'use strict';\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n \r\nlet inputString = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// End of Codeforces interface\r\n\r\nfunction main() {\r\n const testCaseCount = readline();\r\n\r\n for (let i = 0; i < testCaseCount; i++) {\r\n readline();\r\n const numberSet = readline().split(\" \").map(n => parseInt(n));\r\n let evenCount = 0;\r\n let oddCount = 0;\r\n \r\n for (let number of numberSet) {\r\n if (number % 2 === 0) {\r\n evenCount += 1;\r\n } else {\r\n oddCount += 1;\r\n }\r\n }\r\n\r\n if (evenCount === oddCount) {\r\n console.log('Yes');\r\n } else {\r\n console.log('No');\r\n }\r\n }\r\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main() \n});\n\nfunction readline() {\n return inputString[currentLine++]\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n let testCases = readline()\n while(testCases--)\n solve()\n}\n\n// function to solve problems\nfunction solve (){\n let n = readline()\n n = +n\n let odd = 0, even = 0\n let arr = readline().split(' ').map(x => {\n (x % 2 == 0) ? even++ : odd++\n return +x\n })\n if (odd == even) {\n console.log('YES')\n } else {\n console.log('NO')\n }\n}\n\nfunction sortAscending(a, b) {\n return a[0] - b[0]\n}\n// String.prototype.replaceAt = function (index, replacement) {\n// return this.substring(0, index) + replacement + this.substring(index + replacement.length)\n// }\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nlet solve = async () => {\r\n const nsc = parseInt(await getLine());\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = parseInt(await getLine());\r\n const arr = (await getLine()).split(' ').map(num => parseInt(num));\r\n let odd = 0, even = 0;\r\n for(let i = 0; i < arr.length; i++)\r\n if (arr[i] % 2 === 0)\r\n even++;\r\n else\r\n odd++;\r\n if (odd === even) {\r\n console.log('Yes');\r\n } else\r\n console.log('No');\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var l = 0;\n var t = +lines[l++]\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n var arr = lines[l++].trim().split(' ').map(Number)\n console.log(solve(n, arr))\n }\n});\n\nfunction solve(n, arr) {\n let odd = 0\n let even = 0\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] & 1) {\n odd++\n } else {\n even++\n }\n }\n return odd === even ? 'Yes' : 'No'\n}\n\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N * 2);\r\n\t\tvar div = 0;\r\n\t\tfor(var i = 0; i < N * 2; i++){\r\n\t\t\tif(list[i] % 2 == 0){\r\n\t\t\t\tdiv++;\r\n\t\t\t}else{\r\n\t\t\t\tdiv--;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(div == 0){\r\n\t\t\tmyout(\"Yes\");\r\n\t\t}else{\r\n\t\t\tmyout(\"No\");\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "function solution() {\r\n const n = readline();\r\n const arr = readline().split(' ').map(elem => +elem);\r\n\r\n return (arr.filter(elem => elem % 2 === 0).length === (arr.length >> 1)) ? 'Yes' : 'No';\r\n}\r\n\r\nfunction main(t) {\r\n for (var i = 0; i < t; i++) {\r\n print(solution());\r\n }\r\n}\r\n\r\nconst t = readline();\r\nmain(t);\r\n"}, {"source_code": "r=readline;for(r();n=r();print(i==n?'yes':'no'))i=0,r().split(\" \").map(x=>i+=x&1)"}, {"source_code": "r=readline;for(r();n=r();print(i==n?'yes':'no'))i=0,r().split(\" \").map(x=>i+=x&1)\r\n"}, {"source_code": "r=readline;for(r();n=r()|(i=0);print(i==n?'yes':'no'))r().split(\" \").map(x=>i+=x&1)"}, {"source_code": "for(t=readline();t--;){\r\n readline()\r\n c=[0,0]\r\n readline().split(' ').forEach(e=>c[e%2]++)\r\n print(c[0]==c[1]?'Yes':'No')\r\n}"}, {"source_code": "var testCase = +readline()\r\n\r\nfor(var i=0;i+node)\r\n for(var j=0;jx%2==1);\r\n if (w.length==n) {\r\n print(\"YES\");\r\n }\r\n else {\r\n print(\"NO\");\r\n }\r\n}"}, {"source_code": "//JAI SHREE RAM//\r\nvar t;\r\nt=readline();\r\nwhile(t--)\r\n{\r\nvar x,e=0,o=0;\r\nx=readline();\r\nvar a= readline().split(' ').map(x=> parseInt(x));\r\nfor(var i=0;i<2*x;i++)\r\n{\r\n if(a[i]%2===0)\r\n e++;\r\n else\r\n o++;\r\n}\r\nif(e==o)\r\nprint(\"YES\");\r\nelse\r\nprint(\"NO\");\r\n}"}, {"source_code": "t = +readline();\n\nfor (i = 0; i < t; i++) {\n n = +readline();\n a = readline().split(' ');\n a = a.map(Number);\n\n count = 0;\n for (j = 0; j < 2*n; j++) {\n if (a[j] % 2 === 0) {\n count++;\n if (count > n) {\n break;\n }\n }\n }\n\n if (count === n) {\n print('Yes');\n }\n else{\n print('No');\n }\n}"}], "negative_code": [{"source_code": "function oddSet() {\r\n const n = readline();\r\n const arr = readline().split(' ').map(elem => +elem);\r\n \r\n return (arr.filter(elem => elem % 2 === 0).length === (arr.length >> 1)) ? 'Yes' : 'No';\r\n}\r\n \r\nfunction main(t) {\r\n for (let i = 0; i < t; i++) {\r\n print(oddSet());\r\n }\r\n}"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0].split(' ').map(Number);\n var isOdd = false;\n for(var a = 1; a <= n * 2; a++){\n var k = lines[a].split(' ').map(Number);\n if(a % 2 === 0){\n for(var c = 0; c < k.length; c+=2){\n var d = k[c] + k[c+1];\n if(d % 2 === 1){\n isOdd = true;\n d = 0;\n }else{\n isOdd = false;\n break;\n }\n }\n if(isOdd === false){\n console.log('No');\n }else{\n console.log('Yes');\n }\n }\n \n }\n \n});"}, {"source_code": "r=readline;for(r();n=r()|(i=0);print(i&n?'yes':'no'))r().split(\" \").map(x=>i+=x&1)\r\n"}, {"source_code": "for(t=readline();t--;){\r\n readline()\r\n c=[]\r\n readline().split(' ').forEach(e=>c[e%2]++)\r\n print(c[0]==c[1]?'Yes':'No')\r\n}"}, {"source_code": "for(t=readline;t--;){\r\n readline()\r\n c=[]\r\n readline().split(' ').forEach(e=>c[e%2]++)\r\n print(c[0]==c[1]?'Yes':'No')\r\n}"}], "src_uid": "d5bd27c969d9cd910f13baa53c247871"} {"nl": {"description": "You are given strings $$$S$$$ and $$$T$$$, consisting of lowercase English letters. It is guaranteed that $$$T$$$ is a permutation of the string abc. Find string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.String $$$a$$$ is a permutation of string $$$b$$$ if the number of occurrences of each distinct character is the same in both strings.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) elements.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 a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a string $$$S$$$ ($$$1 \\le |S| \\le 100$$$), consisting of lowercase English letters. The second line of each test case contains a string $$$T$$$ that is a permutation of the string abc. (Hence, $$$|T| = 3$$$). Note that there is no limit on the sum of $$$|S|$$$ across all test cases.", "output_spec": "For each test case, output a single string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.", "sample_inputs": ["7\nabacaba\nabc\ncccba\nacb\ndbsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\nbbc\nabc\nac\nabc"], "sample_outputs": ["aaaacbb\nabccc\nbcdis\naaaaacbbdrr\ndddddddddddd\nbbc\nac"], "notes": "NoteIn the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence."}, "positive_code": [{"source_code": "var s, t, count, uni;\r\n var tests = parseInt(readline());\r\n\r\n function cToI(c) {\r\n return c.charCodeAt(0) - 'a'.charCodeAt(0);\r\n }\r\n\r\n function add(i, c) {\r\n for(var j = 0; j < c; j++) {\r\n uni.push(i+97);\r\n }\r\n }\r\n for (var te=0; te {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let [t] = readline().split(' ').map(num => parseInt(num));\n function outChars(chars) {\n console.log(Object.keys(chars).sort().map(c => new Array(chars[c]).fill(c).join('')).join(''));\n }\n for (let i = 0; i < t; i++) {\n let sS = readline().split('');\n let sT = readline();\n const chars = {};\n for (let j = 0; j < sS.length; j++) {\n chars[sS[j]] = (chars[sS[j]] || 0) + 1;\n }\n if (!chars['a'] || !chars['b'] || !chars['c']) {\n outChars(chars);\n } else if (sT !== 'abc') {\n outChars(chars);\n } else {\n let ch = Object.keys(chars).sort();\n let res = new Array(chars['a']).fill('a').join('');\n res += new Array(chars['c']).fill('c').join('');\n res += new Array(chars['b']).fill('b').join('');\n res += ch.slice(3).map(c => new Array(chars[c]).fill(c).join('')).join('');\n console.log(res);\n }\n }\n\n}"}], "negative_code": [], "src_uid": "419ef3579fe142c295ec4d89ee7becfc"} {"nl": {"description": "Let $$$\\mathsf{AND}$$$ denote the bitwise AND operation, and $$$\\mathsf{OR}$$$ denote the bitwise OR operation.You are given an array $$$a$$$ of length $$$n$$$ and a non-negative integer $$$k$$$. You can perform at most $$$k$$$ operations on the array of the following type: Select an index $$$i$$$ ($$$1 \\leq i \\leq n$$$) and replace $$$a_i$$$ with $$$a_i$$$ $$$\\mathsf{OR}$$$ $$$2^j$$$ where $$$j$$$ is any integer between $$$0$$$ and $$$30$$$ inclusive. In other words, in an operation you can choose an index $$$i$$$ ($$$1 \\leq i \\leq n$$$) and set the $$$j$$$-th bit of $$$a_i$$$ to $$$1$$$ ($$$0 \\leq j \\leq 30$$$). Output the maximum possible value of $$$a_1$$$ $$$\\mathsf{AND}$$$ $$$a_2$$$ $$$\\mathsf{AND}$$$ $$$\\dots$$$ $$$\\mathsf{AND}$$$ $$$a_n$$$ after performing at most $$$k$$$ operations. ", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le k \\le 10^9$$$). Then a single line follows, containing $$$n$$$ integers describing the arrays $$$a$$$ ($$$0 \\leq a_i < 2^{31}$$$). 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 a single line containing the maximum possible $$$\\mathsf{AND}$$$ value of $$$a_1$$$ $$$\\mathsf{AND}$$$ $$$a_2$$$ $$$\\mathsf{AND}$$$ $$$\\dots$$$ $$$\\mathsf{AND}$$$ $$$a_n$$$ after performing at most $$$k$$$ operations.", "sample_inputs": ["4\n3 2\n2 1 1\n7 0\n4 6 6 28 6 6 12\n1 30\n0\n4 4\n3 1 3 1"], "sample_outputs": ["2\n4\n2147483646\n1073741825"], "notes": "NoteFor the first test case, we can set the bit $$$1$$$ ($$$2^1$$$) of the last $$$2$$$ elements using the $$$2$$$ operations, thus obtaining the array [$$$2$$$, $$$3$$$, $$$3$$$], which has $$$\\mathsf{AND}$$$ value equal to $$$2$$$.For the second test case, we can't perform any operations so the answer is just the $$$\\mathsf{AND}$$$ of the whole array which is $$$4$$$."}, "positive_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet [n, k] = rna();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet sum = 0;\r\n\t\tfor (let j = 30; j >= 0 && k; j--) {\r\n\t\t\tlet cnt = 0;\r\n\t\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\t\tif ((a[i] & 1 << j) == 0) {\r\n\t\t\t\t\tcnt++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (cnt && cnt <= k) {\r\n\t\t\t\tk -= cnt;\r\n\t\t\t\tsum += 2**j;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlet ans = a[0];\r\n\t\tfor (let i = 0; i < n; i++) ans &= a[i];\r\n\r\n\t\tconsole.log(ans + sum);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\n\nconst { domainToASCII } = require('url');\n\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst L = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\nconst ra = ()=>readline().split(' ').map(a=>+a)\n \nconst calc = (n, k, A)=>{\n let ans = 0;\n for (let i=30; i>=0; i--){\n let cnt_missing = 0;\n let bit = 1< parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [n, k] = iInpArr();\r\n let arr = iInpArr();\r\n let bit = new Array(31).fill(0);\r\n for (let i = 0; i < bit.length; i++) {\r\n let cnt = 0,\r\n k = 1 << (bit.length - i - 1);\r\n for (let j = 0; j < n; j++) {\r\n if (k & arr[j]) cnt++;\r\n }\r\n bit[i] = n - cnt;\r\n }\r\n let ans = 0;\r\n for (let i = 0; i < bit.length; i++) {\r\n let j = 1 << (bit.length - i - 1);\r\n if (bit[i] === 0) ans += j;\r\n else if (k >= bit[i]) {\r\n k = k - bit[i];\r\n ans += j;\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "let readline = require('readline'); \r\nlet rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false\r\n}); \r\nlet input = []; \r\nlet takeInput = async function () { \r\n rl.on('line', function (line) {\r\n input.push(line);\r\n });\r\n}\r\ntakeInput();\r\nnumberOfline = 0;\r\nnextString = () =>{\r\n return input[numberOfline++];\r\n}\r\nnextInt = () => { \r\n return parseInt(input[numberOfline++], 10);\r\n}\r\nnextArrayOfInt = () => { \r\n let str = input[numberOfline++];\r\n return str.split(' ').map((val) => {\r\n return parseInt(val);\r\n }); \r\n}\r\nnextFloat = () => { \r\n return parseFloat(input[numberOfline++]);\r\n}\r\nintDiv = (val, div) => { \r\n return (val - val % div) / div;\r\n}\r\nlet print = (val) => { \r\n console.log(val);\r\n}\r\nlet main = () => { \r\n let test = 1;\r\n test = nextInt();\r\n while (test--){ \r\n solve()\r\n }\r\n\r\n} \r\n\r\nlet solve = () => { \r\n let [n, k] = nextArrayOfInt();\r\n // console.log(n, k);\r\n let arr = nextArrayOfInt();\r\n let bit = [];\r\n for (i = 0; i < 31; i++)\r\n {\r\n bit.push(0);\r\n }\r\n // print(bit);\r\n // print(arr);\r\n\r\n \r\n arr.forEach( (element) => {\r\n for (let i = 0; i < 31; i++)\r\n { \r\n if ((element & (1 << i)) > 0)\r\n {\r\n bit[i]++;\r\n }\r\n }\r\n });\r\n let ans = 0;\r\n for (let i = 30; i >= 0; i--)\r\n { \r\n if (bit[i] + k >= n)\r\n {\r\n ans += (1 << i);\r\n k -= (n - bit[i]);\r\n }\r\n }\r\n print(ans);\r\n // print(arr);\r\n // print(bit);\r\n\r\n\r\n\r\n \r\n}\r\nrl.on('close', main);"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst cnk = (n, k) => {\n let res = 1;\n for (let i = 1; i <= k; i++)\n res = res * (n - k + i) / i;\n // console.log(`DEBUG res`, res);\n return Math.round(res + 0.01);\n}\n\n\nconst calc = (n, k, a)=>{\n let m = 31;\n let bits = new Array(m).fill(0);\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n bits[j] += a[i] & (1 << j) ? 1 : 0;\n }\n }\n\n let ops = k;\n\n for (let i = m - 1; i >= 0; i--) {\n if (ops === 0) break;\n if (n - bits[i] <= ops) {\n ops -= (n - bits[i]);\n bits[i] = n;\n }\n }\n\n let result = 0;\n\n for (let i = m - 1; i >= 0; i--) {\n result += bits[i] === n ? (1 << i) : 0;\n } \n return result; \n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let [n, k] = ra();\n let a = ra();\n console.log(`${calc(n, k, a)}`);\n }\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar K = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar size = 31;\r\n\t\tvar bit = new Array(size).fill(0);\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tfor(var j = 0; j < size; j++){\r\n\t\t\t\tbit[j] += list[i] % 2;\r\n\t\t\t\tlist[i] = Math.floor(list[i] / 2);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor(var i = size - 1; i >= 0; i--){\r\n\t\t\tdiff = N - bit[i];\r\n\t\t\tif(diff <= K){\r\n\t\t\t\tK -= diff;\r\n\t\t\t\tbit[i] += diff;\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar output = 0;\r\n\t\tfor(var i = 0; i < size; i++){\r\n\t\t\tif(bit[i] == N){\r\n\t\t\t\toutput += (1 << i);\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, k, a) {\r\n for (let i = 30; i >= 0; i--) {\r\n let count = 0;\r\n for (let j = 0; j < n; j++) {\r\n if (!(a[j] & 1 << i)) count++;\r\n }\r\n if (count <= k) {\r\n for (let j = 0; j < n; j++) {\r\n a[j] |= 1 << i;\r\n }\r\n k -= count;\r\n }\r\n }\r\n let res = a[0];\r\n for (let i = 0; i < n; i++) {\r\n res &= a[i];\r\n }\r\n console.log(res);\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n let [n, k] = (await read()).split(' ').map(Number),\r\n a = (await read()).split(' ').map(Number);\r\n solve(n, k, a);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, k, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, arr) {\n let ans = 0\n for (let i = 30; i >= 0; i--) {\n let c = 0\n arr.forEach(x => {\n if (x & (1 << i)) return\n c++\n })\n if (c <= k) {\n k -= c\n ans |= (1 << i)\n }\n }\n return ans\n}\n"}], "negative_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet [n, k] = rna();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet sum = 0\r\n\t\tfor (let j = 30; j >= 0 && k; j--) {\r\n\t\t\tlet cnt = 0;\r\n\t\t\tfor (let i = 0; i < n && k; i++) {\r\n\t\t\t\tif ((a[i] & 1 << j) == 0) {\r\n\t\t\t\t\tcnt++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (cnt <= k) {\r\n\t\t\t\tk -= cnt;\r\n\t\t\t\tsum += 2**j;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlet ans = a[0];\r\n\t\tfor (let i = 0; i < n; i++) ans &= a[i];\r\n\r\n\t\tconsole.log(ans + sum);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\n\nconst { domainToASCII } = require('url');\n\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst L = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\nconst ra = ()=>readline().split(' ').map(a=>+a)\n \nconst calc = (n, k, A)=>{\n let ans = 0;\n for (let i=30; i>=0; i--){\n let cnt_missing = 0;\n let bit = 1< {\n // your code goes here\n let tc_count = readNum();\n\n const TRIAL_COUNT = 10;\n let a = Array(1e6);\n let b = Array(1e6);\n let nA, nB, curSum, prev, curAi;\n \n function maxForBigInt(...args) {\n return args.reduce((a, b) => a > b ? a : b);\n };\n\n while (tc_count--) {\n nA = readNum();\n for (let index = 0; index < nA; index++) {\n a[index] = readNum(); \n }\n for (let cnt = TRIAL_COUNT; cnt--;) {\n addemUp();\n arrReverse(a, nA);\n addemUp();\n }\n let ans = nA;\n writeLine(ans);\n }\n function addemUp() {\n nB = 0;\n prev = curSum = a[0];\n for (let index = 1; index < nA; index++) {\n curAi = a[index];\n if (prev !== curAi || curSum !== curAi) {\n curSum += curAi;\n }\n else {\n b[nB++] = curSum;\n curSum = curAi;\n }\n prev = curAi;\n }\n b[nB++] = curSum;\n [a, b] = [b, a];\n nA = nB;\n }\n});\n\n\n\n/**\n * @author flynn\n */\nfunction stdinReadAll() {\n const fs = require(\"fs\");\n return fs.readFileSync(0).toString();\n}\n\nfunction stdioCPPattern({\n getStringFunc = stdinReadAll\n}, callbackfn) {\n const aStr = getStringFunc() + \"\\n\";\n\n let cur = -1;\n const resultList = [];// Array(numberOfLine);\n const seperator = /\\s/;\n const MINUS_CODE = -3n;\n\n callbackfn({\n readCharArray,\n log: console.log,\n readNum() {\n let x = 0n, sign = 1n, ch = nextDigit();\n while (ch !== MINUS_CODE && (ch < 0 || 9 < ch)) ch = nextDigit();\n\n if (ch === MINUS_CODE) { sign = -1n; ch = nextDigit(); }\n\n while (0 <= ch && ch <= 9) {\n x = x * 10n + ch;\n ch = nextDigit();\n }\n return x * sign;\n },\n writeLine(data) {\n resultList.push(`${data}`);\n },\n readStr(bufferLen = 1e6) {\n return readCharArray(bufferLen).join(\"\");\n }\n });\n let prompt = resultList.join(\"\\n\");\n if (prompt) console.log(prompt);\n\n function nextDigit() {\n return BigInt(aStr.charCodeAt(++cur) - 48);\n }\n\n function readCharArray(bufferLen = 1e6) {\n const chArr = Array(bufferLen);\n let ch = aStr[++cur], p = 0;\n while (seperator.test(ch))\n ch = aStr[++cur];\n while (!seperator.test(ch)) {\n chArr[p++] = ch;\n ch = aStr[++cur];\n }\n return chArr.slice(0, p);\n }\n}"}, {"source_code": "// process.stdin.resume();\n// process.stdin.setEncoding('utf8');\n\nfunction readDOM(pos) {\n const inputList = document.querySelectorAll(\".custom-input\");\n const input = inputList[pos];\n // return input.querySelector(\"pre\").textContent;\n return input.textContent;\n}\n\nlet CONFIG = {\n // getStringFunc: readDOM.bind(null, 0)\n}\n\nfunction arrReverse(a, n) {\n for (let index = 0; index < n / 2; index++) {\n [a[index], a[n - index - 1] ] = [a[n - index - 1], a[index]];\n }\n}\n\nstdioCPPattern(CONFIG, ({ readNum, readStr, writeLine, readCharArray }) => {\n // your code goes here\n let tc_count = readNum();\n\n const TRIAL_COUNT = 1;\n let a = Array(1e6);\n let b = Array(1e6);\n let nA, nB, curSum, prev, curAi;\n \n function maxForBigInt(...args) {\n return args.reduce((a, b) => a > b ? a : b);\n };\n\n while (tc_count--) {\n nA = readNum();\n for (let index = 0; index < nA; index++) {\n a[index] = readNum(); \n }\n for (let cnt = TRIAL_COUNT; cnt--;) {\n addemUp();\n arrReverse(a, nA);\n addemUp();\n }\n let ans = nA;\n writeLine(ans);\n }\n function addemUp() {\n nB = 0;\n prev = curSum = a[0];\n for (let index = 1; index < nA; index++) {\n curAi = a[index];\n if (prev !== curAi || curSum !== curAi) {\n curSum += curAi;\n }\n else {\n b[nB++] = curSum;\n curSum = curAi;\n }\n prev = curAi;\n }\n b[nB++] = curSum;\n [a, b] = [b, a];\n nA = nB;\n }\n});\n\n\n\n/**\n * @author flynn\n */\nfunction stdinReadAll() {\n const fs = require(\"fs\");\n return fs.readFileSync(0).toString();\n}\n\nfunction stdioCPPattern({\n getStringFunc = stdinReadAll\n}, callbackfn) {\n const aStr = getStringFunc() + \"\\n\";\n\n let cur = -1;\n const resultList = [];// Array(numberOfLine);\n const seperator = /\\s/;\n const MINUS_CODE = -3n;\n\n callbackfn({\n readCharArray,\n log: console.log,\n readNum() {\n let x = 0n, sign = 1n, ch = nextDigit();\n while (ch !== MINUS_CODE && (ch < 0 || 9 < ch)) ch = nextDigit();\n\n if (ch === MINUS_CODE) { sign = -1n; ch = nextDigit(); }\n\n while (0 <= ch && ch <= 9) {\n x = x * 10n + ch;\n ch = nextDigit();\n }\n return x * sign;\n },\n writeLine(data) {\n resultList.push(`${data}`);\n },\n readStr(bufferLen = 1e6) {\n return readCharArray(bufferLen).join(\"\");\n }\n });\n let prompt = resultList.join(\"\\n\");\n if (prompt) console.log(prompt);\n\n function nextDigit() {\n return BigInt(aStr.charCodeAt(++cur) - 48);\n }\n\n function readCharArray(bufferLen = 1e6) {\n const chArr = Array(bufferLen);\n let ch = aStr[++cur], p = 0;\n while (seperator.test(ch))\n ch = aStr[++cur];\n while (!seperator.test(ch)) {\n chArr[p++] = ch;\n ch = aStr[++cur];\n }\n return chArr.slice(0, p);\n }\n}"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet n = readLine() >> 0;\n\t\tlet store = {};\n\t\tlet arr = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => {\n\t\t\t\tx = x >> 0;\n\t\t\t\tstore[x] = (store[x] || 0) + 1;\n\t\t\t\treturn x;\n\t\t\t});\n\n\t\tif (Object.values(store).length === 1) {\n\t\t\tconsole.log(Object.values(store)[0]);\n\t\t} else {\n\t\t\tconsole.log(1);\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n let arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n arr.sort((a, b) => a - b);\n if (arr[0] === arr[len - 1]) {\n console.log(len);\n } else {\n console.log(1);\n }\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n↑入力 ↓出力');\n Main();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var N = nextInt();\n var list = nextIntArray();\n var isOK = false;\n for(var j = 0; j < N - 1; j++){\n if(list[j] != list[j + 1]){\n isOK = true;\n break;\n }\n }\n if(isOK){\n output[i] = 1;\n }else{\n output[i] = N;\n }\n }\n myout(myconv(output, 9));\n}"}], "negative_code": [{"source_code": "// process.stdin.resume();\n// process.stdin.setEncoding('utf8');\n\nfunction readDOM(pos) {\n const inputList = document.querySelectorAll(\".custom-input\");\n const input = inputList[pos];\n// return input.querySelector(\"pre\").textContent;\n return input.textContent;\n}\n\nlet CONFIG = {\n // getStringFunc: readDOM.bind(null, 0)\n}\n\nstdioCPPattern(CONFIG, ({ readNum, readStr, writeLine, readCharArray }) => {\n // your code goes here\n let tc_count = readNum();\n\n const TRIAL_COUNT = 100;\n let a = Array(1e6);\n let b = Array(1e6);\n let nA, nB, curSum, prev, curAi;\n \n function maxForBigInt(...args) {\n return args.reduce((a, b) => a > b ? a : b);\n };\n\n while (tc_count--) {\n nA = readNum();\n for (let index = 0; index < nA; index++) {\n a[index] = readNum(); \n }\n for (let cnt = TRIAL_COUNT; cnt--;) {\n nB = 0;\n prev = curSum = a[0];\n for (let index = 1; index < nA; index++) {\n curAi = a[index];\n if (prev !== curAi || curSum !== curAi) {\n curSum += curAi;\n } else {\n b[nB++] = curSum;\n curSum = curAi;\n }\n prev = curAi;\n }\n b[nB++] = curSum;\n [a, b] = [b, a];\n nA = nB;\n }\n let ans = nA;\n writeLine(ans);\n }\n});\n\n/**\n * @author flynn\n */\nfunction stdinReadAll() {\n const fs = require(\"fs\");\n return fs.readFileSync(0).toString();\n}\n\nfunction stdioCPPattern({\n getStringFunc = stdinReadAll\n}, callbackfn) {\n const aStr = getStringFunc() + \"\\n\";\n\n let cur = -1;\n const resultList = [];// Array(numberOfLine);\n const seperator = /\\s/;\n const MINUS_CODE = -3n;\n\n callbackfn({\n readCharArray,\n log: console.log,\n readNum() {\n let x = 0n, sign = 1n, ch = nextDigit();\n while (ch !== MINUS_CODE && (ch < 0 || 9 < ch)) ch = nextDigit();\n\n if (ch === MINUS_CODE) { sign = -1n; ch = nextDigit(); }\n\n while (0 <= ch && ch <= 9) {\n x = x * 10n + ch;\n ch = nextDigit();\n }\n return x * sign;\n },\n writeLine(data) {\n resultList.push(`${data}`);\n },\n readStr(bufferLen = 1e6) {\n return readCharArray(bufferLen).join(\"\");\n }\n });\n let prompt = resultList.join(\"\\n\");\n if (prompt) console.log(prompt);\n\n function nextDigit() {\n return BigInt(aStr.charCodeAt(++cur) - 48);\n }\n\n function readCharArray(bufferLen = 1e6) {\n const chArr = Array(bufferLen);\n let ch = aStr[++cur], p = 0;\n while (seperator.test(ch))\n ch = aStr[++cur];\n while (!seperator.test(ch)) {\n chArr[p++] = ch;\n ch = aStr[++cur];\n }\n return chArr.slice(0, p);\n }\n}"}, {"source_code": "// process.stdin.resume();\n// process.stdin.setEncoding('utf8');\n\nfunction readDOM() {\n const inputList = document.querySelectorAll(\".input\");\n const input = inputList[2];\n return input.querySelector(\"pre\").textContent;\n}\n\nstdioCPPattern({}, ({ readNum, readStr, writeLine, readCharArray }) => {\n // your code goes here\n let tc_count = readNum();\n let n, prev, xx, count;\n \n while (tc_count--) {\n [n, prev] = [readNum(), readNum()];\n count = 1;\n while (--n) {\n xx = readNum();\n if (prev === xx) count++;\n prev = xx;\n }\n writeLine(count);\n }\n});\n\n/**\n * @author flynn\n */\nfunction stdinReadAll() {\n const fs = require(\"fs\");\n return fs.readFileSync(0).toString();\n}\n\nfunction stdioCPPattern({\n getStringFunc = stdinReadAll\n}, callbackfn) {\n const aStr = getStringFunc() + \"\\n\";\n\n let cur = 0;\n const resultList = [];// Array(numberOfLine);\n const seperator = /\\s/;\n\n callbackfn({\n readCharArray,\n log: console.log,\n readNum() {\n let x = 0, ch = aStr.charCodeAt(cur) - 48;\n while (ch < 0 || 9 < ch) ch = aStr.charCodeAt(++cur) - 48;\n while (0 <= ch && ch <= 9) {\n x = x * 10 + ch;\n ch = aStr.charCodeAt(++cur) - 48;\n }\n return x;\n },\n writeLine(data) {\n resultList.push(`${data}`);\n },\n readStr(bufferLen = 1e6) {\n return readCharArray(bufferLen).join(\"\");\n }\n });\n let prompt = resultList.join(\"\\n\");\n if (prompt) console.log(prompt);\n\n function readCharArray(bufferLen = 1e6) {\n const chArr = Array(bufferLen);\n let ch = aStr[cur], p = 0;\n while (seperator.test(ch))\n ch = aStr[++cur];\n while (!seperator.test(ch)) {\n chArr[p++] = ch;\n ch = aStr[++cur];\n }\n return chArr.slice(0, p);\n }\n}"}, {"source_code": "// process.stdin.resume();\n// process.stdin.setEncoding('utf8');\n\nfunction readDOM(pos) {\n const inputList = document.querySelectorAll(\".input\");\n const input = inputList[pos];\n return input.querySelector(\"pre\").textContent;\n}\n\nlet CONFIG = {\n // getStringFunc: readDOM.bind(null, 0)\n}\n\nstdioCPPattern(CONFIG, ({ readNum, readStr, writeLine, readCharArray }) => {\n // your code goes here\n let tc_count = readNum();\n let n, prev, curX, curSum, ans;\n \n function maxForBigInt(...args) {\n return args.reduce((a, b) => a > b ? a : b);\n };\n\n while (tc_count--) {\n n = readNum();\n prev = readNum();\n curSum = 0n;\n ans = 1;\n while (--n) {\n curX = readNum();\n if (prev !== curX || curSum !== curX) {\n curSum += curX;\n } else {\n curSum = curX;\n ans++;\n }\n }\n writeLine(ans);\n }\n});\n\n/**\n * @author flynn\n */\nfunction stdinReadAll() {\n const fs = require(\"fs\");\n return fs.readFileSync(0).toString();\n}\n\nfunction stdioCPPattern({\n getStringFunc = stdinReadAll\n}, callbackfn) {\n const aStr = getStringFunc() + \"\\n\";\n\n let cur = -1;\n const resultList = [];// Array(numberOfLine);\n const seperator = /\\s/;\n const MINUS_CODE = -3n;\n\n callbackfn({\n readCharArray,\n log: console.log,\n readNum() {\n let x = 0n, sign = 1n, ch = nextDigit();\n while (ch !== MINUS_CODE && (ch < 0 || 9 < ch)) ch = nextDigit();\n\n if (ch === MINUS_CODE) { sign = -1n; ch = nextDigit(); }\n\n while (0 <= ch && ch <= 9) {\n x = x * 10n + ch;\n ch = nextDigit();\n }\n return x * sign;\n },\n writeLine(data) {\n resultList.push(`${data}`);\n },\n readStr(bufferLen = 1e6) {\n return readCharArray(bufferLen).join(\"\");\n }\n });\n let prompt = resultList.join(\"\\n\");\n if (prompt) console.log(prompt);\n\n function nextDigit() {\n return BigInt(aStr.charCodeAt(++cur) - 48);\n }\n\n function readCharArray(bufferLen = 1e6) {\n const chArr = Array(bufferLen);\n let ch = aStr[++cur], p = 0;\n while (seperator.test(ch))\n ch = aStr[++cur];\n while (!seperator.test(ch)) {\n chArr[p++] = ch;\n ch = aStr[++cur];\n }\n return chArr.slice(0, p);\n }\n}"}], "src_uid": "7b80d3f3cd4f93e4277c76c76dc41f42"} {"nl": {"description": "This is an easier version of the problem. In this version $$$n \\le 1000$$$The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $$$n$$$ plots along the highway and is preparing to build $$$n$$$ skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from $$$1$$$ to $$$n$$$. Then if the skyscraper on the $$$i$$$-th plot has $$$a_i$$$ floors, it must hold that $$$a_i$$$ is at most $$$m_i$$$ ($$$1 \\le a_i \\le m_i$$$). Also there mustn't be integers $$$j$$$ and $$$k$$$ such that $$$j < i < k$$$ and $$$a_j > a_i < a_k$$$. Plots $$$j$$$ and $$$k$$$ are not required to be adjacent to $$$i$$$.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$) — the number of plots. The second line contains the integers $$$m_1, m_2, \\ldots, m_n$$$ ($$$1 \\leq m_i \\leq 10^9$$$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.", "output_spec": "Print $$$n$$$ integers $$$a_i$$$ — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them.", "sample_inputs": ["5\n1 2 3 2 1", "3\n10 6 8"], "sample_outputs": ["1 2 3 2 1", "10 6 6"], "notes": "NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $$$[10, 6, 6]$$$ is optimal. Note that the answer of $$$[6, 6, 8]$$$ also satisfies all restrictions, but is not optimal."}, "positive_code": [{"source_code": "Main();\nfunction myout(t){print(t);}//standard output\nfunction next(){return readline();}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す\n//6:1文字に分割 7:1文字に分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map((a)=>Number(a));case 6:return i.split(\"\");case 7:return i.split(\"\").map((a)=>Number(a));case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main() {\n var N = myconv(next(),1);\n var list = myconv(next(),4);\n \n var highest = 0;\n var highestList = [];\n for(var j = 0; j < N; j++){\n var tmpList = Object.assign([],list);\n var sum = tmpList[j];\n for(var i = j + 1; i < N; i++){\n if(tmpList[i - 1] < tmpList[i]){\n tmpList[i] = tmpList[i - 1];\n }\n sum += tmpList[i];\n }\n \n for(var i = j - 1; i >= 0; i--){\n if(tmpList[i + 1] < tmpList[i]){\n tmpList[i] = tmpList[i + 1];\n }\n sum += tmpList[i];\n }\n if(highest <= sum){\n highest = sum;\n highestList = tmpList;\n }\n //myout(myconv(tmpList,8));\n }\n \n //myout(\"last\");\n myout(myconv(highestList,8));\n}"}, {"source_code": "'use strict';\n\nconst { createInterface } = require('readline');\nconst rl = createInterface({\n input: process.stdin,\n crlfDelay: Infinity\n});\n\nconst lines = [];\nlet nextLine = 0;\nrl.on('line', (line) => {\n lines.push(line);\n});\n\nrl.on('close', () => {\n main();\n});\n\nfunction readline() {\n return lines[nextLine++];\n}\n\nfunction solve(arr) {\n const n = arr.length;\n const arrIdx = arr.map((x, i) => [x, i]);\n arrIdx.sort((a, b) => b[0] - a[0]);\n let minDesc = Number.MAX_SAFE_INTEGER;\n let minArr = [];\n for(let c = 0; c < n; c++) {\n let desc = 0;\n let curFloor = arr[c];\n const curArr = Array(n);\n curArr[c] = arr[c];\n for (let i = c + 1; i < n; i++) {\n if (arr[i] > curFloor) {\n desc += arr[i] - curFloor;\n if (desc >= minDesc) break;\n } else { // arr[i] <= curFloor\n curFloor = arr[i];\n }\n curArr[i] = curFloor;\n }\n if (desc >= minDesc) continue;\n curFloor = arr[c];\n for (let i = c - 1; i >= 0; i--) {\n if (arr[i] > curFloor) {\n desc += arr[i] - curFloor;\n if (desc >= minDesc) break;\n } else { // arr[i] <= curFloor\n curFloor = arr[i];\n }\n curArr[i] = curFloor;\n }\n if (minDesc > desc) {\n minDesc = desc;\n minArr = curArr;\n }\n }\n return minArr;\n}\n\nfunction main() {\n const n = readline();\n const arr = readline().split(' ').map(Number);\n const res = solve(arr);\n console.log(res.join(' '));\n}\n\n"}], "negative_code": [{"source_code": "Main();\nfunction myout(t){print(t);}//standard output\nfunction next(){return readline();}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す\n//6:1文字に分割 7:1文字に分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map((a)=>Number(a));case 6:return i.split(\"\");case 7:return i.split(\"\").map((a)=>Number(a));case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main() {\n var N = myconv(next(),1);\n var list = myconv(next(),4);\n var max = Math.max.apply(null,list);\n var maxIndex = list.indexOf(max);\n var maxIndexs = [];\n for(var i = 0; i < N; i++){\n if(list[i] == max){\n maxIndexs.push(i);\n }\n }\n \n var highest = 0;\n var highestList = [];\n for(var j = 0; j < maxIndexs.length; j++){\n var tmpList = Object.assign([],list);\n var sum = tmpList[maxIndexs[j]];\n for(var i = maxIndexs[j] + 1; i < N; i++){\n if(tmpList[i - 1] < tmpList[i]){\n tmpList[i] = tmpList[i - 1];\n }\n sum += tmpList[i];\n }\n \n for(var i = maxIndexs[j] - 1; i >= 0; i--){\n if(tmpList[i + 1] < tmpList[i]){\n tmpList[i] = tmpList[i + 1];\n }\n sum += tmpList[i];\n }\n if(highest <= sum){\n highest = sum;\n highestList = tmpList;\n }\n //myout(myconv(tmpList,8));\n }\n \n //myout(\"last\");\n myout(myconv(highestList,8));\n}"}, {"source_code": "Main();\nfunction myout(t){print(t);}//standard output\nfunction next(){return readline();}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す\n//6:1文字に分割 7:1文字に分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map((a)=>Number(a));case 6:return i.split(\"\");case 7:return i.split(\"\").map((a)=>Number(a));case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main() {\n var N = myconv(next(),1);\n var list = myconv(next(),4);\n var max = Math.max.apply(null,list);\n var maxIndex = list.indexOf(max);\n for(var i = maxIndex + 1; i < N; i++){\n if(list[i - 1] < list[i]){\n list[i] = list[i - 1];\n }\n }\n \n for(var i = maxIndex - 1; i >= 0; i--){\n if(list[i + 1] < list[i]){\n list[i] = list[i + 1];\n }\n }\n myout(myconv(list,8));\n}"}, {"source_code": "'use strict';\n\nconst { createInterface } = require('readline');\nconst rl = createInterface({\n input: process.stdin,\n crlfDelay: Infinity\n});\n\nconst lines = [];\nlet nextLine = 0;\nrl.on('line', (line) => {\n lines.push(line);\n});\n\nrl.on('close', () => {\n main();\n});\n\nfunction readline() {\n return lines[nextLine++];\n}\n\nfunction solve(arr) {\n const n = arr.length;\n const arrIdx = arr.map((x, i) => [x, i]);\n arrIdx.sort((a, b) => b[0] - a[0]);\n let minDesc = Number.MAX_SAFE_INTEGER;\n let minArr = [];\n for(let c = 0; c < n; c++) {\n let desc = 0;\n let curFloor = arr[c];\n const curArr = Array(n);\n curArr[c] = arr[c];\n for (let i = c + 1; i < n; i++) {\n if (arr[i] > curFloor) {\n desc += arr[i] - curFloor;\n if (desc >= minDesc) break;\n } else { // arr[i] <= curFloor\n curFloor = arr[i];\n }\n curArr[i] = curFloor;\n }\n if (desc >= minDesc) continue;\n curFloor = arr[c];\n for (let i = c - 1; i >= 0; i--) {\n if (arr[i] > curFloor) {\n desc += arr[i] - curFloor;\n if (desc >= minDesc) break;\n } else { // arr[i] <= curFloor\n curFloor = arr[i];\n }\n curArr[i] = curFloor;\n }\n if (minDesc > desc) {\n minDesc = desc;\n minArr = curArr;\n }\n }\n return minArr;\n}\n\nfunction main() {\n const n = readline();\n const arr = readline().split(' ').map(Number);\n const res = solve(arr);\n console.log(res);\n}\n\n"}], "src_uid": "88e6cd9ef45b956be8bee5d4fedd5725"} {"nl": {"description": "Little Vasya has received a young builder’s 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 ≤ N ≤ 1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000.", "output_spec": "In one line output two numbers — 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": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar n, identifier=0;\nrl.on('line', (input) => {\n if(identifier==0){\n n= parseInt(input);\n identifier++;\n }\n else{\n /*\n let maxValue=0;\n let dict={};\n let temp = input.split(' ').map(item=> parseInt(item));\n for(let i=0;i parseInt(item)).forEach(elem => {\n if(elem in dict)\n dict[elem] ++;\n else dict[elem] = 1;\n if(maxValue < dict[elem])\n maxValue=dict[elem];\n });\n console.log(\"%d %d\",maxValue, Object.keys(dict).length);\n rl.close();\n }\n });"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const bars = Number(readline())\n const lengths = readline().split(' ').map(Number)\n \n helper(bars, lengths)\n}\n\nfunction helper(bars, ls) {\n let cnt = new Map() \n \n for (let i = 0; i < bars; i++) {\n cnt.set(ls[i], (cnt.get(ls[i]) || 0) + 1)\n }\n \n let maxHeight = 0\n for (let [key, value] of cnt) {\n maxHeight = Math.max(maxHeight, value)\n }\n \n console.log(maxHeight + ' ' + cnt.size)\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction printResult(x) {\n process.stdout.write(x);\n}\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n const arr = readLine().split(' ').map(Number);\n\n const result = businessTrip(n, arr);\n printResult(result);\n}\n\nconst businessTrip = (n, a) => {\n const counts = new Array(1001).fill(0);\n for (let i = 0; i < n; i++) {\n counts[a[i]]++;\n }\n\n const height = counts.reduce((a, b) => Math.max(a, b));\n let total = 0;\n for (let i = 0; i < counts.length; i++) {\n if (total === n) break;\n if (counts[i]) total++;\n }\n\n return `${height} ${total}`;\n};"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar counter = 0, N, ans = 1;\nrl.on('line', (input) => {\n if (counter == 0) {\n N = parseInt(input);\n counter++\n }\n else {\n let cont = input.split(\" \").map(item => parseInt(item));\n cont.sort();\n let maxRep=1;\n for (let i = 0; i < cont.length - 1; i++) {\n if (cont[i] == cont[i + 1])\n ans++;\n else{\n if(maxRep < ans)\n maxRep = ans;\n\n ans = 1;\n }\n \n }\n if(maxRep < ans)\n maxRep = ans;\n cont2 = new Set(cont);\n\n\n console.log(\"%d %d\",maxRep, cont2.size);\n \n rl.close();\n }\n\n\n});"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\n/*\nvar counter = 0, N, ans = 1;\nrl.on('line', (input) => {\n if (counter == 0) {\n N = parseInt(input);\n counter++\n }\n else {\n let cont = input.split(\" \").map(item => parseInt(item));\n cont.sort();\n let maxRep=1;\n for (let i = 0; i < cont.length - 1; i++) {\n if (cont[i] == cont[i + 1])\n ans++;\n else{\n if(maxRep < ans)\n maxRep = ans;\n\n ans = 1;\n }\n \n }\n if(maxRep < ans)\n maxRep = ans;\n cont2 = new Set(cont);\n\n\n console.log(\"%d %d\",maxRep, cont2.size);\n \n rl.close();\n }\n\n\n});\n*/\n/*\n15\n5 3 8 3 5 8 3 5 8 3 3 8 5 8 8\n\n\n3 5 8\n--- ----- --------\n--- ----- --------\n--- ----- --------\n--- ----- --------\n--- --------\n --------\n\n\n{(3 -> 5) (5 -> 4) (8 -> 6)}\n*/\nvar counter = 0;\nrl.on('line', (input)=>{\n if(counter == 0)\n counter++;\n else{\n let myDict = {}, maxValue=0;\n input.split(' ').map(item => parseInt(item)).forEach(elem=> {\n if(elem in myDict)\n myDict[elem] ++;\n else myDict[elem] = 1;\n\n if(maxValue < myDict[elem])\n maxValue = myDict[elem];\n });\n\n console.log(\"%d %d\",maxValue, Object.keys(myDict).length);\n rl.close();\n }\n});"}, {"source_code": "\nvar n=+readline();\nvar l=readline().split(' ').map(function(v){return+v;});\nvar m={};\nvar ans=0;\nl.forEach(function(v){\n\tif(m[v]){\n\t\tm[v]++;\n\t}else{\n\t\tm[v]=1;\n\t\tans++;\n\t}\n});\nvar h=0;\nfor(var key in m){\n\th=Math.max(h, m[key]);\n}\nprint(h+' '+ans);"}, {"source_code": "function countUniqueElements(input,output){\n\tfor(var i = 0; i < input.length; i++){\n\t\tif(output[+input[i]] == undefined){\n\t\t\toutput[+input[i]] = 1;\n\t\t}\n\t\telse{\n\t\t\toutput[+input[i]]++;\n\t\t}\n\t}\n}\n\nvar n = +readline(), l = readline().split(\" \").map(Number), blocks = {}, arr = [];\n\ncountUniqueElements(l,blocks);\n\nfor(key in blocks){\n\tarr.push(blocks[key]);\n}\n\nwrite(Math.max.apply(null, arr));\nwrite(\" \" + Object.keys(blocks).length);"}, {"source_code": "\nvar a = new Array(1001);\n\nfor (var i = 0; i < 1001; i++)\n{\n a[i] = 0;\n}\n\nvar line = readline().split(' ')\n\nvar size = parseInt(line[0])\n\nline = readline().split(' ')\n\nfor (var i = 0; i < size; i++)\n{\n a[parseInt(line[i])] += 1;\n}\n\nvar maxHeight = 0;\nvar count = 0;\n\nfor (var i = 0; i < 1001; i++)\n{\n if (a[i] > maxHeight)\n {\n maxHeight = a[i];\n }\n \n if (a[i] != 0)\n {\n count++;\n }\n}\n\nprint(maxHeight + ' ' + count)"}, {"source_code": "var n = +readline();\nvar m = {};\nvar s = readline().split(' ').map(function (e) {\n\tif (!m[e]) m[e] = 1;\n\telse m[e] += 1;\n});\n\nprint(Math.max.apply(null, Object.keys(m).map(function (e) { return m[e]; })) + \" \" + Object.keys(m).length);"}, {"source_code": "readline(), readline()\n\t.split(' ')\n\t.map(function (e, i, a){\n\t\treturn [e, a.filter(function(_e){\n\t\t\treturn _e == e;\n\t\t}).length];\n\t}).filter(function(e, i, a){\n\t\treturn i == a.map(function(_e){\n\t\t\treturn _e[0];\n\t\t}).lastIndexOf(e[0]);\n\t}).map(function(e){\n\t\treturn e[1];\n\t}).forEach(function(e, i, a){\n\t\tif (i == (a.length-1))\n\t\t\tprint(Math.max.apply(null, a) + \" \" + a.length);\n\t})"}, {"source_code": "'use strict'\n\nlet N = +readline()\nlet l = readline().split(' ').map(v => parseInt(v)).sort((a, b) => a - b)\n\nlet n = 1\nlet m = 1\nlet c = 1\nfor (let i = 1; i < N; i++) {\n if (l[i] == l[i - 1]) {\n c++\n m = Math.max(m, c)\n } else {\n c = 1\n n++\n }\n}\n\nprint(m + ' ' + n)"}, {"source_code": "var n=readline();\nn=Number(n);\nvar a=readline();\na=a.split(\" \");\nfor (var i=0 ;i max) {\n\t\t\tmax = hash[key];\n\t\t}\n\t}\n}\n\nprint (max + \" \" + num);"}], "negative_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', (inputStdin) => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', (_) => {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const bars = Number(readline())\n const lengths = readline().split(' ').map(Number)\n \n helper(bars, lengths)\n}\n\nfunction helper(bars, ls) {\n let cnt = new Map() \n \n for (let i = 0; i < bars; i++) {\n cnt.set(ls[i], (cnt.get(ls[i]) || 0) + 1)\n }\n \n let max = 0\n let maxHeight = 0\n for (let [key, value] of cnt) {\n max = Math.max(max, key * value)\n maxHeight = Math.max(maxHeight, value)\n }\n \n console.log(maxHeight + ' ' + max)\n}"}, {"source_code": "\nvar n=+readline();\nvar l=readline().split(' ').map(function(v){return+v;});\nvar m={};\nvar ans=0;\nl.forEach(function(v){\n\tif(m[v]){\n\t\tm[v]++;\n\t}else{\n\t\tm[v]=1;\n\t\tans++;\n\t}\n});\nvar h=0;\nfor(var key in m){\n\th=Math.max(m[key]);\n}\nprint(h+' '+ans);"}, {"source_code": "\nvar a = new Array(1000);\n\nfor (var i = 0; i < 1000; i++)\n{\n a[i] = 0;\n}\n\nvar line = readline().split(' ')\n\nvar size = parseInt(line[0])\n\nline = readline().split(' ')\n\nfor (var i = 0; i < size; i++)\n{\n a[parseInt(line[i])] += 1;\n}\n\nvar maxHeight = 0;\nvar count = 0;\n\nfor (var i = 0; i < 1000; i++)\n{\n if (a[i] > maxHeight)\n {\n maxHeight = a[i];\n }\n \n if (a[i] != 0)\n {\n count++;\n }\n}\n\nprint(maxHeight + ' ' + count)"}, {"source_code": "var line = readline().split(' ')\n\nvar a = new Array(1000);\n\nfor (var i = 0; i < 1000; i++)\n{\n a[i] = 0;\n}\n\nfor (var i in line)\n{\n a[parseInt(i)] += 1;\n}\n\nvar maxHeight = 0;\nvar count = 0;\n\nfor (var i = 0; i < 1000; i++)\n{\n if (a[i] > maxHeight)\n {\n maxHeight = a[i];\n }\n \n if (a[i] != 0)\n {\n count++;\n }\n}\n\nprint(maxHeight + ' ' + count)"}, {"source_code": "var line = readline().split(' ')\n\nvar a = new Array(1000);\n\nfor (var i = 0; i < 1000; i++)\n{\n a[i] = 0;\n}\n\nvar size = parseInt(line[0])\n\nfor (var i = 0; i < size; i++)\n{\n a[parseInt(line[i])] += 1;\n}\n\nvar maxHeight = 0;\nvar count = 0;\n\nfor (var i = 0; i < 1000; i++)\n{\n if (a[i] > maxHeight)\n {\n maxHeight = a[i];\n }\n \n if (a[i] != 0)\n {\n count++;\n }\n}\n\nprint(maxHeight + ' ' + count)"}, {"source_code": "readline();\n\nprint(\n\treadline()\n\t\t.split(' ')\n\t\t.map(function (e, i, a){\n\t\t\treturn [e, a.filter(function(_e){\n\t\t\t\treturn _e == e;\n\t\t\t}).length];\n\t\t}).filter(function(e, i, a){\n\t\t\treturn i == a.map(function(_e){\n\t\t\t\treturn _e[0];\n\t\t\t}).lastIndexOf(e[0]);\n\t\t}).map(function(e){\n\t\t\treturn e[1];\n\t\t}).reduce(function(p, e, i, a){\n\t\t\treturn Math.max.apply(null, a) + \" \" +a.length;\n\t\t})\n);"}, {"source_code": "'use strict'\n\nlet N = +readline()\nlet l = readline().split(' ').map(v => parseInt(v)).sort((a, b) => a - b)\n\nlet n = 1\nlet m = -Infinity\nlet c = 1\nfor (let i = 1; i < N; i++) {\n if (l[i] == l[i - 1]) {\n c++\n } else {\n m = Math.max(m, c)\n c = 1\n n++\n }\n}\n\nprint(m + ' ' + n)"}, {"source_code": "var n=readline();\nn=Number(n);\nvar a=readline();\na=a.split(\" \");\nfor (var i=0 ;i input += x)\n\nprocess.stdin.on('end', () => {\n const lines = input.trim().split('\\n')\n let curLine = 0\n const [n, q] = parseIntArray(lines[curLine++])\n const v = [...new Array(n + 1)].map((_, idx) => idx)\n const acc = [0]\n v.slice(1).forEach((x) => acc.push(acc[acc.length - 1] + x))\n\n const suffixIdx = Math.max(1, n - 15)\n \n for (let i = 0; i < q; i++) {\n const [op, l, r] = parseIntArray(lines[curLine++])\n if (op === 1) {\n console.log(acc[r] - acc[l - 1])\n } else {\n const newSuffix = findNextPermutation(v.slice(suffixIdx), l)\n for (let j = suffixIdx; j <= n; j++) {\n v[j] = newSuffix[j - suffixIdx]\n acc[j] = acc[j - 1] + v[j]\n }\n }\n }\n})\n\nconst factorial = [1]\nfor (let i = 1; i < 20; i++) {\n factorial.push(i * factorial[i - 1])\n}\n\nconst findNextPermutation = (arr, k) => {\n const permIdx = getPermutationIdx(arr)\n return genPermutation([...arr].sort((a, b) => a - b), permIdx + k)\n}\n\nconst getPermutationIdx = (arr) => {\n let permIdx = 0\n arr.forEach((x, idx) => {\n const count = arr.slice(idx + 1).reduce((a, b) => a + (b < x ? 1 : 0), 0)\n permIdx += count * factorial[arr.length - idx - 1]\n })\n return permIdx\n}\n\nconst genPermutation = (arr, k) => {\n const rem = [...arr]\n const perm = []\n for (let i = 0; i < arr.length; i++) {\n const q = Math.floor(k / factorial[arr.length - i - 1])\n k -= q * factorial[arr.length - i - 1]\n perm.push(...rem.splice(q, 1))\n }\n return perm\n}\n\nconst parseIntArray = (line) => line.split(' ').map((x) => parseInt(x))\n"}], "negative_code": [{"source_code": "let input = ''\n\nprocess.stdin.on('data', (x) => input += x)\n\nprocess.stdin.on('end', () => {\n const lines = input.trim().split('\\n')\n let curLine = 0\n const [n, q] = parseIntArray(lines[curLine++])\n const v = [...new Array(n + 1)].map((_, idx) => idx)\n const acc = [0]\n v.slice(1).forEach((x) => acc.push(acc[acc.length - 1] + x))\n\n const suffixIdx = Math.max(1, n - 15)\n \n for (let i = 0; i < q; i++) {\n const [op, l, r] = parseIntArray(lines[curLine++])\n if (op === 1) {\n console.log(acc[r] - acc[l - 1])\n } else {\n const newSuffix = findNextPermutation(v.slice(suffixIdx), l)\n for (let j = suffixIdx; j < n; j++) {\n v[j] = newSuffix[j - suffixIdx]\n acc[j] = acc[j - 1] + v[j]\n }\n }\n }\n})\n\nconst factorial = [1]\nfor (let i = 1; i < 20; i++) {\n factorial.push(i * factorial[i - 1])\n}\n\nconst findNextPermutation = (arr, k) => {\n const permIdx = getPermutationIdx(arr)\n return genPermutation([...arr].sort((a, b) => a - b), permIdx + k)\n}\n\nconst getPermutationIdx = (arr) => {\n let permIdx = 0\n arr.forEach((x, idx) => {\n const count = arr.slice(idx + 1).reduce((a, b) => a + (b < x ? 1 : 0), 0)\n permIdx += count * factorial[arr.length - idx - 1]\n })\n return permIdx\n}\n\nconst genPermutation = (arr, k) => {\n const rem = [...arr]\n const perm = []\n for (let i = 0; i < arr.length; i++) {\n const q = Math.floor(k / factorial[arr.length - i - 1])\n k -= q * factorial[arr.length - i - 1]\n perm.push(...rem.splice(q, 1))\n }\n return perm\n}\n\nconst parseIntArray = (line) => line.split(' ').map((x) => parseInt(x))\n"}], "src_uid": "d458a65b351b2ba7f9891178ef1b64a1"} {"nl": {"description": "The integers shop sells $$$n$$$ segments. The $$$i$$$-th of them contains all integers from $$$l_i$$$ to $$$r_i$$$ and costs $$$c_i$$$ coins.Tomorrow Vasya will go to this shop and will buy some segments there. He will get all integers that appear in at least one of bought segments. The total cost of the purchase is the sum of costs of all segments in it.After shopping, Vasya will get some more integers as a gift. He will get integer $$$x$$$ as a gift if and only if all of the following conditions are satisfied: Vasya hasn't bought $$$x$$$. Vasya has bought integer $$$l$$$ that is less than $$$x$$$. Vasya has bought integer $$$r$$$ that is greater than $$$x$$$. Vasya can get integer $$$x$$$ as a gift only once so he won't have the same integers after receiving a gift.For example, if Vasya buys segment $$$[2, 4]$$$ for $$$20$$$ coins and segment $$$[7, 8]$$$ for $$$22$$$ coins, he spends $$$42$$$ coins and receives integers $$$2, 3, 4, 7, 8$$$ from these segments. He also gets integers $$$5$$$ and $$$6$$$ as a gift.Due to the technical issues only the first $$$s$$$ segments (that is, segments $$$[l_1, r_1], [l_2, r_2], \\ldots, [l_s, r_s]$$$) will be available tomorrow in the shop.Vasya wants to get (to buy or to get as a gift) as many integers as possible. If he can do this in differents ways, he selects the cheapest of them.For each $$$s$$$ from $$$1$$$ to $$$n$$$, find how many coins will Vasya spend if only the first $$$s$$$ segments will be available.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) — the number of segments in the shop. Each of next $$$n$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$, $$$c_i$$$ ($$$1 \\leq l_i \\leq r_i \\leq 10^9, 1 \\leq c_i \\leq 10^9$$$) — the ends of the $$$i$$$-th segments and its cost. It is guaranteed that the total sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case output $$$n$$$ integers: the $$$s$$$-th ($$$1 \\leq s \\leq n$$$) of them should be the number of coins Vasia will spend in the shop if only the first $$$s$$$ segments will be available.", "sample_inputs": ["3\n2\n2 4 20\n7 8 22\n2\n5 11 42\n5 11 42\n6\n1 4 4\n5 8 9\n7 8 7\n2 10 252\n1 11 271\n1 10 1"], "sample_outputs": ["20\n42\n42\n42\n4\n13\n11\n256\n271\n271"], "notes": "NoteIn the first test case if $$$s = 1$$$ then Vasya can buy only the segment $$$[2, 4]$$$ for $$$20$$$ coins and get $$$3$$$ integers.The way to get $$$7$$$ integers for $$$42$$$ coins in case $$$s = 2$$$ is described in the statement.In the second test case note, that there can be the same segments in the shop."}, "positive_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst INF = 1e9 + 1e9 + 100;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tlet la = INF, ra = -INF, lrc = INF;\r\n\t\tlet lb = INF, rb = -INF, lc = INF, rc = INF;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l <= la && r >= ra) {\r\n\t\t\t\tif (l < la || r > ra) {\r\n\t\t\t\t\tla = l;\r\n\t\t\t\t\tra = r;\r\n\t\t\t\t\tlrc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlrc = Math.min(lrc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (l <= lb) {\r\n\t\t\t\tif (l < lb) {\r\n\t\t\t\t\tlb = l;\r\n\t\t\t\t\tlc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlc = Math.min(lc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (r >= rb) {\r\n\t\t\t\tif (r > rb) {\r\n\t\t\t\t\trb = r;\r\n\t\t\t\t\trc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\trc = Math.min(rc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(Math.min(lc + rc, la == lb && ra == rb ? lrc : INF));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst INF = 1e18;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tlet la = INF, ra = -INF, lrc = INF;\r\n\t\tlet lb = INF, rb = -INF, lc = INF, rc = INF;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l <= la && r >= ra) {\r\n\t\t\t\tif (l < la || r > ra) {\r\n\t\t\t\t\tla = l;\r\n\t\t\t\t\tra = r;\r\n\t\t\t\t\tlrc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlrc = Math.min(lrc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (l <= lb) {\r\n\t\t\t\tif (l < lb) {\r\n\t\t\t\t\tlb = l;\r\n\t\t\t\t\tlc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlc = Math.min(lc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (r >= rb) {\r\n\t\t\t\tif (r > rb) {\r\n\t\t\t\t\trb = r;\r\n\t\t\t\t\trc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\trc = Math.min(rc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(Math.min(lc + rc, la == lb && ra == rb ? lrc : INF));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst INF = 1e18;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tlet la = INF, ra = -INF, lrc = INF;\r\n\t\tlet l = INF, r = -INF, lc = INF, rc = INF;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [li, ri, ci] = rna();\r\n\r\n\t\t\tif (li <= la && ri >= ra) {\r\n\t\t\t\tif (li < la || ri > ra) {\r\n\t\t\t\t\tla = li;\r\n\t\t\t\t\tra = ri;\r\n\t\t\t\t\tlrc = ci;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlrc = Math.min(lrc, ci);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (li == l) {\r\n\t\t\t\tlc = Math.min(lc, ci);\r\n\t\t\t} else if (li < l) {\r\n\t\t\t\tl = li;\r\n\t\t\t\tlc = ci;\r\n\t\t\t}\r\n\r\n\t\t\tif (ri == r) {\r\n\t\t\t\trc = Math.min(rc, ci);\r\n\t\t\t} else if (ri > r) {\r\n\t\t\t\tr = ri;\r\n\t\t\t\trc = ci;\r\n\t\t\t}\r\n\t\t\t//console.log({la, ra, l, r, lrc, lc, rc})\r\n\r\n\t\t\tconsole.log(Math.min(lc + rc, la == l && ra == r ? lrc : INF));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n \nconst calc = ()=>{\n // READING:\n let [n] = ra();\n LT({n});\n let A = [];\n let cost = 0;\n let ans = [];\n let minLPrice = -1;\n let minL = -1;\n let minRPrice = -1;\n let maxR = -1;\n let fullPrice = -1;\n for (let i=0; imaxR || r==maxR && c {\r\n return string.trim();\r\n });\r\n\r\n let t = inputReader.readNumber();\r\n\r\n function solve() {\r\n let n = inputReader.readNumber();\r\n let minL = Infinity,\r\n maxR = -Infinity,\r\n costL = Infinity,\r\n costR = Infinity,\r\n ans = Infinity;\r\n while (n--) {\r\n let [l, r, c] = inputReader.readNumberArray();\r\n if (l < minL) {\r\n minL = l;\r\n costL = c;\r\n ans = Infinity;\r\n }\r\n if (r > maxR) {\r\n maxR = r;\r\n costR = c;\r\n ans = Infinity;\r\n }\r\n if (l == minL && r == maxR) ans = Math.min(c, ans);\r\n if (l == minL && costL > c) costL = c;\r\n if (r == maxR && costR > c) costR = c;\r\n console.log(Math.min(ans, costL + costR));\r\n }\r\n }\r\n\r\n while (t--) {\r\n solve();\r\n }\r\n}\r\n\r\nvar _inputData = \"\";\r\nfunction cacheInput(data) {\r\n _inputData += data;\r\n}\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf8\");\r\nprocess.stdin.on(\"data\", cacheInput).on(\"end\", _main);\r\n\r\nfunction _inputReader() {\r\n function readNumber() {\r\n return Number(_inputLines[_lineNumber++]);\r\n }\r\n\r\n function readNumberArray() {\r\n return _inputLines[_lineNumber++].split(\" \").map((val) => Number(val));\r\n }\r\n\r\n return {\r\n readNumber,\r\n readNumberArray,\r\n };\r\n}\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nconst readInt = async function(){\r\n return parseInt(await getLine());\r\n}\r\n\r\nconst readIntArray = async function() {\r\n return (await getLine()).split(' ').map(num => parseInt(num));\r\n}\r\n\r\nlet solve = async () => {\r\n const nsc = await readInt();\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = await readInt();\r\n let [l,r,c] = await readIntArray();\r\n let lleft, lright, cl, rleft, rright, cr;\r\n let onel, oner, onec;\r\n onel = lleft = rleft = l;\r\n oner = lright = rright = r;\r\n onec = cl = cr = c;\r\n console.log(c);\r\n for(let i = 1; i < n; i++) {\r\n [l,r,c] = await readIntArray();\r\n if (l < lleft || (lleft === l && c < cl)) {\r\n lleft = l;\r\n lright = r;\r\n cl = c;\r\n }\r\n\r\n if (r > rright || (r === rright && c < cr)) {\r\n rleft = l;\r\n rright = r;\r\n cr = c;\r\n }\r\n\r\n if (l === lleft && r === rright) {\r\n if (l < onel || r > oner || (l === onel && r===oner && c < onec)) {\r\n onel = l;\r\n oner = r;\r\n onec = c;\r\n }\r\n }\r\n\r\n if (lleft === onel && rright === oner && cr + cl > onec) {\r\n console.log(onec);\r\n } else {\r\n console.log(cr + cl);\r\n }\r\n }\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines.slice(l, l + n).map(str => str.trim().split(' ').map(Number))\n l += n\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n let min = Infinity\n let mincost\n let max = -Infinity\n let maxcost\n const map = {}\n return arr.map(([l, r, c], i) => {\n if (l < min) {\n min = l\n mincost = i\n } else if (l === min && c < arr[mincost][2]) {\n mincost = i\n }\n if (r > max) {\n max = r\n maxcost = i\n } else if (r === max && c < arr[maxcost][2]) {\n maxcost = i\n }\n //\n let k = key(l, r)\n map[k] = (k in map) ? Math.min(map[k], c) : c\n //\n let prev\n if (mincost === maxcost) {\n prev = arr[mincost][2]\n } else {\n prev = arr[mincost][2] + arr[maxcost][2]\n }\n //\n k = key(min, max)\n if (k in map) {\n return Math.min(map[k], prev)\n } else {\n return prev\n }\n }).join('\\n')\n}\nfunction key(...args) {\n return args.join(',')\n}\n"}], "negative_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst INF = 1e9 + 100;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tlet la = INF, ra = -INF, lrc = INF;\r\n\t\tlet lb = INF, rb = -INF, lc = INF, rc = INF;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l <= la && r >= ra) {\r\n\t\t\t\tif (l < la || r > ra) {\r\n\t\t\t\t\tla = l;\r\n\t\t\t\t\tra = r;\r\n\t\t\t\t\tlrc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlrc = Math.min(lrc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (l <= lb) {\r\n\t\t\t\tif (l < lb) {\r\n\t\t\t\t\tlb = l;\r\n\t\t\t\t\tlc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlc = Math.min(lc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (r >= rb) {\r\n\t\t\t\tif (r > rb) {\r\n\t\t\t\t\trb = r;\r\n\t\t\t\t\trc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\trc = Math.min(rc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(Math.min(lc + rc, la == lb && ra == rb ? lrc : INF));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst INF = 1e18;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tlet la = INF, ra = -INF, lrc = INF;\r\n\t\tlet lb = INF, rb = -INF, lc = INF, rc = INF;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l <= la && r >= ra) {\r\n\t\t\t\tif (l < la || r > ra) {\r\n\t\t\t\t\tla = l;\r\n\t\t\t\t\tra = r;\r\n\t\t\t\t\tlrc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlrc = Math.min(lrc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (l <= lb) {\r\n\t\t\t\tif (l < lb) {\r\n\t\t\t\t\tlb = l;\r\n\t\t\t\t\tlc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlc = Math.min(lc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (r >= r) {\r\n\t\t\t\tif (r > rb) {\r\n\t\t\t\t\trb = r;\r\n\t\t\t\t\trc = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\trc = Math.min(rc, c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(Math.min(lc + rc, la == lb && ra == rb ? lrc : INF));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tlet la = INF, ra = -INF, lrc = INF;\r\n\t\tlet l = INF, r = -INF, lc = INF, rc = INF;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [li, ri, ci] = rna();\r\n\r\n\t\t\tif (li <= la && ri >= ra) {\r\n\t\t\t\tif (li < la || ri > ra) {\r\n\t\t\t\t\tla = li;\r\n\t\t\t\t\tra = ri;\r\n\t\t\t\t\tlrc = ci;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlrc = Math.min(lrc, ci);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (li == l) {\r\n\t\t\t\tlc = Math.min(lc, ci);\r\n\t\t\t} else if (li < l) {\r\n\t\t\t\tl = li;\r\n\t\t\t\tlc = ci;\r\n\t\t\t}\r\n\r\n\t\t\tif (ri == r) {\r\n\t\t\t\trc = Math.min(rc, ci);\r\n\t\t\t} else if (ri > r) {\r\n\t\t\t\tr = ri;\r\n\t\t\t\trc = ci;\r\n\t\t\t}\r\n\t\t\t//console.log({la, ra, l, r, lrc, lc, rc})\r\n\r\n\t\t\tconsole.log(Math.min(lc + rc, la == l && ra == r ? lrc : INF));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e18;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tlet mn = INF, mnc, mx = 0, mxc;\r\n\t\tlet oneseg, onel, oner, onec;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l < mn || l == mn && c < mnc) {\r\n\t\t\t\tmn = l;\r\n\t\t\t\tmnc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (r > mx || r == mx && c < mxc) {\r\n\t\t\t\tmx = r;\r\n\t\t\t\tmxc = c;\r\n\t\t\t}\r\n\r\n\t\t\toneseg = onel == mn && oner == mx;\r\n\r\n\t\t\tif (l == mn && r == mx && c < Math.min(oneseg ? onec : INF, mnc + mxc)) {\r\n\t\t\t\toneseg = true;\r\n\t\t\t\tonel = l;\r\n\t\t\t\toner = r;\r\n\t\t\t\tonec = c;\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(oneseg ? onec : mnc + mxc);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e18;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tlet mn = INF, mnc, mx = 0, mxc;\r\n\t\tlet oneseg, onel, oner, onec;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l < mn || l == mn && c < mnc) {\r\n\t\t\t\tmn = l;\r\n\t\t\t\tmnc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (r > mx || r == mx && c < mxc) {\r\n\t\t\t\tmx = r;\r\n\t\t\t\tmxc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (onel > mn || oner < mx)\r\n\t\t\t\toneseg = false;\r\n\r\n\t\t\tif (l == mn && r == mx && c < Math.min(oneseg ? onec : INF, mxc+mnc)) {\r\n\t\t\t\toneseg = true;\r\n\t\t\t\tonel = l;\r\n\t\t\t\toner = r;\r\n\t\t\t\tonec = c;\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(oneseg ? onec : mnc + mxc);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e18;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tlet mn = INF, mnc, mx = 0, mxc;\r\n\t\tlet oneseg, onel, oner, onec;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l < mn || l == mn && c < mnc) {\r\n\t\t\t\tmn = l;\r\n\t\t\t\tmnc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (r > mx || r == mx && c < mxc) {\r\n\t\t\t\tmx = r;\r\n\t\t\t\tmxc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (oner != mx || onel != mn)\r\n\t\t\t\toneseg = false;\r\n\r\n\t\t\tif (l == mn && r == mx && c < Math.min(oneseg ? onec : INF, mxc+mnc)) {\r\n\t\t\t\toneseg = true;\r\n\t\t\t\tonel = l;\r\n\t\t\t\toner = r;\r\n\t\t\t\tonec = c;\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(oneseg ? onec : mnc + mxc);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 2e9+10;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tlet mn = INF, mnc, mx = 0, mxc;\r\n\t\tlet oneseg, onel, oner, onec;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l < mn || l == mn && c < mnc) {\r\n\t\t\t\tmn = l;\r\n\t\t\t\tmnc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (r > mx || r == mx && c < mxc) {\r\n\t\t\t\tmx = r;\r\n\t\t\t\tmxc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (oner != mx || onel != mn)\r\n\t\t\t\toneseg = false;\r\n\r\n\t\t\tif (l == mn && r == mx && c < Math.min(oneseg ? onec : INF, mxc+mnc)) {\r\n\t\t\t\toneseg = true;\r\n\t\t\t\tonel = l;\r\n\t\t\t\toner = r;\r\n\t\t\t\tonec = c;\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(oneseg ? onec : mnc + mxc);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tlet mn = INF, mnc, mx = 0, mxc;\r\n\t\tlet oneseg, onel, oner, onec;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l < mn || l == mn && c < mnc) {\r\n\t\t\t\tmn = l;\r\n\t\t\t\tmnc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (r > mx || r == mx && c < mxc) {\r\n\t\t\t\tmx = r;\r\n\t\t\t\tmxc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (oner != mx || onel != mn)\r\n\t\t\t\toneseg = false;\r\n\r\n\t\t\tif (l == mn && r == mx && c < Math.min(oneseg ? onec : INF, mxc+mnc)) {\r\n\t\t\t\toneseg = true;\r\n\t\t\t\tonel = l;\r\n\t\t\t\toner = r;\r\n\t\t\t\tonec = c;\r\n\t\t\t}\r\n\r\n\t\t\tconsole.log(oneseg ? onec : mnc + mxc);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tlet mn = INF, mnc, mx = 0, mxc;\r\n\t\tlet oneseg, onel, oner, onec;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l < mn || l == mn && c < mnc) {\r\n\t\t\t\tmn = l;\r\n\t\t\t\tmnc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (r > mx || r == mx && c < mxc) {\r\n\t\t\t\tmx = r;\r\n\t\t\t\tmxc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (l == mn && r == mx && c < Math.min(oneseg ? onec : INF, mxc+mnc)) {\r\n\t\t\t\toneseg = true;\r\n\t\t\t\tonel = l;\r\n\t\t\t\toner = r;\r\n\t\t\t\tonec = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (oner != mx || onel != mn)\r\n\t\t\t\toneseg = false;\r\n\r\n\t\t\tconsole.log(oneseg ? onec : mnc + mxc);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst ans = [];\r\n\t\tlet mn = INF, mnc, mx = 0, mxc;\r\n\t\tlet oneseg, onel, oner, onec;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tconst [l, r, c] = rna();\r\n\t\t\tif (l < mn || l == mn && c < mnc) {\r\n\t\t\t\tmn = l;\r\n\t\t\t\tmnc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (r > mx || r == mx && c < mxc) {\r\n\t\t\t\tmx = r;\r\n\t\t\t\tmxc = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (l == mn && r == mx && c < mxc+mnc) {\r\n\t\t\t\toneseg = true;\r\n\t\t\t\tonel = l;\r\n\t\t\t\toner = r;\r\n\t\t\t\tonec = c;\r\n\t\t\t}\r\n\r\n\t\t\tif (oner != mx || onel != mn)\r\n\t\t\t\toneseg = false;\r\n\r\n\t\t\tconsole.log(oneseg ? onec : mnc + mxc);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "ee773d908fc297cc692aaecf6af299c9"} {"nl": {"description": "Ashish has two strings $$$a$$$ and $$$b$$$, each of length $$$n$$$, and an integer $$$k$$$. The strings only contain lowercase English letters.He wants to convert string $$$a$$$ into string $$$b$$$ by performing some (possibly zero) operations on $$$a$$$.In one move, he can either choose an index $$$i$$$ ($$$1 \\leq i\\leq n-1$$$) and swap $$$a_i$$$ and $$$a_{i+1}$$$, or choose an index $$$i$$$ ($$$1 \\leq i \\leq n-k+1$$$) and if $$$a_i, a_{i+1}, \\ldots, a_{i+k-1}$$$ are all equal to some character $$$c$$$ ($$$c \\neq$$$ 'z'), replace each one with the next character $$$(c+1)$$$, that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string $$$a$$$. Help Ashish determine if it is possible to convert string $$$a$$$ into $$$b$$$ after performing some (possibly zero) operations on it.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^5$$$) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers $$$n$$$ ($$$2 \\leq n \\leq 10^6$$$) and $$$k$$$ ($$$1 \\leq k \\leq n$$$). The second line of each test case contains the string $$$a$$$ of length $$$n$$$ consisting of lowercase English letters. The third line of each test case contains the string $$$b$$$ of length $$$n$$$ consisting of lowercase English letters. It is guaranteed that the sum of values $$$n$$$ among all test cases does not exceed $$$10^6$$$.", "output_spec": "For each test case, print \"Yes\" if Ashish can convert $$$a$$$ into $$$b$$$ after some moves, else print \"No\". You may print the letters of the answer in any case (upper or lower).", "sample_inputs": ["4\n3 3\nabc\nbcd\n4 2\nabba\nazza\n2 1\nzz\naa\n6 2\naaabba\nddddcc"], "sample_outputs": ["No\nYes\nNo\nYes"], "notes": "NoteIn the first test case it can be shown that it is impossible to convert $$$a$$$ into $$$b$$$.In the second test case,\"abba\" $$$\\xrightarrow{\\text{inc}}$$$ \"acca\" $$$\\xrightarrow{\\text{inc}}$$$ $$$\\ldots$$$ $$$\\xrightarrow{\\text{inc}}$$$ \"azza\".Here \"swap\" denotes an operation of the first type, and \"inc\" denotes an operation of the second type.In the fourth test case,\"aaabba\" $$$\\xrightarrow{\\text{swap}}$$$ \"aaabab\" $$$\\xrightarrow{\\text{swap}}$$$ \"aaaabb\" $$$\\xrightarrow{\\text{inc}}$$$ $$$\\ldots$$$ $$$\\xrightarrow{\\text{inc}}$$$ \"ddaabb\" $$$\\xrightarrow{\\text{inc}}$$$ $$$\\ldots$$$ $$$\\xrightarrow{\\text{inc}}$$$ \"ddddbb\" $$$\\xrightarrow{\\text{inc}}$$$ $$$\\ldots$$$ $$$\\xrightarrow{\\text{inc}}$$$ \"ddddcc\"."}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [len, k] = readLine().split(\" \").map(Number);\n const s1 = readLine();\n const s2 = readLine();\n let flag = true;\n const [a1, a2] = [Array(26).fill(0), Array(26).fill(0)];\n for (let i = 0; i < len; i++) {\n const char1 = s1[i].charCodeAt(0) - 97;\n a1[char1]++;\n }\n for (let i = 0; i < len; i++) {\n const char2 = s2[i].charCodeAt(0) - 97;\n a2[char2]++;\n }\n\n for (let i = 0; i < 26; i++) {\n if (a1[i] < a2[i]) {\n console.log(`NO`);\n flag = false;\n break;\n }\n const extra = a1[i] - a2[i];\n if (extra % k !== 0) {\n console.log(`NO`);\n flag = false;\n break;\n } else {\n a1[i + 1] += extra;\n }\n }\n flag && console.log(`YES`);\n }\n}\n"}], "negative_code": [], "src_uid": "09d0f11bdb9eca2161dee83a335dd2b7"} {"nl": {"description": "A binary string is a string where each character is either 0 or 1. Two binary strings $$$a$$$ and $$$b$$$ of equal length are similar, if they have the same character in some position (there exists an integer $$$i$$$ such that $$$a_i = b_i$$$). For example: 10010 and 01111 are similar (they have the same character in position $$$4$$$); 10010 and 11111 are similar; 111 and 111 are similar; 0110 and 1001 are not similar. You are given an integer $$$n$$$ and a binary string $$$s$$$ consisting of $$$2n-1$$$ characters. Let's denote $$$s[l..r]$$$ as the contiguous substring of $$$s$$$ starting with $$$l$$$-th character and ending with $$$r$$$-th character (in other words, $$$s[l..r] = s_l s_{l + 1} s_{l + 2} \\dots s_r$$$).You have to construct a binary string $$$w$$$ of length $$$n$$$ which is similar to all of the following strings: $$$s[1..n]$$$, $$$s[2..n+1]$$$, $$$s[3..n+2]$$$, ..., $$$s[n..2n-1]$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 50$$$). The second line of each test case contains the binary string $$$s$$$ of length $$$2n - 1$$$. Each character $$$s_i$$$ is either 0 or 1.", "output_spec": "For each test case, print the corresponding binary string $$$w$$$ of length $$$n$$$. If there are multiple such strings — print any of them. It can be shown that at least one string $$$w$$$ meeting the constraints always exists.", "sample_inputs": ["4\n1\n1\n3\n00000\n4\n1110000\n2\n101"], "sample_outputs": ["1\n000\n1010\n00"], "notes": "NoteThe explanation of the sample case (equal characters in equal positions are bold):The first test case: $$$\\mathbf{1}$$$ is similar to $$$s[1..1] = \\mathbf{1}$$$. The second test case: $$$\\mathbf{000}$$$ is similar to $$$s[1..3] = \\mathbf{000}$$$; $$$\\mathbf{000}$$$ is similar to $$$s[2..4] = \\mathbf{000}$$$; $$$\\mathbf{000}$$$ is similar to $$$s[3..5] = \\mathbf{000}$$$. The third test case: $$$\\mathbf{1}0\\mathbf{10}$$$ is similar to $$$s[1..4] = \\mathbf{1}1\\mathbf{10}$$$; $$$\\mathbf{1}01\\mathbf{0}$$$ is similar to $$$s[2..5] = \\mathbf{1}10\\mathbf{0}$$$; $$$\\mathbf{10}1\\mathbf{0}$$$ is similar to $$$s[3..6] = \\mathbf{10}0\\mathbf{0}$$$; $$$1\\mathbf{0}1\\mathbf{0}$$$ is similar to $$$s[4..7] = 0\\mathbf{0}0\\mathbf{0}$$$. The fourth test case: $$$0\\mathbf{0}$$$ is similar to $$$s[1..2] = 1\\mathbf{0}$$$; $$$\\mathbf{0}0$$$ is similar to $$$s[2..3] = \\mathbf{0}1$$$. "}, "positive_code": [{"source_code": "var numCases = parseInt(readline());\nfor (var i = 0; i < numCases; i ++) {\n var n = parseInt(readline());\n var str = readline();\n var output = '';\n for (var j = 0; j < n; j ++) {\n output += str[j * 2];\n }\n print(output);\n}"}, {"source_code": "var t = parseInt(readline());\n\nwhile(t--){\n var n = parseInt(readline());\n var s = readline();\n \n var sym = s[n - 1];\n var res = \"\";\n for(var i = 0; i < n; i++){\n res += sym;\n }\n print(res);\n}"}, {"source_code": "var t = parseInt(readline());\n \nwhile(t--){\n var n = parseInt(readline());\n var s = readline();\n \n var sym = s[n - 1];\n var res = \"\";\n for(var i = 0; i < n; i++){\n res += sym;\n }\n print(res);\n}\n"}, {"source_code": "'use strict'\n\nconst readLine = require('readline')\n\nconst readLineInterface = readLine.createInterface({\n input: process.stdin,\n})\n\nconst rows = []\nlet numberOfRows = 0\n\nreadLineInterface.on('line', (row) => {\n if (!numberOfRows) {\n numberOfRows = Number(row)\n } else {\n rows.push(row)\n }\n\n if (rows.length === numberOfRows * 2) {\n readLineInterface.close()\n }\n})\nreadLineInterface.on('close', main)\n\n\nfunction main() {\n for (let i = 0; i < numberOfRows * 2; i += 2) {\n const n = Number(rows[i])\n const fullS = rows[i + 1]\n const s = []\n const startPosition = n - 1\n for (let j = startPosition; j < fullS.length; j++) {\n s.push(fullS.slice(j - startPosition, j + 1))\n }\n let resultS = ''\n for (let i = 0; i < n; i++) {\n let additionValue = 0\n for (let j of s) {\n additionValue += Number(j[i])\n }\n if (additionValue === n) {\n resultS += '1'\n } else {\n resultS += '0'\n }\n }\n console.log(resultS)\n }\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n const str = readLine();\n let [count0, count1] = [0, 0];\n\n for (let i = 0; i < str.length; i++) {\n if (str[i] === \"0\") count0++;\n else count1++;\n }\n\n if (count0 > count1) console.log(\"0\".repeat(len));\n else console.log(\"1\".repeat(len));\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n↑入力 ↓出力');\n Main();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var N = nextInt();\n var s = next();\n var str = [];\n var count = new Array(N);\n for(var j = 0; j < N; j++){\n count[j] = new Set();\n }\n for(var j = 0; j < s.length; j++){\n str.push(s[j]);\n if(j >= N){\n str.shift();\n }\n if(j >= N - 1){\n for(var k = 0; k < N; k++){\n count[k].add(str[k]);\n }\n }\n }\n str = \"\";\n myerr(count);\n for(var j = 0; j < N; j++){\n var tmp = Array.from(count[j]).sort();\n str += tmp[0];\n }\n output[i] = str;\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', async _ => {\n inputString = inputString.split(/\\n/);\n try {\n await main(); \n } catch (e) {\n console.log(e)\n }\n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nasync function main() {\n const t = Number(readLine())\n for (let _ = 0; _ < t; _++) {\n const n = Number(readLine())\n const s = readLine().trim()\n console.log(Array.from(s).filter((_, i) => i % 2 === 0).join(''))\n }\n}\n\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const t = parseInt(readline());\n for (let i=0; i= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n a = a || 0;\n b = b || (this.length - 1);\n let prev = a;\n for (let i = a; i <= b; i++) {\n if (i == b || fn(this[i], this[i + 1])) {\n arr.push(this.slice(prev, i + 1));\n prev = i + 1;\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nfunction inv(b, m) {\n for (var a = m, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + m) % m;\n}\n\n// let MOD = 1e9 + 7\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;\n let t = $()\n while (t--) {\n let n = +$(), s = $()\n out.push(s[n-1].repeat(n))\n }\n log(out.join('\\n'))\n}\n"}, {"source_code": "const readline = require('readline');\nconst fs = require('fs');\n\nconst rl = readline.createInterface({\n input: process.env.TEST ? fs.createReadStream('input.txt') : process.stdin,\n output: process.stdout,\n});\n/** @type {Array} */\nconst lines = [];\n\nrl.on('line', (line) => lines.push(line));\n\nrl.on('close', task);\n\nfunction nextNumber() {\n return Number(lines.shift());\n}\nfunction nextString() {\n return lines.shift();\n}\n\nfunction task() {\n let t = nextNumber();\n while (t--) {\n let n = nextNumber();\n let s = nextString();\n let ret = '';\n for (let i = 0; i < n; i++) {\n ret += s[i * 2];\n }\n console.log(ret);\n }\n}\n"}, {"source_code": "const processData = (lines) => {\n let acc = 0\n const n = +lines[acc++]\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probA(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n\n let n = parseInt(readline());\n let s = readline().split('');\n let c = s[n-1];\n let res = '';\n for(let i = 0; i< n; i++){\n res += c;\n }\n\n console.log(res);\n }\n}"}], "negative_code": [{"source_code": "var numCases = parseInt(readline());\nfor (var i = 0; i < numCases; i ++) {\n var n = parseInt(readline());\n var str = readline();\n var output;\n for (var j = 0; j < n; j ++) {\n output += str[j * 2];\n }\n print(output);\n}"}, {"source_code": "'use strict'\n\nconst readLine = require('readline')\n\nconst readLineInterface = readLine.createInterface({\n input: process.stdin,\n})\n\nconst rows = []\nlet numberOfRows = 0\n\nreadLineInterface.on('line', (row) => {\n if (!numberOfRows) {\n numberOfRows = Number(row)\n } else {\n rows.push(row)\n }\n\n if (rows.length === numberOfRows * 2) {\n readLineInterface.close()\n }\n})\nreadLineInterface.on('close', main)\n\n\nfunction main() {\n for (let i = 0; i < numberOfRows * 2; i += 2) {\n const n = Number(rows[i])\n const fullS = rows[i + 1]\n const s = []\n const startPosition = n - 1\n for (let j = startPosition; j < fullS.length; j++) {\n s.push(fullS.slice(j - startPosition, j + 1))\n }\n let resultS = ''\n for (let i = 0; i < n; i++) {\n let additionValue = 0\n for (let j of s) {\n additionValue += Number(j[i])\n }\n if (additionValue > Math.floor(n / 2)) {\n resultS += '1'\n } else {\n resultS += '0'\n }\n }\n console.log(resultS)\n }\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n↑入力 ↓出力');\n Main();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var N = nextInt();\n var s = next();\n var str = [];\n var count = new Array(N);\n for(var j = 0; j < N; j++){\n count[j] = new Set();\n }\n for(var j = 0; j < s.length; j++){\n str.push(s[j]);\n if(j >= N){\n str.shift();\n }\n if(j >= N - 1){\n for(var k = 0; k < N; k++){\n count[k].add(str[k]);\n }\n }\n }\n str = \"\";\n for(var j = 0; j < N; j++){\n var tmp = Array.from(count[j]);\n str += tmp[0];\n }\n output[i] = str;\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n probA(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction probA(){\n let t = parseInt(readline());\n while(t > 0){\n t--;\n\n let n = parseInt(readline());\n let s = readline();\n console.log(s.substring(0,n));\n }\n}"}], "src_uid": "b37bbf1fe9ac5144cfa230633ccbdd79"} {"nl": {"description": "One day, you are accepted as being Dr. Chanek's assistant. The first task given by Dr. Chanek to you is to take care and store his magical stones.Dr. Chanek has $$$N$$$ magical stones with $$$N$$$ being an even number. Those magical stones are numbered from $$$1$$$ to $$$N$$$. Magical stone $$$i$$$ has a strength of $$$A_i$$$. A magical stone can be painted with two colours, namely the colour black or the colour white. You are tasked to paint the magical stones with the colour black or white and store the magical stones into a magic box with a magic coefficient $$$Z$$$ ($$$0 \\leq Z \\leq 2$$$). The painting of the magical stones must be done in a way such that there are $$$\\frac{N}{2}$$$ black magical stones and $$$\\frac{N}{2}$$$ white magical stones.Define $$$\\text{concat}(x, y)$$$ for two integers $$$x$$$ and $$$y$$$ as the result of concatenating the digits of $$$x$$$ to the left of $$$y$$$ in their decimal representation without changing the order. As an example, $$$\\text{concat}(10, 24)$$$ will result in $$$1024$$$.For a magic box with a magic coefficient $$$Z$$$, magical stone $$$i$$$ will react with magical stone $$$j$$$ if the colours of both stones are different and $$$\\text{concat}(A_i, A_j) \\times \\text{concat}(A_j, A_i) + A_i \\times A_j \\equiv Z \\mod 3$$$. A magical stone that is reacting will be very hot and dangerous. Because of that, you must colour the magical stones and determine the magic coefficient $$$Z$$$ of the magic box in a way such that there is no magical stone that reacts, or report if it is impossible.", "input_spec": "The first line contains a single even integer $$$N$$$ ($$$2 \\le N \\le 10^5$$$) — the number of magical stones Dr. Chanek has. The second line contains $$$N$$$ integer $$$A_1, A_2, \\ldots, A_N$$$ ($$$1 \\leq A_i \\leq 10^9$$$) — the strengths of all magical stones.", "output_spec": "If it is not possible to satisfy the condition of the problem, output $$$-1$$$. Otherwise, output two lines. The first line contains an integer $$$Z$$$ denoting the magic coefficient of the magic box. The second line contains a string $$$S$$$ of length $$$N$$$. $$$S_i$$$ is $$$0$$$ if magical stone $$$i$$$ is coloured black or $$$1$$$ if magical stone $$$i$$$ is coloured white. If there are more than one possibilities of colouring and choosing the magic coefficient $$$Z$$$, output any of them.", "sample_inputs": ["4\n4 10 9 14"], "sample_outputs": ["0\n1001"], "notes": "NoteBy giving the above colouring, it can be seen that: $$$i=1, j=2 \\longrightarrow \\text{concat}(4, 10) \\times \\text{concat}(10, 4) + 10 \\times 4 = 410 \\times 104 + 40 = 42680 \\equiv 2 \\mod 3$$$ $$$i=1, j=3 \\longrightarrow \\text{concat}(4, 9) \\times \\text{concat}(9, 4) + 4 \\times 9 = 49 \\times 94 + 36 = 4642 \\equiv 1 \\mod 3$$$ $$$i=4, j=2 \\longrightarrow \\text{concat}(14, 10) \\times \\text{concat}(10, 14) + 10 \\times 14 = 1410 \\times 1014 + 140 = 1429880 \\equiv 2 \\mod 3$$$ $$$i=4, j=3 \\longrightarrow \\text{concat}(14, 9) \\times \\text{concat}(9, 14) + 14 \\times 9 = 149 \\times 914 + 126 = 136312 \\equiv 1 \\mod 3$$$ Because of that, by choosing $$$Z = 0$$$, it can be guaranteed that there is no magical stone that reacts."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n const n = rn(),\r\n a = new Array(n);\r\n let cnt = [0, 0, 0];\r\n for (let i = 0; i < n; i++) {\r\n a[i] = rn() % 3;\r\n cnt[a[i]]++;\r\n }\r\n let res = new Array(n).fill(1);\r\n const check0 = () => {\r\n if (cnt[0] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n if (cnt[0] <= n / 2) {\r\n let t = n / 2 - cnt[0];\r\n for (let i = 0; i < n; i++) {\r\n if (!a[i]) res[i] = 0;else if (t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check1 = () => {\r\n if (cnt[0] === 0 || cnt[0] === n) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check2 = () => {\r\n if (cnt[1] + cnt[2] <= n / 2) {\r\n let t = n / 2 - (cnt[1] + cnt[2]);\r\n for (let i = 0; i < n; i++) {\r\n if (a[i]) res[i] = 0;else if (t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n if (check0()) return `0\\n${res.join('')}`;else if (check1()) return `1\\n${res.join('')}`;else if (check2()) return `2\\n${res.join('')}`;\r\n return -1;\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n }\r\n }\r\n if (t >= 100) ; else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n const n = rn(),\r\n a = new Array(n);\r\n let cnt = [0, 0, 0];\r\n for (let i = 0; i < n; i++) {\r\n a[i] = rn() % 3;\r\n cnt[a[i]]++;\r\n }\r\n let res = new Array(n).fill(1);\r\n const check0 = () => {\r\n if (cnt[0] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n if (cnt[0] <= n / 2) {\r\n let t = n / 2 - cnt[0];\r\n for (let i = 0; i < n; i++) {\r\n if (!a[i]) res[i] = 0;else if (t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check1 = () => {\r\n if (cnt[0] === 0 || cnt[0] === n) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check2 = () => {\r\n if (cnt[1] === 0 || cnt[2] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n if (cnt[1] + cnt[2] <= n / 2) {\r\n let t = n / 2 - (cnt[1] + cnt[2]);\r\n for (let i = 0; i < n; i++) {\r\n if (a[i]) res[i] = 0;else if (t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n if (check0()) return `0\\n${res.join('')}`;else if (check1()) return `1\\n${res.join('')}`;else if (check2()) return `2\\n${res.join('')}`;\r\n return -1;\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n }\r\n }\r\n if (t >= 100) ; else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n const n = rn(),\r\n a = new Array(n);\r\n let cnt = [0, 0, 0];\r\n for (let i = 0; i < n; i++) {\r\n a[i] = rn() % 3;\r\n cnt[a[i]]++;\r\n }\r\n let res = new Array(n).fill(1);\r\n const check0 = () => {\r\n if (cnt[0] === n || cnt[1] === n || cnt[2] === n || cnt[2] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check1 = () => {\r\n if (cnt[0] === n || cnt[2] === n || cnt[0] === 0 || cnt[1] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n if (cnt[0] + cnt[1] <= n / 2) {\r\n let t = n / 2 - (cnt[0] + cnt[1]);\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] < 2) res[i] = 0;else if (t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check2 = () => {\r\n if (cnt[1] === n || cnt[2] === 0 || cnt[0] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n if (cnt[0] <= n / 2 && cnt[1] <= n / 2) {\r\n let t = n / 2 - cnt[0];\r\n for (let i = 0; i < n; i++) {\r\n if (!a[i]) res[i] = 0;else if (a[i] === 1 && t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n if (check0()) return `0\\n${res.join('')}`;else if (check1()) return `1\\n${res.join('')}`;else if (check2()) return `2\\n${res.join('')}`;\r\n return -1;\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n }\r\n }\r\n if (t >= 100) ; else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n const n = rn(),\r\n a = new Array(n);\r\n let cnt = [0, 0, 0];\r\n for (let i = 0; i < n; i++) {\r\n a[i] = rn() % 3;\r\n cnt[a[i]]++;\r\n }\r\n let res = new Array(n).fill(1);\r\n const check0 = () => {\r\n if (cnt[0] <= n / 2) {\r\n let t = n / 2 - cnt[0];\r\n for (let i = 0; i < n; i++) {\r\n if (!a[i]) res[i] = 0;else if (t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check1 = () => {\r\n if (cnt[0] === n || cnt[1] === n || cnt[2] === n || cnt[0] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n return false;\r\n };\r\n const check2 = () => {\r\n if (cnt[1] === 0 || cnt[2] === 0) {\r\n for (let i = 0; i < n / 2; i++) res[i] = 0;\r\n return true;\r\n }\r\n if (cnt[1] + cnt[2] <= n / 2) {\r\n let t = n / 2 - (cnt[1] + cnt[2]);\r\n for (let i = 0; i < n; i++) {\r\n if (a[i]) res[i] = 0;else if (t) {\r\n res[i] = 0;\r\n t--;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n if (check0()) return `0\\n${res.join('')}`;else if (check1()) return `1\\n${res.join('')}`;else if (check2()) return `2\\n${res.join('')}`;\r\n return -1;\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = 1;\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n }\r\n }\r\n if (t >= 100) ; else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "src_uid": "381a292a15cd0613eafd2f6ddf011165"} {"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 — 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": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\n\nrl.on('line', (data) => {\n var arr = data.split(' ')\n var H = parseInt(arr[0])\n var L = parseInt(arr[1])\n\n var res = (L*L) - (H*H)\n res = res/(2*H)\n\n console.log(res.toFixed(13))\n});\n\n\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet l, h, result;\nrl.on('line', input => {\n [h, l] = input.split(' ').map(x => +x);\n result = (l*l - h*h) / h \n console.log(result / 2)\n rl.close()\n})"}, {"source_code": "// Codeforces 1199/B\n\nconst readline = require('readline');\n\nrl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nrl.question('', (input) => {\n const [h, l] = input.split(' ');\n console.log(((l*l) - (h*h)) / (2 * h));\n rl.close();\n});\n"}, {"source_code": "const processData = (lines) => {\n const [conditions] = lines\n const [h, l] = conditions.split(' ').map(x => +x)\n const hyp = Math.sqrt(h*h + l*l)\n const atan = Math.atan(l/h)\n const A = hyp / Math.sin(Math.PI - 2 * atan) * Math.sin(atan)\n console.log(A - h)\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n for (const line of lines) {\n const [H, L] = line.split(' ')\n if (H && L) {\n const A = (L ** 2) / (2 * H) - H / 2\n console.log(A)\n }\n }\n})"}, {"source_code": "let lines = ''\n \nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\nprocess.stdin.on('data', input => lines += input)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n lines = lines.split(EOL)\n \n main()\n})\n \nfunction main() {\n const [ h, l ] = lines[0].split(/\\s/).map(Number)\n const a = (Math.pow(l, 2) - Math.pow(h, 2)) / (2 * h)\n \n console.log(a.toFixed(13))\n}\n"}, {"source_code": "const readline = require('readline')\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', (line) => {\n var num = line.split(\" \").map(x => parseInt(x));\n var h, l;\n h = num[0];\n l = num[1];\n\n var result = (l*l-h*h)/(2*h);\n console.log(result);\n});\n"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n \nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n\nprint((l*l-h*h)/(2*h));"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n\nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n \nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\n\nvar h=num[0];\nvar l=num[1];\n \nvar r= (l*l-h*h)/(2*h);\n\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n\nvar r= (l*l-h*h)/(2*h);\nprint(r);\n"}, {"source_code": "function padStart(str, count, symbol) {\n for(var i = str.length; i < count; i++) {\n str = '0' + str;\n }\n \n return str;\n}\n\nvar arr = readline().split(' ').map(item => +item);\n\nprint((arr[1] * arr[1] - arr[0] * arr[0]) / (2 * arr[0]));\n"}, {"source_code": "var input = readline()\n .split(\" \")\n .map(function(x) {\n return parseInt(x);\n });\nvar result =\n (Math.pow(input[0], 2) + Math.pow(input[1], 2)) / (2 * input[0]) - input[0];\nprint(result);\n"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\n\n// function main() {\n// let line;\n// while(line = readline()) {\n// let [h, l] = line.split(' ').map(num => parseInt(num));\n// findHeight(h, l)\n// }\n// }\n\n// function findHeight(h, l) {\n// let output = (l*l - h*h)/(2*h);\n// print(output)\n// }\nvar line = readline().split(' ').map(num => parseInt(num));\nvar h = line[0];\nvar l = line[1];\nvar output = (l*l - h*h)/(2*h);\nprint(output)\n\n"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\n\nvar h,l;\nh = num[0], l= num[1];\n\nvar r = (l*l-h*h)/(2*h);\n\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n\nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\nvar r= (l*l-h*h)/(2*h);\nprint(r);\n"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n \nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var inp = readline().split(' ');\nvar h = parseInt(inp[0], 10), l = parseInt(inp[1], 10);\n\nvar a = (Math.pow(l,2) - Math.pow(h,2)) / (2*h);\n\nprint(a);"}, {"source_code": "(function() {\nvar INPUT = ``;\nvar OUTPUT = ``;\n\nvar main = function() {\"use strict\";\n // TODO\n var input = rdArN();\n var H = input[0];\n var L = input[1];\n \n var fullHyp = Math.sqrt(L*L + H*H);\n var halfHyp = fullHyp/2;\n var cosA = H/fullHyp;\n \n var stem = halfHyp/cosA;\n var x = stem - H;\n wr(x.toFixed(20))\n};\n\nif(INPUT){INPUT=INPUT.split('\\n').reverse();\nreadline=()=>INPUT.pop();\nwrite=(...s)=>{OUTPUT+=[...s].join(' ')};\nprint=(...s)=>{write(...s);OUTPUT+='\\n'};}\nconst\nrdS=readline,\nrdN=()=>+rdS(),\nrdArS=()=>rdS().split(' '),\nrdArN=()=>rdArS().map(v=>+v),\nwr=write,\npr=print,\nprAr=(a)=>pr(...a),\nprOb=(o)=>pr(JSON.stringify(o,null,4)),\ncrAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},\ngetPrimes=function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;jObject.defineProperty(o,pN,{configurable:true,enumerable:false,value:v});\ndefineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});\ndefineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});\ndefineProperty(Set.prototype,'union',function(s){return new Set([...this,...s]);});\ndefineProperty(Set.prototype,'intersection',function(s){return new Set([...this].filter((v)=>s.has(v)));});\ndefineProperty(Set.prototype,'difference',function(s){return new Set([...this].filter((v)=>!s.has(v)));});\n\nmain();\nreturn OUTPUT;\n})();"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n\nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n \nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n \nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x));\nvar h,l;\nh=num[0],l=num[1];\n\nvar r= (l*l-h*h)/(2*h);\nprint(r);"}, {"source_code": "var r,h,l,num=readline().split(\" \").map(x => parseInt(x)),h=num[0],l=num[1],r= (l*l-h*h)/(2*h);print(r);"}], "negative_code": [{"source_code": "var input = readline()\n .split(\" \")\n .map(function(x) {\n return parseInt(x);\n });\nvar result = (Math.pow(input[0], 2) + Math.pow(input[1], 2)) / 2 - input[0];\nprint(result);\n"}, {"source_code": "var input = readline()\n .split(\" \")\n .map(function(x) {\n return parseInt(x);\n });\nvar result = (input[0] + input[1]) / 2 - input[0];\nprint(result);\n"}], "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 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — 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 — 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": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n let [_, ...arr] = i.split`\\n`;\n arr = arr[0].split` `.map(Number);\n arr.sort((a, b) => a - b);\n arr.pop() === 1 ? arr.push(2) : arr.unshift(1);\n console.log(arr.join` `);\n});"}, {"source_code": "//Input\n// var firstLine = \"5\" ; var secondLine = \"1 2 3 4 5\" //R: 1 1 2 3 4\n// var firstLine = \"5\" ; var secondLine = \"2 3 4 5 6 \" //R: 1 2 3 4 5\n// var firstLine = \"3\" ; var secondLine = \"2 2 2\" //R: 1 2 2\n// var firstLine = \"4\" ; var secondLine = \"1 1 2 3\" //R: 1 1 1 2\n\n// var firstLine = \"3\" ; var secondLine = \"1 1 1\" //R: 1 1 2\n\n// var firstLine = \"10\" ; var secondLine = \"5 6 1 2 3 1 3 45 7 1000000000\" //R: 1 1 1 2 3 3 5 6 7 45\n// var firstLine = \"1\" ; var secondLine = \"1 \" //R: 1\n\n\nvar firstLine = readline(); var secondLine = readline();\n\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var n = parseInt(firstLine);\n var arr = secondLine.split(\" \").map(function (x){ return parseInt(x)});\n\n write(replace(arr));\n // console.log(replace(arr));\n return \"Hola\";\n};\n\nfunction replace(arr){\n var len = arr.length;\n var newArr = \"\"; new Array(len+1).join(\"0\").split(\"\").map(parseInt); if(len > 1){newArr[1] = 0};\n\n arr.sort(function (a, b){return a-b});\n if(arr[len-1] != 1){\n arr[len-1] = 1;\n } else{\n arr[len-1] = 2\n };\n arr.sort(function(a, b){ return a-b});\n\n for(var i = 0 ; i < len ; i++){\n newArr += \"\" + arr[i];\n if(i < len -1){\n newArr += \" \";\n };\n };\n\n return newArr;\n};\n\n\n\n\n\n"}, {"source_code": ";(function () {\n\n\tprint(function (n) {\n\n\t\tvar a = readline().split(' '),\n\t\t\tisEqual = true,\n\t\t\tmax = 0, j = 0;\n\n\t\tfor (var i = 0; i < n; i++) {\n\t\t\ta[i] = +a[i];\n\n\t\t\tif (isEqual && a[i] !== a[0]) isEqual = false;\n\n\t\t\tif (max < a[i]) {\n\t\t\t\tj = i;\n\t\t\t\tmax = a[i];\n\t\t\t}\n\t\t}\n\n\t\tif (isEqual) {\n\n\t\t\tif (a[0] !== 1) a[0] = 1;\n\t\t\telse a[a.length - 1] = 2;\n\n\t\t} else a[j] = 1;\n\n\t\treturn a.sort(function (a, b) { return a - b; }).join(' ');\n\n\t}(+readline()));\n\n}.call(this));"}, {"source_code": "var getNums = function () {\n return readline().split(' ').map(function (a) { return parseInt(a) });\n};\n\n\n//135A, 2 attempts\nvar n = readline();\nvar arr = getNums();\nvar max = {val: 1, pos: -1};\nfor (var i = 0; i < n; i++) {\n if (arr[i] > max.val) {\n max = {val: arr[i], pos: i};\n }\n}\nif (max.pos === -1) {\n arr[0] = 2;\n} else {\n arr[max.pos] = 1;\n}\nprint(arr.sort(function(a, b){return a - b}).join(' '));"}], "negative_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n let [_, ...arr] = i.split`\\n`;\n arr = arr[0].split` `.map(Number);\n arr.sort((a, b) => a - b);\n arr.pop() === 1 ? arr.push(2) : arr.unshift(1);\n console.log(arr);\n});"}, {"source_code": "//Input\n// var firstLine = \"5\" ; var secondLine = \"1 2 3 4 5\" //R: 1 1 2 3 4\n// var firstLine = \"5\" ; var secondLine = \"2 3 4 5 6 \" //R: 1 2 3 4 5\n// var firstLine = \"3\" ; var secondLine = \"2 2 2\" //R: 1 2 2\n// var firstLine = \"4\" ; var secondLine = \"1 1 2 3\" //R: 1 1 1 2\n\n// var firstLine = \"3\" ; var secondLine = \"1 1 1\" //R: 1 1 2\n\n// var firstLine = \"10\" ; var secondLine = \"5 6 1 2 3 1 3 45 7 1000000000\" //R: 1 1 1 2 3 3 5 6 7 45\n// var firstLine = \"1\" ; var secondLine = \"1 \" //R: 1\n\n\nvar firstLine = readline(); var secondLine = readline();\n\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var n = parseInt(firstLine);\n var arr = secondLine.split(\" \").map(function (x){ return parseInt(x)});\n\n // console.log(replace(arr));\n write(replace(arr));\n return \"Hola\";\n};\n\nfunction replace(arr){\n var len = arr.length;\n var newArr = new Array(len+1).join(\"0\").split(\"\").map(parseInt); if(len > 1){newArr[1] = 0};\n\n //console.log(\"arr: \" + arr);\n arr.sort(function (a, b){return a-b});\n //console.log(\"arr: \" + arr);\n if(arr[len-1] != 1){\n arr[len-1] = 1;\n } else{\n arr[len-1] = 2\n };\n arr.sort(function(a, b){ return a-b});\n\n\n\n return arr;\n};\n\n\n\n\n\n"}, {"source_code": "(function(){print(function(e){var t=readline().split(\" \").map(Number);if(t[0]===t.slice(-1)[0]){if(t[0]===1){t[t.length-1]=2}else{t[0]=1}}else{var n=0,r=0;for(var i=0;i n; i++) {\n if (arr[i] > max.val) {\n max = {val: arr[i], pos: i};\n }\n}\narr[max.pos] = 1;\nprint(arr.sort(function(a, b){return a - b}).join(' '));"}, {"source_code": "var getNums = function () {\n return readline().split(' ').map(function (a) { return parseInt(a) });\n};\n\n\n//134B\nvar n = readline();\nvar arr = getNums();\nvar max = {val: arr[0], pos: 0};\nfor (var i = 1; i < n; i++) {\n if (arr[i] > max.val) {\n max = {val: arr[i], pos: i};\n }\n}\narr[max.pos] = 1;\nprint(arr.sort(function(a, b){return a - b}).join(' '));"}], "src_uid": "1cd10f01347d869be38c08ad64266870"} {"nl": {"description": "You are given an equation: Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order.", "input_spec": "The first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0.", "output_spec": "In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.", "sample_inputs": ["1 -5 6"], "sample_outputs": ["2\n2.0000000000\n3.0000000000"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\n\nconst A = lll[0]\nconst B = lll[1]\nconst C = lll[2]\n\n;(function () {\n if (A == 0) {\n if (B == 0) {\n if (C == 0) return print(-1)\n return print(0)\n }\n print(1)\n return print(-C / B)\n } else {\n const D = B * B - 4 * A * C\n if (D < 0) return print(0)\n if (D == 0) {\n print(1)\n return print(-B / (2 * A))\n }\n print(2)\n if (A > 0) {\n print((-B - Math.sqrt(D)) / (2 * A))\n print((-B + Math.sqrt(D)) / (2 * A))\n } else {\n print((-B + Math.sqrt(D)) / (2 * A))\n print((-B - Math.sqrt(D)) / (2 * A))\n }\n }\n})()"}], "negative_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\n\nconst A = lll[0]\nconst B = lll[1]\nconst C = lll[2]\n\n;(function () {\n if (A == 0) {\n if (B == 0) {\n if (C == 0) return print(-1)\n return print(0)\n }\n print(1)\n return print(-C / B)\n } else {\n const D = B * B - 4 * A * C\n if (D < 0) return print(0)\n if (D == 0) {\n print(1)\n return print(-B / (2 * A))\n }\n print(2)\n print((-B - Math.sqrt(D)) / (2 * A))\n print((-B + Math.sqrt(D)) / (2 * A))\n }\n})()"}, {"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\n\nconst A = lll[0]\nconst B = lll[1]\nconst C = lll[2]\n\n;(function () {\n if (A == 0) {\n if (B == 0) {\n if (C == 0) return print(0)\n return print(-1)\n }\n print(1)\n return print(-C / B)\n } else {\n const D = B * B - 4 * A * C\n if (D < 0) return print(0)\n if (D == 0) {\n print(1)\n return print(-B / (2 * A))\n }\n print(2)\n print((-B - Math.sqrt(D)) / (2 * A))\n print((-B + Math.sqrt(D)) / (2 * A))\n }\n})()"}], "src_uid": "84372885f2263004b74ae753a2f358ac"} {"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 ≤ t ≤ 105). Each of the next t lines will contain four space-separated integers n, k, d1, d2 (1 ≤ n ≤ 1012; 0 ≤ k ≤ n; 0 ≤ d1, d2 ≤ k) — 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 = 0, d1 = 0, d2 = 0). 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 = 3). As d1 = 0 and d2 = 0, 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 = 1, d2 = 0. 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": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction feasible(n, k, d1, d2) {\n\tif (n%3 != 0) {\n\t\treturn false;\n\t}\n\tvar x = k - d1 - 2*d2;\n\tif (x < 0 || x%3 != 0) {\n\t\treturn false;\n\t}\n\tvar c0 = x/3, b0 = c0 + d2, a0 = b0 + d1,\n\t\ty = n/3;\n\tif (a0 > y || b0 > y || c0 > y ||\n\t\ta0 < 0 || b0 < 0 || c0 < 0) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction main() {\n\tvar numCases = parseInt(readline());\n\tfor (var caseIndex = 0; caseIndex < numCases; ++caseIndex) {\n\t\tvar data = tokenizeIntegers(readline()),\n\t\t\tn = data[0], k = data[1], d1 = data[2], d2 = data[3];\n\t\tif (feasible(n, k, d1, d2) || feasible(n, k, -d1, d2) ||\n\t\t\t\tfeasible(n, k, d1, -d2) || feasible(n, k, -d1, -d2)) {\n\t\t\tprint('yes');\n\t\t} else {\n\t\t\tprint('no');\n\t\t}\n\t}\n}\n\nmain();\n"}], "negative_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction solve(n, k, d1, d2) {\n\tif (n%3 != 0) {\n\t\treturn 'no';\n\t}\n\tvar x = k - d1 - 2*d2;\n\tif (x < 0 || x%3 != 0) {\n\t\treturn 'no';\n\t}\n\tvar c0 = x/3, b0 = c0 + d2, a0 = b0 + d1,\n\t\ty = n/3;\n\tif (a0 > y || b0 > y || c0 > y) {\n\t\treturn 'no';\n\t}\n\treturn 'yes';\n}\n\nfunction main() {\n\tvar numCases = parseInt(readline());\n\tfor (var caseIndex = 0; caseIndex < numCases; ++caseIndex) {\n\t\tvar data = tokenizeIntegers(readline()),\n\t\t\tn = data[0], k = data[1], d1 = data[2], d2 = data[3];\n\t\tprint(solve(n, k, d1, d2));\n\t}\n}\n\nmain();\n"}], "src_uid": "324298100f3e36d289ef6ca8178ac6d3"} {"nl": {"description": "You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \\ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \\le l \\le r \\le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\\max(a_{1}, a_{2}, \\ldots, a_{l-1}, a_{r+1}, a_{r+2}, \\ldots, a_{n}) - \\min(a_{1}, a_{2}, \\ldots, a_{l-1}, a_{r+1}, a_{r+2}, \\ldots, a_{n}) + \\max(a_{l}, \\ldots, a_{r}) - \\min(a_{l}, \\ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) — the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \\leq n \\leq 10^5)$$$ — 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$$$) — the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each testcase print a single integer — the maximum beauty of a proper subsegment.", "sample_inputs": ["4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8"], "sample_outputs": ["9\n297\n0\n14"], "notes": "NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const testCases = readline();\r\n for (let i = 0; i < testCases; i++) {\r\n const length = readline();\r\n const arr = readline().split(\" \");\r\n arr.sort((a, b) => a - b);\r\n const result =\r\n parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1]);\r\n console.log(result);\r\n }\r\n}\r\n"}, {"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const n = parseInt(input[index]);\n index++;\n const a = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n a,\n };\n testCases.push(testCase);\n }\n}\n\nconst attempt = (a, n) => {\n let leftMin = Infinity;\n let leftMax = -Infinity;\n const leftMins = [];\n const leftMaxs = [];\n for (let i = 0; i < n; i++) {\n const v = a[i];\n if (v < leftMin) leftMin = v;\n if (v > leftMax) leftMax = v;\n leftMins.push(leftMin);\n leftMaxs.push(leftMax);\n }\n let rightMin = Infinity;\n let rightMax = -Infinity;\n const rightMins = [];\n const rightMaxs = [];\n for (let i = n - 1; i >= 0; i--) {\n const v = a[i];\n if (v < rightMin) rightMin = v;\n if (v > rightMax) rightMax = v;\n rightMins.unshift(rightMin);\n rightMaxs.unshift(rightMax);\n }\n\n const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);\n const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);\n // console.log(leftMins);\n // console.log(leftMaxs);\n // console.log(leftDiffs);\n // console.log(rightMins);\n // console.log(rightMaxs);\n // console.log(rightDiffs);\n\n let result = 0;\n for (let i = 0; i < n - 1; i++) {\n const v = leftDiffs[i] + rightDiffs[i + 1];\n if (v > result) result = v;\n }\n return result;\n};\n\nfunction solution(testCase) {\n let { n, a } = testCase;\n\n a.sort((b, c) => b - c);\n console.log(a[a.length - 1] + a[a.length - 2] - a[1] - a[0]);\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "/* why are we still here, just to suffer? */\r\nlet buf='';\r\n\r\nprocess.stdin.on('readable', ()=>{\r\n let chunk=process.stdin.read();\r\n if(chunk) buf += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', ()=>{\r\n let lines=buf.split('\\n');\r\n let lc=0;\r\n let t=parseInt(lines[lc++]);\r\n while(t--) {\r\n let n=parseInt(lines[lc++]);\r\n let _=lines[lc++].split(' ');\r\n let a=[];\r\n for(let i=0;i=max1) {\r\n max2=max1; max1=a[i];\r\n } else if(a[i]>max2) max2=a[i];\r\n \r\n if(a[i]<=min1) {\r\n min2=min1; min1=a[i]; \r\n } else if(a[i] stop += c);\nprocess.stdin.on('end', () => { \n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i];\n }else{\n var k = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});\n var a = k[k.length - 1] + k[k.length - 2];\n var b = k[0] + k[1];\n a -= b;\n console.log(a);\n }\n }\n}); "}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n readline();\r\n const arr = readline().split(' ').map(Number);\r\n\r\n\r\n let min1 = Infinity;\r\n let min2 = Infinity;\r\n let max1 = -1;\r\n let max2 = -1;\r\n\r\n for (let i = 0; i < arr.length; i++) {\r\n if (arr[i] < min1) {\r\n min2 = min1;\r\n min1 = arr[i];\r\n } else if (arr[i] < min2) {\r\n min2 = arr[i];\r\n }\r\n if (arr[i] > max1) {\r\n max2 = max1;\r\n max1 = arr[i];\r\n } else if (arr[i] > max2) {\r\n max2 = arr[i];\r\n }\r\n }\r\n output(max1 + max2 - min1 - min2);\r\n }\r\n}\r\n\r\n// max max min min\r\n// min max min max\r\n// max min min max\r\n//\r\n//\r\n//"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '', currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => { inputString += inputStdin; });\r\nprocess.stdin.on('end', _ => { \r\n inputString = inputString.trim().split('\\n').map(string => string.trim());\r\n main(); \r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const t = +readLine();\r\n for(let i = 0; i < t; i++){\r\n const n = +readLine();\r\n const arr = readLine().split(' ').map(p => +p);\r\n let result = myFunc(arr);\r\n console.log(result);\r\n }\r\n}\r\n\r\n\r\n\r\nfunction myFunc(arr){\r\n \r\n const n = arr.length;\r\n arr.sort((a, b) => a - b);\r\n\r\n return arr[n-1] + arr[n-2] - arr[1] - arr[0];\r\n\r\n}\r\n"}, {"source_code": "var n, a;\r\n var tests = parseInt(readline());\r\n for (var t=0; tparseInt(x));\r\n a.sort((x, y) => x-y);\r\n print(a[n-1] + a[n-2] - a[0] - a[1])\r\n }"}], "negative_code": [{"source_code": "\"use strict\";\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n \r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\nconst testCases = readline()\r\n \r\nfunction main() {\r\n const length = readline()\r\n const arr = readline().split(' ')\r\n arr.sort((a, b) => a - b)\r\n const result = parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1])\r\n console.log(result)\r\n}\r\n"}, {"source_code": "\"use strict\";\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n \r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// Main Function, write code here\r\n \r\nfunction main() {\r\n const length = readline()\r\n const arr = readline().split(' ')\r\n arr.sort((a, b) => a - b)\r\n const result = parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1])\r\n console.log(result)\r\n}"}, {"source_code": "\"use strict\";\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n \r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\nfunction main() {\r\n const length = readline()\r\n const arr = readline().split(' ')\r\n arr.sort()\r\n const result = parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1])\r\n return result\r\n}"}, {"source_code": "\"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Main Function, write code here\r\n\r\nfunction main() {\r\n const length = readline()\r\n const arr = readline().split(' ')\r\n arr.sort()\r\n const result = arr[length - 1] - arr[0] + arr[length - 2] - arr[1]\r\n return result\r\n}\r\n"}, {"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const n = parseInt(input[index]);\n index++;\n const a = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n a,\n };\n testCases.push(testCase);\n }\n}\n\nconst attempt = (a, n) => {\n let leftMin = Infinity;\n let leftMax = -Infinity;\n const leftMins = [];\n const leftMaxs = [];\n for (let i = 0; i < n; i++) {\n const v = a[i];\n if (v < leftMin) leftMin = v;\n if (v > leftMax) leftMax = v;\n leftMins.push(leftMin);\n leftMaxs.push(leftMax);\n }\n let rightMin = Infinity;\n let rightMax = -Infinity;\n const rightMins = [];\n const rightMaxs = [];\n for (let i = n - 1; i >= 0; i--) {\n const v = a[i];\n if (v < rightMin) rightMin = v;\n if (v > rightMax) rightMax = v;\n rightMins.unshift(rightMin);\n rightMaxs.unshift(rightMax);\n }\n\n const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);\n const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);\n // console.log(leftMins);\n // console.log(leftMaxs);\n // console.log(leftDiffs);\n // console.log(rightMins);\n // console.log(rightMaxs);\n // console.log(rightDiffs);\n\n let result = 0;\n for (let i = 0; i < n - 1; i++) {\n const v = leftDiffs[i] + rightDiffs[i + 1];\n if (v > result) result = v;\n }\n return result;\n};\n\nfunction solution(testCase) {\n let { n, a } = testCase;\n // console.log(n, a);\n\n let maxi = -Infinity;\n let maxiIndex;\n let mini = Infinity;\n let miniIndex;\n a.forEach((v, i) => {\n if (v > maxi) {\n maxi = v;\n maxiIndex = i;\n }\n if (v < mini) {\n mini = v;\n miniIndex = i;\n }\n });\n\n let startWithMax = [...a];\n const toPushStartWithMax = startWithMax.splice(0, maxiIndex);\n startWithMax.push(...toPushStartWithMax);\n\n const resultStartWithMax = attempt(startWithMax, n);\n\n let endWithMax = [...a];\n const toPushEndWithMax = endWithMax.splice(maxiIndex + 1);\n endWithMax.push(...toPushEndWithMax);\n\n const resultEndWithMax = attempt(endWithMax, n);\n\n let startWithMin = [...a];\n const toPushStartWithMin = startWithMin.splice(0, miniIndex);\n startWithMin.push(...toPushStartWithMin);\n\n const resultStartWithMin = attempt(startWithMin, n);\n\n let endWithMin = [...a];\n const toPushEndWithMin = endWithMin.splice(miniIndex + 1);\n endWithMin.push(...toPushEndWithMin);\n\n const resultEndWithMin = attempt(endWithMin, n);\n\n // console.log(a);\n\n console.log(\n Math.max(\n resultStartWithMax,\n resultEndWithMax,\n resultStartWithMin,\n resultEndWithMin\n )\n );\n // console.log(\"--------\");\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const n = parseInt(input[index]);\n index++;\n const a = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n a,\n };\n testCases.push(testCase);\n }\n}\n\nconst attempt = (a, n) => {\n let leftMin = Infinity;\n let leftMax = -Infinity;\n const leftMins = [];\n const leftMaxs = [];\n for (let i = 0; i < n; i++) {\n const v = a[i];\n if (v < leftMin) leftMin = v;\n if (v > leftMax) leftMax = v;\n leftMins.push(leftMin);\n leftMaxs.push(leftMax);\n }\n let rightMin = Infinity;\n let rightMax = -Infinity;\n const rightMins = [];\n const rightMaxs = [];\n for (let i = n - 1; i >= 0; i--) {\n const v = a[i];\n if (v < rightMin) rightMin = v;\n if (v > rightMax) rightMax = v;\n rightMins.unshift(rightMin);\n rightMaxs.unshift(rightMax);\n }\n\n const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);\n const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);\n // console.log(leftMins);\n // console.log(leftMaxs);\n // console.log(leftDiffs);\n // console.log(rightMins);\n // console.log(rightMaxs);\n // console.log(rightDiffs);\n\n let result = 0;\n for (let i = 0; i < n - 1; i++) {\n const v = leftDiffs[i] + rightDiffs[i + 1];\n if (v > result) result = v;\n }\n return result;\n};\n\nfunction solution(testCase) {\n let { n, a } = testCase;\n // console.log(n, a);\n\n let maxi = -Infinity;\n let maxiIndex;\n let mini = Infinity;\n let miniIndex;\n a.forEach((v, i) => {\n if (v > maxi) {\n maxi = v;\n maxiIndex = i;\n }\n if (v < mini) {\n mini = v;\n miniIndex = i;\n }\n });\n\n let startWithMax = [...a];\n const toPushStartWithMax = startWithMax.splice(0, maxiIndex);\n startWithMax.push(...toPushStartWithMax);\n\n const resultStartWithMax = attempt(startWithMax, n);\n\n let endWithMax = [...a];\n const toPushEndWithMax = endWithMax.splice(maxiIndex + 1);\n endWithMax.push(...toPushEndWithMax);\n\n const resultEndWithMax = attempt(endWithMax, n);\n\n // console.log(a);\n\n console.log(Math.max(resultStartWithMax, resultEndWithMax));\n // console.log(\"--------\");\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}, {"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const n = parseInt(input[index]);\n index++;\n const a = input[index].split(\" \").map((item) => parseInt(item));\n const testCase = {\n n,\n a,\n };\n testCases.push(testCase);\n }\n}\n\nfunction solution(testCase) {\n let { n, a } = testCase;\n // console.log(n, a);\n\n let maxi = -Infinity;\n let maxiIndex;\n a.forEach((v, i) => {\n if (v > maxi) {\n maxi = v;\n maxiIndex = i;\n }\n });\n\n const toPush = a.splice(0, maxiIndex);\n a.push(...toPush);\n\n // console.log(a);\n\n let leftMin = Infinity;\n let leftMax = -Infinity;\n const leftMins = [];\n const leftMaxs = [];\n for (let i = 0; i < n; i++) {\n const v = a[i];\n if (v < leftMin) leftMin = v;\n if (v > leftMax) leftMax = v;\n leftMins.push(leftMin);\n leftMaxs.push(leftMax);\n }\n let rightMin = Infinity;\n let rightMax = -Infinity;\n const rightMins = [];\n const rightMaxs = [];\n for (let i = n - 1; i >= 0; i--) {\n const v = a[i];\n if (v < rightMin) rightMin = v;\n if (v > rightMax) rightMax = v;\n rightMins.unshift(rightMin);\n rightMaxs.unshift(rightMax);\n }\n\n const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);\n const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);\n // console.log(leftMins);\n // console.log(leftMaxs);\n // console.log(leftDiffs);\n // console.log(rightMins);\n // console.log(rightMaxs);\n // console.log(rightDiffs);\n\n let result = 0;\n for (let i = 0; i < n - 1; i++) {\n const v = leftDiffs[i] + rightDiffs[i + 1];\n if (v > result) result = v;\n }\n console.log(result);\n // console.log(\"--------\");\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}], "src_uid": "1e54530bc8cff81199b9cc1a6e51d638"} {"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, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-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 = w), 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 ≤ n ≤ 100) — 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 ≤ ai ≤ 100).", "output_spec": "Print the single number — 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": "print(function(n, a) {\n\tvar i, sum = 0,\n\t\tcnt = new Int32Array(105);\n\n\tfor (i = 0; i < n; i++)\n\t\t++cnt[a[i]];\n\n\tfor (i = 0; i < 105; i++)\n\t\tsum += cnt[i] >> 1;\n\n\treturn sum >> 1;\n\n}(+readline(), readline().split(' ').map(Number)));"}, {"source_code": ";(function () {\n\n\tprint(function () {\n\t\tvar n = +readline(), m = {}, r = 0;\n\t\treadline().split(' ').forEach(function (e) { m[e] = m[e] ? m[e] + 1 : 1; });\n\n\t\tfor (var k in m)\n\t\t\tif (m[k] > 1)\n\t\t\t\tr += Math.floor(m[k] / 2);\n\n\t\treturn Math.floor(r / 2);\n\t}());\n\n}).call(this);"}], "negative_code": [], "src_uid": "f9b56b3fddcd5db0d0671714df3f8646"} {"nl": {"description": "You are given $$$n$$$ numbers $$$a_1, a_2, \\dots, a_n$$$. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract $$$1$$$ from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to $$$1$$$, in other words, we want $$$a_1 \\cdot a_2$$$ $$$\\dots$$$ $$$\\cdot a_n = 1$$$. For example, for $$$n = 3$$$ and numbers $$$[1, -3, 0]$$$ we can make product equal to $$$1$$$ in $$$3$$$ coins: add $$$1$$$ to second element, add $$$1$$$ to second element again, subtract $$$1$$$ from third element, so that array becomes $$$[1, -1, -1]$$$. And $$$1\\cdot (-1) \\cdot (-1) = 1$$$.What is the minimum cost we will have to pay to do that?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$) — the numbers.", "output_spec": "Output a single number — the minimal number of coins you need to pay to make the product equal to $$$1$$$.", "sample_inputs": ["2\n-1 1", "4\n0 0 0 0", "5\n-5 -3 5 3 0"], "sample_outputs": ["2", "4", "13"], "notes": "NoteIn the first example, you can change $$$1$$$ to $$$-1$$$ or $$$-1$$$ to $$$1$$$ in $$$2$$$ coins.In the second example, you have to apply at least $$$4$$$ operations for the product not to be $$$0$$$.In the third example, you can change $$$-5$$$ to $$$-1$$$ in $$$4$$$ coins, $$$-3$$$ to $$$-1$$$ in $$$2$$$ coins, $$$5$$$ to $$$1$$$ in $$$4$$$ coins, $$$3$$$ to $$$1$$$ in $$$2$$$ coins, $$$0$$$ to $$$1$$$ in $$$1$$$ coin."}, "positive_code": [{"source_code": "function input() {\n return [\n parseInt(readline().trim()),\n readline()\n .trim()\n .split(\" \")\n .map(function(i) {\n return parseInt(i);\n })\n ];\n}\n\nfunction main() {\n // get input\n var read = input();\n var n = read[0];\n var values = read[1];\n\n var negative = Infinity;\n var positive = 0;\n\n values.forEach(function(v) {\n var _negative = negative,\n _positive = positive;\n positive = Math.min(\n _negative + Math.abs(v + 1),\n _positive + Math.abs(v - 1)\n );\n negative = Math.min(\n _negative + Math.abs(v - 1),\n _positive + Math.abs(v + 1)\n );\n });\n\n print(positive);\n}\n\nmain();\n"}, {"source_code": "(function() {\nvar INPUT = ``;\nvar OUTPUT = ``;\n \nvar main = function() {\"use strict\";\n // TODO\n var n = rdN();\n var A = rdArN();\n var res = 0;\n var sign = 1;\n var zC = 0;\n for (var i = 0; i < n; ++i) {\n if (A[i] > 0) {\n res += A[i] - 1;\n } else if (A[i] < 0) {\n res += -A[i] - 1;\n sign *= -1;\n } else {\n ++zC;\n }\n }\n if (zC > 0) {\n res += zC;\n } else {\n if (sign === -1) {\n res += 2;\n }\n }\n wr(res);\n};\n \nif(INPUT){INPUT=INPUT.split('\\n').reverse();\nreadline=()=>INPUT.pop();\nwrite=(...s)=>{OUTPUT+=[...s].join(' ')};\nprint=(...s)=>{write(...s);OUTPUT+='\\n'};}\nconst\nrdS=readline,\nrdN=()=>+rdS(),\nrdArS=()=>rdS().split(' '),\nrdArN=()=>rdArS().map(v=>+v),\nwr=write,\npr=print,\nprAr=(a)=>pr(...a),\nprOb=(o)=>pr(JSON.stringify(o,null,4)),\ncrAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},\ngetPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},\ndefineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});\ndefineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});\ndefineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});\n \nmain();\nreturn OUTPUT;\n})();"}, {"source_code": "var a = parseInt(readline().trim());var answ = 0;var numbers = readline().trim().split(\" \").map(function(x) { return parseInt(x); });var cnt = 0, cn = 0;for(var i = 0; i < numbers.length; i++){answ += Math.abs(numbers[i]);answ--;if(numbers[i]===0){answ++;cnt++;}if(numbers[i] < 0){cn++}}if(cn % 2 === 1 && cnt === 0)answ += 2;else answ += cnt;print(answ);"}, {"source_code": "\nfunction doStuff (data) {\n var x = data.split(' ');\n\n var solutionNrs = [];\n var coins = 0;\n var zeroPresent = false;\n for (var i = 0; i < numbers; i++) {\n var cur = x[i];\n if (cur == 0) {\n cur++;\n zeroPresent = true;\n solutionNrs.push(1);\n } else if (cur < 0) {\n cur *= -1;\n cur--;\n solutionNrs.push(-1);\n } else if (cur > 0) {\n cur--;\n solutionNrs.push(1);\n }\n coins += cur;\n }\n var endNrLogic = 1;\n solutionNrs.forEach( function (y) {\n endNrLogic *= y;\n });\n if (endNrLogic == 0) {\n coins += 2;\n } else if (endNrLogic == -1 && zeroPresent) {\n // coins--;\n } else if (endNrLogic == -1 && !zeroPresent) {\n coins += 2;\n }\n console.log(coins);\n};\nvar numbers;\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n numbers = lines[0];\n doStuff(lines[1]);\n});"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = \"\";\nlet input = \"\";\nlet input_currentline = 0;\n\nfunction readLine() {\n return input[input_currentline++];\n}\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n input = input_stdin.split(\"\\n\");\n main();\n});\n\n\n// your code goes here\nfunction main() {\n const N = Number(readLine());\n const n = readLine().split(' ').map(x=>+x);\n \n let ans = 0\n let minus1 = 0;\n let numZeros = 0;\n for (let i = 0; i < N; i ++) {\n let toMinus1 = Math.abs(n[i] + 1);\n let toPlus1 = Math.abs(n[i] - 1)\n ans += Math.min(toMinus1, toPlus1);\n if (toMinus1 < toPlus1) minus1++;\n if (n[i] === 0) numZeros++;\n }\n console.log(minus1%2 === 1 && numZeros === 0 ? ans + 2 : ans);\n}"}, {"source_code": "const processData = (lines) => {\ndebugger\n const [n, a] = lines\n\n const A = a.split(' ').map(n => Number(n))\n\n let coins = 0\n let sign = 1\n let closeTo = 2\n for (let i = 0; i < A.length; i++) {\n const el = A[i]\n if (el >= 1) coins += el - 1\n if (el <= -1) coins += Math.abs(el) - 1\n if (el === 0) {\n coins += 1\n closeTo = 0\n }\n sign = sign * (Math.sign(el) === 0 ? 1 : Math.sign(el))\n }\n if (sign < 0) {\n coins += closeTo\n }\n\n console.log(coins)\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let ans = 0;\n let minus = 0;\n let hasZero = false;\n const arr = d.split(\" \").map(Number);\n arr.sort((a, b) => a - b);\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n ans += Math.abs(arr[i] + 1);\n minus++;\n } else {\n if (arr[i] === 0) {\n hasZero = true;\n }\n ans += Math.abs(arr[i] - 1);\n }\n }\n\n if (minus % 2 !== 0 && !hasZero) {\n ans += 2;\n }\n\n console.log(ans);\n c++;\n});\n"}], "negative_code": [{"source_code": "function input() {\n return [\n parseInt(readline().trim()),\n readline()\n .trim()\n .split(\" \")\n .map(function(i) {\n return parseInt(i);\n })\n ];\n}\n\nfunction main() {\n // get input\n var read = input();\n var n = read[0];\n var values = read[1];\n\n var negative = 0;\n var positive = 0;\n\n values.forEach(function(v) {\n var _negative = negative,\n _positive = positive;\n positive = Math.min(\n _negative + Math.abs(v + 1),\n _positive + Math.abs(v - 1)\n );\n negative = Math.min(\n _negative + Math.abs(v - 1),\n _positive + Math.abs(v + 1)\n );\n });\n\n print(positive);\n}\n\nmain();\n"}, {"source_code": "var a = parseInt(readline().trim());var answ = 0;\nvar numbers = readline().trim().split(\" \").map(function(x) { return parseInt(x); });var cnt = 0, cn = 0;\nfor(var i = 0; i < numbers.length; i++){answ += Math.abs(numbers[i]);answ--;if(numbers[i]===0){answ++;cnt++;}if(numbers[i] < 0){cn++}}\nif(cn % 2 === 1 && cnt === 0)answ += 2;\nelse answ += cn + cnt;\nprint(answ);"}, {"source_code": "\nfunction doStuff (data) {\n var x = data.split(' ');\n\n var solutionNrs = [];\n var coins = 0;\n var zeroPresent = false;\n for (var i = 0; i < x.nr; i++) {\n var cur = x.numbers[i];\n if (cur == 0) {\n cur++;\n zeroPresent = true;\n solutionNrs.push(1);\n } else if (cur < 0) {\n cur *= -1;\n cur--;\n solutionNrs.push(-1);\n } else if (cur > 0) {\n cur--;\n solutionNrs.push(1);\n }\n coins += cur;\n }\n var endNrLogic = 1;\n solutionNrs.forEach( function (y) {\n endNrLogic *= y;\n });\n if (endNrLogic == 0) {\n coins += 2;\n } else if (endNrLogic == -1 && zeroPresent) {\n coins--;\n } else if (endNrLogic == -1 && !zeroPresent) {\n coins += 2;\n }\n console.log(coins);\n};\nvar numbers;\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n numbers = lines[0];\n doStuff(lines[1]);\n});"}, {"source_code": "\nfunction doStuff (data) {\n var x = data.split(' ');\n\n var solutionNrs = [];\n var coins = 0;\n var zeroPresent = false;\n for (var i = 0; i < numbers; i++) {\n var cur = x[i];\n if (cur == 0) {\n cur++;\n zeroPresent = true;\n solutionNrs.push(1);\n } else if (cur < 0) {\n cur *= -1;\n cur--;\n solutionNrs.push(-1);\n } else if (cur > 0) {\n cur--;\n solutionNrs.push(1);\n }\n coins += cur;\n }\n var endNrLogic = 1;\n solutionNrs.forEach( function (y) {\n endNrLogic *= y;\n });\n if (endNrLogic == 0) {\n coins += 2;\n } else if (endNrLogic == -1 && zeroPresent) {\n coins--;\n } else if (endNrLogic == -1 && !zeroPresent) {\n coins += 2;\n }\n console.log(coins);\n};\nvar numbers;\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n numbers = lines[0];\n doStuff(lines[1]);\n});"}, {"source_code": "\nfunction doStuff (data) {\n var x = data.split(' ');\n\n var solutionNrs = [];\n var coins = 0;\n var zeroPresent = false;\n for (var i = 0; i < x.nr; i++) {\n var cur = x.numbers[i];\n if (cur == 0) {\n cur++;\n zeroPresent = true;\n solutionNrs.push(1);\n } else if (cur < 0) {\n cur *= -1;\n cur--;\n solutionNrs.push(-1);\n } else if (cur > 0) {\n cur--;\n solutionNrs.push(1);\n }\n coins += cur;\n }\n var endNrLogic = 1;\n solutionNrs.forEach( function (y) {\n endNrLogic *= y;\n });\n if (endNrLogic == 0) {\n coins += 2;\n } else if (endNrLogic == -1 && zeroPresent) {\n coins--;\n } else if (endNrLogic == -1 && !zeroPresent) {\n coins += 2;\n }\n console.log(coins);\n};\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n doStuff(lines[0]);\n});"}, {"source_code": "\nfunction doStuff (x) {\n var solutionNrs = [];\n var coins = 0;\n var zeroPresent = false;\n for (var i = 0; i < x.nr; i++) {\n var cur = x.numbers[i];\n if (cur == 0) {\n cur++;\n zeroPresent = true;\n solutionNrs.push(1);\n } else if (cur < 0) {\n cur *= -1;\n cur--;\n solutionNrs.push(-1);\n } else if (cur > 0) {\n cur--;\n solutionNrs.push(1);\n }\n coins += cur;\n }\n var endNrLogic = 1;\n solutionNrs.forEach( function (y) {\n endNrLogic *= y;\n });\n if (endNrLogic == 0) {\n coins += 2;\n } else if (endNrLogic == -1 && zeroPresent) {\n coins--;\n } else if (endNrLogic == -1 && !zeroPresent) {\n coins += 2;\n }\n console.log(coins);\n};\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n doStuff(lines[0]);\n});"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = \"\";\nlet input = \"\";\nlet input_currentline = 0;\n\nfunction readLine() {\n return input[input_currentline++];\n}\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n input = input_stdin.split(\"\\n\");\n main();\n});\n\n\n// your code goes here\nfunction main() {\n const N = Number(readLine());\n const n = readLine().split(' ').map(x=>+x);\n \n let memo = [];\n\n const getCoins = (arr, res) => {\n if (arr.length===1) {\n return res === 1 ? Math.abs(arr[0] - 1) : Math.abs(arr[0] + 1);\n }\n if (memo.findIndex(x => x.id === arr.join(\"-\") && x.res === res) != -1) {\n return memo.find(x => x.id === arr.join(\"-\") && x.res === res).val;\n }\n let v = Math.min(getCoins(arr.slice(1), 1) + Math.abs(arr[0] - 1), getCoins(arr.slice(1), -1) + Math.abs(arr[0] + 1));\n memo.push({id:arr.join(\"-\"), res: res, val: v});\n return v;\n }\n \n console.log(getCoins(n, 1));\n \n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = \"\";\nlet input = \"\";\nlet input_currentline = 0;\n\nfunction readLine() {\n return input[input_currentline++];\n}\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n input = input_stdin.split(\"\\n\");\n main();\n});\n\n\n// your code goes here\nfunction main() {\n const N = Number(readLine());\n const n = readLine().split(' ').map(x=>+x);\n \n let ans = 0\n let minus1 = 0;\n for (let i = 0; i < N; i ++) {\n let toMinus1 = Math.abs(n[i] + 1);\n let toPlus1 = Math.abs(n[i] - 1)\n ans += Math.min(toMinus1, toPlus1);\n if (toMinus1 < toPlus1) minus1++;\n }\n console.log(minus1%2 === 0 ? ans : ans + 2);\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input_stdin = \"\";\nlet input = \"\";\nlet input_currentline = 0;\n\nfunction readLine() {\n return input[input_currentline++];\n}\n\nprocess.stdin.on('data', function (data) {\n input_stdin += data;\n});\n\nprocess.stdin.on('end', function () {\n input = input_stdin.split(\"\\n\");\n main();\n});\n\n\n// your code goes here\nfunction main() {\n const N = Number(readLine());\n const n = readLine().split(' ').map(x=>+x);\n \n let memo = [];\n\n const getCoins = (arr, res) => {\n if (arr.length===1) {\n return res === 1 ? Math.abs(arr - 1) : Math.abs(arr + 1);\n }\n if (memo.findIndex(x => x.id === arr.join(\"-\")) != -1) {\n return memo.find(x => x.id === arr.join(\"-\")).val;\n }\n let v = Math.min(getCoins(arr.slice(1), 1) + Math.abs(arr[0] - 1), getCoins(arr.slice(1), -1) + Math.abs(arr[0] + 1));\n memo.push({id:arr.join(\"-\"), val: v});\n return v;\n }\n \n console.log(getCoins(n, 1));\n \n}"}, {"source_code": "const processData = (lines) => {\n const [n, a] = lines\n\n const A = a.split(' ').map(n => Number(n))\n\n let coins = 0\n let sign = 1\n // let closeTo1 = 1\n for (let i = 0; i < A.length; i++) {\n if (A[i] > 1) coins += A[i] - 1\n if (A[i] < -1) coins += Math.abs(A[i]) - 1\n // if (Math.abs(A[i] - 1) < Math.abs(A[closeTo1] - 1)) closeTo1 = i\n sign = sign * Math.sign(A[i])\n }\n if (sign < 0) coins -= 2\n\n console.log(coins)\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})"}, {"source_code": "const processData = (lines) => {\n const [n, a] = lines\n\n const A = a.split(' ').map(n => Number(n))\n\n let coins = 0\n let sign = 1\n let closeTo = 2\n for (let i = 0; i < A.length; i++) {\n if (A[i] >= 1) coins += A[i] - 1\n if (A[i] <= -1) coins += Math.abs(A[i]) - 1\n if (A[i] === 0) {\n coins += 1\n closeTo = 0\n }\n sign = sign * Math.sign(A[i]) === 0 ? 1 : Math.sign(A[i])\n }\n if (sign < 0) {\n coins += closeTo\n }\n\n console.log(coins)\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})"}, {"source_code": "const processData = (lines) => {\n const [n, a] = lines\n \n const A = a.split(' ').map(n => Number(n))\n \n let coins = 0\n let sign = 1\n // let closeTo1 = 1\n for (let i = 0; i < A.length; i++) {\n if (A[i] > 1) coins += A[i] - 1\n if (A[i] < -1) coins += Math.abs(A[i]) - 1\n // if (Math.abs(A[i] - 1) < Math.abs(A[closeTo1] - 1)) closeTo1 = i\n sign = sign * Math.sign(A[i])\n }\n if (sign < 0) coins += 2\n \n console.log(coins)\n}\n \nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})"}, {"source_code": "const processData = (lines) => {\n const [n, a] = lines\n\n const A = a.split(' ').map(n => Number(n))\n\n let coins = 0\n let sign = 1\n let closeTo1 = 1\n for (let i = 0; i < A.length; i++) {\n if (A[i] >= 1) coins += A[i] - 1\n if (A[i] <= -1) coins += Math.abs(A[i]) - 1\n if (A[i] === 0) coins += 1\n if (Math.abs(A[i] - 1) < Math.abs(A[closeTo1] - 1)) closeTo1 = i\n sign = sign * Math.sign(A[i])\n }\n if (sign < 0) {\n if (A[closeTo1] <= -1) {\n coins += 2\n }\n if (A[closeTo1] >= 1) {\n coins += 2\n }\n // if (A[closeTo1] === 0) {\n // \n // }\n }\n\n console.log(coins)\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const { EOL } = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})"}], "src_uid": "3b3b2408609082fa5c3a0d55bb65d29a"} {"nl": {"description": "Madoka is going to enroll in \"TSUNS PTU\". But she stumbled upon a difficult task during the entrance computer science exam: A number is called good if it is a multiple of $$$d$$$. A number is called beatiful if it is good and it cannot be represented as a product of two good numbers. Notice that a beautiful number must be good.Given a good number $$$x$$$, determine whether it can be represented in at least two different ways as a product of several (possibly, one) beautiful numbers. Two ways are different if the sets of numbers used are different.Solve this problem for Madoka and help her to enroll in the best school in Russia!", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) — number of test cases. Below comes their description. Each test case consists of two integers $$$x$$$ and $$$d$$$, separated by a space ($$$2 \\leq x, d \\leq 10^9$$$). It is guaranteed that $$$x$$$ is a multiple of $$$d$$$.", "output_spec": "For each set of input data, output \"NO\" if the number cannot be represented in at least two ways. Otherwise, output \"YES\". You can output each letter in any case (for example, \"YES\", \"Yes\", \"yes\", \"yEs\", \"yEs\" will be recognized as a positive answer).", "sample_inputs": ["8\n\n6 2\n\n12 2\n\n36 2\n\n8 2\n\n1000 10\n\n2376 6\n\n128 4\n\n16384 4"], "sample_outputs": ["NO\nNO\nYES\nNO\nYES\nYES\nNO\nYES"], "notes": "NoteIn the first example, $$$6$$$ can be represented as $$$6$$$, $$$1 \\cdot 6$$$, $$$2 \\cdot 3$$$. But $$$3$$$ and $$$1$$$ are not a good numbers because they are not divisible by $$$2$$$, so there is only one way.In the second example, $$$12$$$ can be represented as $$$6 \\cdot 2$$$, $$$12$$$, $$$3 \\cdot 4$$$, or $$$3 \\cdot 2 \\cdot 2$$$. The first option is suitable. The second is— no, because $$$12$$$ is not beautiful number ($$$12 = 6 \\cdot 2$$$). The third and fourth are also not suitable, because $$$3$$$ is not good number.In the third example, $$$36$$$ can be represented as $$$18 \\cdot 2$$$ and $$$6 \\cdot 6$$$. Therefore it can be decomposed in at least two ways."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(x, d) {\r\n let count = 0;\r\n while (x % d === 0) {\r\n count++;\r\n x /= d;\r\n }\r\n if (count < 2) {\r\n console.log('NO');\r\n return;\r\n }\r\n for (let i = 2; i <= x / i; i++) {\r\n if (x % i === 0) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n if (count > 2) {\r\n for (let i = 2; i <= d / i; i++) {\r\n if (d % i === 0) {\r\n if (i === d / i) {\r\n if (i !== x) {\r\n console.log('YES');\r\n return;\r\n } else if (count > 3) {\r\n console.log('YES');\r\n return;\r\n }\r\n } else {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n console.log('NO');\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const [x, d] = (await read()).split(' ').map(Number);\r\n solve(x, d);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "function solve() {\r\n const [x, d] = readArray(Number);\r\n const count = countBeatyMul(x, d, 1);\r\n write(count > 1 ? 'YES' : 'NO');\r\n}\r\n\r\nfunction countBeatyMul(x, d, start) {\r\n if (x % d !== 0) {\r\n return 0;\r\n }\r\n if (isBeaty(x, d)) {\r\n return 1;\r\n }\r\n let ans = 0;\r\n for (let i = start; i <= Math.floor(Math.sqrt(x)); i++) {\r\n if (x % i !== 0) {\r\n continue;\r\n }\r\n const xDivI = Math.floor(x / i);\r\n if (xDivI < start) {\r\n continue;\r\n }\r\n if (isBeaty(i, d)) {\r\n ans += countBeatyMul(xDivI, d, i)\r\n }\r\n }\r\n return ans;\r\n}\r\n\r\nfunction isBeaty(x, d) {\r\n return x % d === 0 && x % (d * d) !== 0;\r\n}\r\n\r\nfunction init() {\r\n try {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n } catch (e) {\r\n write(e + e.stack);\r\n }\r\n}\r\n\r\nfunction modPow(a, n, mod) {\r\n let d = a;\r\n let curN = n;\r\n let ans = 1n;\r\n while(curN) {\r\n if (curN & 1n) {\r\n ans = modMul(ans, d, mod);\r\n }\r\n curN >>= 1n;\r\n d = modMul(d, d, mod);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction modMul(a, b, mod) {\r\n return (a * b) % mod;\r\n}\r\n\r\nfunction modSum(a, b, mod) {\r\n return (a + b) % mod;\r\n}\r\n\r\nfunction modDiff(a, b, mod) {\r\n return (a + mod - b) % mod;\r\n}\r\n\r\nfunction isZero(num) {\r\n if (typeof num === 'bigint') {\r\n return num === 0n;\r\n }\r\n return num === 0;\r\n}\r\nfunction div(a, b) {\r\n if (typeof a !== typeof b) {\r\n throw new Error('Different types on division');\r\n }\r\n if (typeof a === 'bigint') {\r\n return a / b;\r\n }\r\n return Math.floor(a / b);\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if (isZero(y)) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction lcm(x, y) {\r\n return div(x * y, gcd(x, y));\r\n}\r\n\r\nfunction allIndexOf(arr, value) {\r\n var index = arr.indexOf(value)\r\n var ans = [];\r\n while (index !== -1) {\r\n ans.push(index);\r\n index = arr.indexOf(value, index + 1);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction xor(a, b, k) {\r\n if (k === 2) {\r\n return a ^ b;\r\n }\r\n}\r\n\r\nfunction decToBin(num) {\r\n let n = num;\r\n const ans = [];\r\n while(n > 0) {\r\n ans.push(n & 1);\r\n n = (n >> 1);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction binToDec(binN) {\r\n let ans = 0;\r\n for (let i = binN.length - 1; i >= 0; i--) {\r\n ans = ((ans << 1) | binN[i]);\r\n }\r\n return ans;\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n \r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(x, d) {\r\n let count = 0;\r\n while (x % d === 0) {\r\n count++;\r\n x /= d;\r\n }\r\n if (count < 2) {\r\n console.log('NO');\r\n return;\r\n }\r\n for (let i = 2; i <= x / i; i++) {\r\n if (x % i === 0) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n if (count > 2) {\r\n for (let i = 2; i <= d / i; i++) {\r\n if (d % i === 0) {\r\n if (i === d / i) {\r\n if (i !== x) {\r\n console.log('YES');\r\n return;\r\n }\r\n } else {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n console.log('NO');\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const [x, d] = (await read()).split(' ').map(Number);\r\n solve(x, d);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(x, d) {\r\n let count = 0;\r\n while (x % d === 0) {\r\n count++;\r\n x /= d;\r\n }\r\n if (count < 2) {\r\n console.log('NO');\r\n return;\r\n }\r\n for (let i = 2; i <= x / i; i++) {\r\n if (x % i === 0) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n if (count > 2) {\r\n for (let i = 2; i <= d / i; i++) {\r\n if (count > 3) {\r\n if (d % i === 0) {\r\n console.log('YES');\r\n return;\r\n }\r\n } else {\r\n if (d % i === 0 && i !== x && d / i !== x) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n console.log('NO');\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const [x, d] = (await read()).split(' ').map(Number);\r\n solve(x, d);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(x, d) {\r\n let count = 0;\r\n while (x % d === 0) {\r\n count++;\r\n x /= d;\r\n }\r\n if (count < 2) {\r\n console.log('NO');\r\n return;\r\n }\r\n for (let i = 2; i <= x / i; i++) {\r\n if (x % i === 0) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n if (count > 2) {\r\n for (let i = 2; i <= d / i; i++) {\r\n if (count > 3) {\r\n if (d % i === 0) {\r\n console.log('YES');\r\n return;\r\n }\r\n } else {\r\n if (i !== x && d / i !== x) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n console.log('NO');\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const [x, d] = (await read()).split(' ').map(Number);\r\n solve(x, d);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(x, d) {\r\n let count = 0;\r\n while (x % d === 0) {\r\n count++;\r\n x /= d;\r\n }\r\n if (count < 2) {\r\n console.log('NO');\r\n return;\r\n }\r\n for (let i = 2; i <= x / i; i++) {\r\n if (x % i === 0) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n if (count > 2) {\r\n for (let i = 2; i <= d / i; i++) {\r\n if (d % i === 0 && i !== x && d / i !== x) {\r\n console.log('YES');\r\n return;\r\n }\r\n }\r\n }\r\n console.log('NO');\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const [x, d] = (await read()).split(' ').map(Number);\r\n solve(x, d);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "src_uid": "ee27020ca43546993b82357527585831"} {"nl": {"description": "Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \\leq x \\leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. ", "input_spec": "The first contains a single positive integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\\leq n \\leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \\ldots, ca_n$$$ ($$$1 \\leq ca_i \\leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \\ldots, cb_n$$$ ($$$1 \\leq cb_i \\leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a 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 a single integer — the highest possible beauty.", "sample_inputs": ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"], "sample_outputs": ["18\n10\n0"], "notes": "NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\\left|4-3 \\right|+\\left|3-5 \\right|+\\left|2-4 \\right|+\\left|5-2 \\right|+\\left|1-6 \\right|+\\left|6-1 \\right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\\left|2-2 \\right|+\\left|1-6 \\right|+\\left|3-3 \\right|+\\left|6-1 \\right|+\\left|4-4 \\right|+\\left|5-5 \\right|=10$$$."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b) {\r\n a = a.map(num => num - 1);\r\n b = b.map(num => num - 1);\r\n const p = [...new Array(n).keys()];\r\n const count = new Array(n).fill(1);\r\n const find = i => {\r\n if (p[i] !== i) p[i] = find(p[p[i]]);\r\n return p[i];\r\n };\r\n const union = (i, j) => {\r\n const ri = find(i),\r\n rj = find(j);\r\n if (ri !== rj) {\r\n p[rj] = ri;\r\n count[ri] += count[rj];\r\n }\r\n };\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] !== b[i]) union(a[i], b[i]);\r\n }\r\n const roots = new Set();\r\n for (let i = 0; i < n; i++) {\r\n roots.add(find(i));\r\n }\r\n let res = 0,\r\n l = 1,\r\n r = n;\r\n for (let i of roots) {\r\n let c = count[i];\r\n if (c === 1) continue;\r\n if (c & 1) c = c - 1;\r\n let nums = new Array(c).fill(0);\r\n for (let i = 0, j = c - 1; i < j; i++, j--) {\r\n if (i & 1) {\r\n nums[i] = r--;\r\n nums[j] = l++;\r\n } else {\r\n nums[i] = l++;\r\n nums[j] = r--;\r\n }\r\n }\r\n for (let i = 0; i < c; i++) {\r\n res += Math.abs(nums[(i + 1) % c] - nums[i]);\r\n }\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "//import { readline, print } from '@ip-algorithmics/codeforces-io';\r\nvar t = +readline();\r\nvar _loop_1 = function () {\r\n readline();\r\n var a = readline().split(' ').map(function (v) { return +v; });\r\n var b = readline().split(' ').map(function (v) { return +v; });\r\n var A = a.map(function (_, i) { return [a[i], b[i]]; });\r\n A.sort(function (a, b) { return a[0] - b[0]; });\r\n var count = 0;\r\n var i = 0;\r\n while (i < A.length) {\r\n var temp = i;\r\n while (A[i][0]) {\r\n A[i][0] = 0;\r\n i = A[i][1] - 1;\r\n count++;\r\n }\r\n count -= (count % 2);\r\n i = temp + 1;\r\n }\r\n print(count * (a.length - (count >> 1)));\r\n};\r\nwhile (t-- > 0) {\r\n _loop_1();\r\n}\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n\nlet stackRecursion = (fn, init_state)=>{\n let stack = [];\n let rec = (cb, a0, a1, a2)=>{\n let state = Object.assign({}, init_state);\n stack.push([state, cb, a0, a1, a2]);\n };\n return (cb, a0, a1, a2)=>{\n rec(cb, a0, a1, a2);\n while (stack.length){\n let [state, cb, a0, a1, a2] = stack[stack.length-1];\n let added = false;\n fn((cb, a0, a1, a2)=>{\n added = true;\n rec(cb, a0, a1, a2);\n }, state, a0, a1, a2);\n if (!added){\n cb(state);\n stack.pop();\n }\n }\n };\n};\n \nconst calc = ()=>{\n // READING:\n let [n] = ra();\n let A = ra();\n let B = ra();\n LT({n, A, B});\n // PROCESSING:\n let posB = new Array(n).fill(0);\n for (let i=0; i{\n if (visit.has(v)){\n return;\n }\n visit.add(v);\n cnt++;\n rec(()=>{}, posB[A[v]]);\n }, {});\n let c = 0;\n for (let i=0; i{}, i);\n c += cnt>>1;\n }\n return Math.floor((c*(n-c))*2);\n};\n "}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b) {\r\n a = a.map(num => num - 1);\r\n b = b.map(num => num - 1);\r\n const p = [...new Array(n).keys()];\r\n const count = new Array(n).fill(1);\r\n const find = i => {\r\n if (p[i] !== i) p[i] = find(p[p[i]]);\r\n return p[i];\r\n };\r\n const union = (i, j) => {\r\n const ri = find(i),\r\n rj = find(j);\r\n if (ri !== rj) {\r\n p[rj] = ri;\r\n count[ri] += count[rj];\r\n }\r\n };\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] !== b[i]) union(a[i], b[i]);\r\n }\r\n const roots = new Set();\r\n for (let i = 0; i < n; i++) {\r\n roots.add(find(i));\r\n }\r\n let res = 0,\r\n l = 1,\r\n r = n;\r\n for (let i of roots) {\r\n const c = count[i];\r\n if (c === 1) continue;\r\n if (c === 2) {\r\n res += (r - l) * 2;\r\n r--;\r\n l--;\r\n continue;\r\n }\r\n res += r - l;\r\n for (let i = 0; i < (c - 2) / 2; i++) {\r\n res += (r - l - 1) * 2;\r\n r--, l++;\r\n }\r\n res += r - l;\r\n r--, l++;\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a, b));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n\nlet stackRecursion = (fn, init_state)=>{\n let stack = [];\n let rec = (cb, a0, a1, a2)=>{\n let state = Object.assign({}, init_state);\n stack.push([state, cb, a0, a1, a2]);\n };\n return (cb, a0, a1, a2)=>{\n rec(cb, a0, a1, a2);\n while (stack.length){\n let [state, cb, a0, a1, a2] = stack[stack.length-1];\n let added = false;\n fn((cb, a0, a1, a2)=>{\n added = true;\n rec(cb, a0, a1, a2);\n }, state, a0, a1, a2);\n if (!added){\n cb(state);\n stack.pop();\n }\n }\n };\n};\n \nconst calc = ()=>{\n // READING:\n let [n] = ra();\n let A = ra();\n let B = ra();\n LT({n, A, B});\n // PROCESSING:\n let posB = new Array(n).fill(0);\n for (let i=0; i{\n if (visit.has(v)){\n return;\n }\n visit.add(v);\n cnt++;\n rec(()=>{}, posB[A[v]]);\n }, {});\n let c = 0;\n for (let i=0; i{}, i);\n c += cnt>>1;\n }\n return (c*(n-c))<<1;\n};\n "}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n \nconst calc = ()=>{\n // READING:\n let [n] = ra();\n let A = ra();\n let B = ra();\n LT({n, A, B});\n // PROCESSING:\n let nums = new Set();\n let posA = new Array(n).fill(0)\n let posB = new Array(n).fill(0)\n for (let i=0; ia-b)\n let l = 0, r = n-1;\n L(arr)\n let ans = 0;\n let i=0;\n let alloc = new Array(n).fill(-1);\n while (i=0 && valR>=0){\n ans += Math.abs(valL-valR);\n } else {\n if (valL==-1){\n if (Math.abs(l-valR)>Math.abs(r-valR)){\n alloc[A[i]] = l++;\n\n } else {\n alloc[A[i]] = r--;\n }\n } else {\n if (Math.abs(l-valL)>Math.abs(r-valL)){\n alloc[B[i]] = l++;\n } else {\n alloc[B[i]] = r--;\n }\n\n }\n ans += Math.abs(alloc[A[i]]-alloc[B[i]]);\n }\n i++;\n\n }\n return ans;\n};\n "}], "src_uid": "4bcaa910cce687f0881a36231aa1a2c8"} {"nl": {"description": "After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $$$n$$$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string $$$s$$$ of length $$$n$$$, where $$$s_i = \\texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \\texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $$$s_1$$$) and his goal is to get to the last crossroad (which corresponds to $$$s_n$$$).If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \\ldots, j-1$$$ there is a bus station, one can pay $$$a$$$ roubles for the bus ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the bus (it is not necessary to have a bus station at the $$$j$$$-th crossroad). Formally, paying $$$a$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \\texttt{A}$$$ for all $$$i \\le t < j$$$. If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \\ldots, j-1$$$ there is a tram station, one can pay $$$b$$$ roubles for the tram ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the tram (it is not necessary to have a tram station at the $$$j$$$-th crossroad). Formally, paying $$$b$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \\texttt{B}$$$ for all $$$i \\le t < j$$$.For example, if $$$s$$$=\"AABBBAB\", $$$a=4$$$ and $$$b=3$$$ then Petya needs: buy one bus ticket to get from $$$1$$$ to $$$3$$$, buy one tram ticket to get from $$$3$$$ to $$$6$$$, buy one bus ticket to get from $$$6$$$ to $$$7$$$. Thus, in total he needs to spend $$$4+3+4=11$$$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $$$s_n$$$) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the $$$n$$$-th crossroad. After the party he has left with $$$p$$$ roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad $$$i$$$ to go on foot the first, so he has enough money to get from the $$$i$$$-th crossroad to the $$$n$$$-th, using only tram and bus tickets.", "input_spec": "Each test contains one or more 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 consists of three integers $$$a, b, p$$$ ($$$1 \\le a, b, p \\le 10^5$$$) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has. The second line of each test case consists of one string $$$s$$$, where $$$s_i = \\texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \\texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad ($$$2 \\le |s| \\le 10^5$$$). It is guaranteed, that the sum of the length of strings $$$s$$$ by all test cases in one test doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print one number — the minimal index $$$i$$$ of a crossroad Petya should go on foot. The rest of the path (i.e. from $$$i$$$ to $$$n$$$ he should use public transport).", "sample_inputs": ["5\n2 2 1\nBB\n1 1 1\nAB\n3 2 8\nAABBBBAABB\n5 3 4\nBBBBB\n2 1 1\nABABAB"], "sample_outputs": ["2\n1\n3\n1\n6"], "notes": null}, "positive_code": [{"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n\n\n\n\n\n function foo (data, ost) {\n let [a, b, p] = data;\n\n const substr = [];\n const substrInd = [];\n\n for (let i=0; i= 0; k--) {\n if (substr[k] === 'B' && p >= b) {\n p = p - b;\n } else if (substr[k] === 'A' && p >= a) {\n p = p - a;\n } else {\n return substrInd[k+1];\n }\n }\n\n return 1;\n }\n\n let testCount = 1;\n let answer = '';\n while(testCount <= +lines[0]) {\n let data = lines[testCount*2-1].split(\" \").map(Number);\n let ost = lines[testCount*2].split(\"\");\n let result = foo(data, ost);\n answer += result +\"\\n\";\n testCount++;\n }\n console.log(answer);\n})"}, {"source_code": "\"use strict\";\nexports.__esModule = true;\nfunction main(rawInput) {\n var lines = rawInput.split(\"\\n\");\n var tests = parseInt(lines.shift(), 10);\n for (var i = 0; i < tests; i++) {\n var _a = lines.shift().split(\" \").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];\n var stations = lines.shift().trim().split(\"\");\n var res = stations.map(function (v) { return 0; });\n costs(stations, busCost, tramCost, res);\n var j = 0;\n while (j < stations.length && res[j] > balance) {\n j++;\n }\n // console.log(j === stations.length ? j - 1 : j + 1);\n console.log(j + 1);\n }\n}\nfunction costs(stations, busCost, tramCost, res) {\n res[stations.length - 1] = 0;\n res[stations.length - 2] = stations[stations.length - 2] === \"A\" ? busCost : tramCost;\n for (var i = stations.length - 3; i >= 0; i--) {\n if (stations[i] !== stations[i + 1]) {\n res[i] = res[i + 1] + (stations[i] === \"A\" ? busCost : tramCost);\n }\n else {\n res[i] = res[i + 1];\n }\n }\n}\n(function () {\n var s = \"\";\n process.stdin.on(\"data\", function (d) { return s += d; });\n process.stdin.on(\"end\", function () { return main(s); });\n})();\n"}], "negative_code": [{"source_code": "function main(rawInput) {\n var lines = rawInput.split(\"\\n\");\n var tests = parseInt(lines.shift(), 10);\n for (var i = 0; i < tests; i++) {\n var _a = lines.shift().split(\" \").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];\n var stations = lines.shift().split(\"\");\n var j = 0;\n var found = false;\n while (j < stations.length && !found) {\n if (remainingBalance(j, stations, busCost, tramCost, balance) >= 0) {\n found = true;\n }\n else {\n j++;\n }\n }\n console.log(j + 1);\n }\n}\nvar dm = {};\nfunction remainingBalance(pos, stations, busCost, tramCost, balance) {\n if (pos === void 0) { pos = 0; }\n if (balance < 0) {\n dm[pos + \"-\" + balance] = -1;\n return -1;\n }\n if (pos === stations.length - 1) {\n dm[pos + \"-\" + balance] = balance;\n return balance;\n }\n var newPos = pos;\n var fst = stations[pos];\n while (stations[newPos] === fst) {\n if (newPos === stations.length) {\n // dm[newPos + \"-\" + balance] = balance;\n return balance;\n }\n newPos++;\n }\n return remainingBalance(newPos, stations, busCost, tramCost, balance - (fst === \"A\" ? busCost : tramCost));\n}\n(function () {\n var s = \"\";\n process.stdin.on(\"data\", function (d) { return s += d; });\n process.stdin.on(\"end\", function () { return main(s); });\n})();\n"}, {"source_code": "\"use strict\";\nexports.__esModule = true;\nfunction main(rawInput) {\n var lines = rawInput.split(\"\\n\");\n var tests = parseInt(lines.shift(), 10);\n for (var i = 0; i < tests; i++) {\n var _a = lines.shift().split(\" \").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];\n var stations = lines.shift().split(\"\");\n var res = stations.map(function (v) { return 0; });\n costs(stations, busCost, tramCost, res);\n var j = 0;\n while (j < stations.length - 1 && res[j] > balance) {\n j++;\n }\n // console.log(j === stations.length ? j - 1 : j + 1, balance, busCost, tramCost, res, stations);\n console.log(j + 1);\n }\n}\nfunction costs(stations, busCost, tramCost, res) {\n res[stations.length - 1] = 0;\n res[stations.length - 2] = stations[stations.length - 2] === \"A\" ? busCost : tramCost;\n for (var i = stations.length - 3; i >= 0; i--) {\n if (stations[i] !== stations[i + 1]) {\n res[i] = res[i + 1] + (stations[i] === \"A\" ? busCost : tramCost);\n }\n else {\n res[i] = res[i + 1];\n }\n }\n}\n(function () {\n var s = \"\";\n process.stdin.on(\"data\", function (d) { return s += d; });\n process.stdin.on(\"end\", function () { return main(s); });\n})();\n"}, {"source_code": "\"use strict\";\nexports.__esModule = true;\nfunction main(rawInput) {\n var lines = rawInput.split(\"\\n\");\n var tests = parseInt(lines.shift(), 10);\n for (var i = 0; i < tests; i++) {\n var _a = lines.shift().split(\" \").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];\n var stations = lines.shift().split(\"\");\n var res = stations.map(function (v) { return 0; });\n costs(stations, busCost, tramCost, res);\n var j = 0;\n while (j < stations.length - 1 && res[j] > balance) {\n j++;\n }\n // console.log(j === stations.length ? j - 1 : j + 1, balance, busCost, tramCost, res, stations);\n console.log(j);\n }\n}\nfunction costs(stations, busCost, tramCost, res) {\n res[stations.length - 1] = 0;\n res[stations.length - 2] = stations[stations.length - 2] === \"A\" ? busCost : tramCost;\n for (var i = stations.length - 3; i >= 0; i--) {\n if (stations[i] !== stations[i + 1]) {\n res[i] = res[i + 1] + (stations[i] === \"A\" ? busCost : tramCost);\n }\n else {\n res[i] = res[i + 1];\n }\n }\n}\n(function () {\n var s = \"\";\n process.stdin.on(\"data\", function (d) { return s += d; });\n process.stdin.on(\"end\", function () { return main(s); });\n})();\n"}, {"source_code": "\"use strict\";\nexports.__esModule = true;\nfunction main(rawInput) {\n var lines = rawInput.split(\"\\n\");\n var tests = parseInt(lines.shift(), 10);\n for (var i = 0; i < tests; i++) {\n var _a = lines.shift().split(\" \").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];\n var stations = lines.shift().split(\"\");\n var res = stations.map(function (v) { return 0; });\n costs(stations, busCost, tramCost, res);\n var j = 0;\n while (j < stations.length - 1 && res[j] > balance) {\n j++;\n }\n console.log(j === stations.length ? j - 1 : j + 1);\n // console.log(j+1);\n }\n}\nfunction costs(stations, busCost, tramCost, res) {\n res[stations.length - 1] = 0;\n res[stations.length - 2] = stations[stations.length - 2] === \"A\" ? busCost : tramCost;\n for (var i = stations.length - 3; i >= 0; i--) {\n if (stations[i] !== stations[i + 1]) {\n res[i] = res[i + 1] + (stations[i] === \"A\" ? busCost : tramCost);\n }\n else {\n res[i] = res[i + 1];\n }\n }\n}\n(function () {\n var s = \"\";\n process.stdin.on(\"data\", function (d) { return s += d; });\n process.stdin.on(\"end\", function () { return main(s); });\n})();\n"}, {"source_code": "\"use strict\";\nexports.__esModule = true;\nfunction main(rawInput) {\n var lines = rawInput.split(\"\\n\");\n var tests = parseInt(lines.shift(), 10);\n for (var i = 0; i < tests; i++) {\n var _a = lines.shift().split(\" \").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];\n var stations = lines.shift().split(\"\");\n var res = stations.map(function (v) { return 0; });\n costs(stations, busCost, tramCost, res);\n var j = 0;\n while (j < stations.length && res[j] > balance) {\n j++;\n }\n console.log(j === stations.length ? j - 1 : j + 1);\n // console.log(j+1);\n }\n}\nfunction costs(stations, busCost, tramCost, res) {\n res[stations.length - 1] = 0;\n res[stations.length - 2] = stations[stations.length - 2] === \"A\" ? busCost : tramCost;\n for (var i = stations.length - 3; i >= 0; i--) {\n if (stations[i] !== stations[i + 1]) {\n res[i] = res[i + 1] + (stations[i] === \"A\" ? busCost : tramCost);\n }\n else {\n res[i] = res[i + 1];\n }\n }\n}\n(function () {\n var s = \"\";\n process.stdin.on(\"data\", function (d) { return s += d; });\n process.stdin.on(\"end\", function () { return main(s); });\n})();\n"}], "src_uid": "0e4c297fcacdd0a304310882cd7c8a44"} {"nl": {"description": "There is a programming language in which every program is a non-empty sequence of \"<\" and \">\" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. Current character pointer (CP); Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right.We repeat the following steps until the first moment that CP points to somewhere outside the sequence. If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. If CP is pointing to \"<\" or \">\" then the direction of DP changes to \"left\" or \"right\" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is \"<\" or \">\" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated.It's obvious the every program in this language terminates after some steps.We have a sequence s1, s2, ..., sn of \"<\", \">\" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl, sl + 1, ..., sr as an independent program in this language.", "input_spec": "The first line of input contains two integers n and q (1 ≤ n, q ≤ 105) — represents the length of the sequence s and the number of queries. The second line contains s, a sequence of \"<\", \">\" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces. The next q lines each contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the i-th query.", "output_spec": "For each query print 10 space separated integers: x0, x1, ..., x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input.", "sample_inputs": ["7 4\n1>3>22<\n1 3\n4 7\n7 7\n1 7"], "sample_outputs": ["0 1 0 1 0 0 0 0 0 0\n2 2 2 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n2 3 2 1 0 0 0 0 0 0"], "notes": null}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar data = tokenizeIntegers(readline()),\n\t\tn = data[0], qNum = data[1],\n\t\ts = trim(readline());\n\tfor (var q = 0; q < qNum; ++q) {\n\t\tdata = tokenizeIntegers(readline());\n\t\tvar left = data[0]-1, right = data[1]-1,\n\t\t\ttape = s.substring(left, right+1).split(''),\n\t\t\tlen = right-left+1,\n\t\t\tpos = 0, dir = +1,\n\t\t\tcounts = new Array(10);\n\t\tfor (var i = 0; i < 10; ++i) {\n\t\t\tcounts[i] = 0;\n\t\t}\n\t\tfunction display() {\n\t\t\tprint(tape.join('') + ' pos = '+pos);\n\t\t}\n\t\twhile (pos >= 0 && pos < len) {\n\t\t\tvar value = tape[pos];\n\t\t\tif (value != '<' && value != '>') {\n\t\t\t\tpos += dir;\n\t\t\t\tcounts[value] += 1;\n\t\t\t\ttape[pos-dir] -= 1;\n\t\t\t\tif (tape[pos-dir] == -1) {\n\t\t\t\t\ttape.splice(pos-dir, 1);\n\t\t\t\t\tlen -= 1;\n\t\t\t\t\tif (dir == 1) {\n\t\t\t\t\t\tpos -= 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdir = (value == '<' ? -1 : 1);\n\t\t\t\tpos += dir;\n\t\t\t\tif (pos != -1 && pos != len) {\n\t\t\t\t\tif (tape[pos] == '<' || tape[pos] == '>') {\n\t\t\t\t\t\ttape.splice(pos-dir, 1);\n\t\t\t\t\t\tlen -= 1;\n\t\t\t\t\t\tif (dir == 1) {\n\t\t\t\t\t\t\tpos -= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprint(counts.join(' '));\n\t}\n}\n\nmain();\n"}], "negative_code": [], "src_uid": "5c3fc40b18c9b3e58c49d9f6e44ea28c"} {"nl": {"description": "Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings \"pop\", \"noon\", \"x\", and \"kkkkkk\" are palindromes, while strings \"moon\", \"tv\", and \"abab\" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has $$$n$$$ distinct strings of equal length $$$m$$$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m \\le 50$$$) — the number of strings and the length of each string. Next $$$n$$$ lines contain a string of length $$$m$$$ each, consisting of lowercase Latin letters only. All strings are distinct.", "output_spec": "In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.", "sample_inputs": ["3 3\ntab\none\nbat", "4 2\noo\nox\nxo\nxx", "3 5\nhello\ncodef\norces", "9 4\nabab\nbaba\nabcd\nbcde\ncdef\ndefg\nwxyz\nzyxw\nijji"], "sample_outputs": ["6\ntabbat", "6\noxxxxo", "0", "20\nababwxyzijjizyxwbaba"], "notes": "NoteIn the first example, \"battab\" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string."}, "positive_code": [{"source_code": "var palindromicPairs = {}\nvar palindromicStrings = []\nvar head = [], tail = [];\nvar input = []\nvar input1 = readline().split(' ').map((val)=>{\n return parseInt(val)\n})\nfor (var m = 0; m < input1[0];m++){\n input.push(readline())\n}\ninput.forEach((val)=>{\n var interim = val.split('').reverse().join('')\n if (interim == val){\n palindromicStrings.push(val)\n }\n else {\n if (!palindromicPairs.hasOwnProperty(val)){\n palindromicPairs[interim] = val\n }\n else{\n head.push(interim)\n tail.push(val)\n }\n }\n})\nvar res = head.join('');\nres += (palindromicStrings.length > 0) ? palindromicStrings[0] + tail.reverse().join('') : tail.reverse().join('')\nif (head.length >0 || palindromicStrings.length>0){\n print(res.length)\n print(res)\n}\nelse{\n print(0);\n print(' ')\n}\n\n"}, {"source_code": "Main();\nfunction myout(t){print(t);}//standard output\nfunction next(){return readline();}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す\n//6:1文字に分割 7:1文字に分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map((a)=>Number(a));case 6:return i.split(\"\");case 7:return i.split(\"\").map((a)=>Number(a));case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main() {\n var one = myconv(next(),4);\n var N = one[0];\n var M = one[1];\n var list = new Array(N);\n var output = \"\";\n for(var i = 0; i < N; i++){\n list[i] = next();\n }\n for(var i = 0; i < N; i++){\n var check = myconv(list[i],6);\n var isKaibun = true;\n //kaibun check\n for(var j = 0; j < M; j++){\n if(check[j] != check[M - j - 1]){\n isKaibun = false;\n break;\n }\n }\n if(isKaibun){\n output = list[i];\n list.splice(i,1);\n break;\n }\n }\n \n for(var i = 0; i < list.length; i++){\n var tmp = myconv(list[i],6);\n var inverse = \"\";\n //myout(tmp);\n for(var j = 0; j < M; j++){\n inverse += tmp[M - j - 1];\n }\n if(list.indexOf(inverse) != -1 && list.indexOf(inverse) != i){\n output = myconv(tmp,0) + output + inverse;\n //myout(list.length);\n list.splice(i,1);\n list.splice(list.indexOf(inverse),1);\n //myout(list.length);\n i -= 1;\n }\n }\n myout(output.length);\n myout(output);\n \n \n \n}"}, {"source_code": "function reversed(first, second)\n{\n var ans = true;\n for(var i = 0; i < first.length; i++)\n {\n if (first[i] != second[first.length - 1 - i])\n {\n ans = false;\n break;\n }\n }\n return ans;\n}\n\nfunction pal(str)\n{\n var half = Math.floor(str.length / 2);\n var ans = true;\n for(var i = 0; i < half; i++)\n if (str[i] != str[str.length - 1 - i])\n {\n ans = false;\n break;\n }\n return ans;\n}\n\nvar input = readline().split(\" \").map(function(x) { return parseInt(x); }); \nvar n = input[0];\nvar m = input[1];\n\nvar arr = [];\nwhile(n--)\n arr.push(readline());\n\nvar taked = Array.apply(null, Array(arr.length)).map(Number.prototype.valueOf,0);\n\nvar count = 0;\nfor(var i = 0; i < arr.length - 1; i++)\n{\n if (taked[i] != 0)\n continue;\n\n for(var j = i + 1; j < arr.length; j++)\n {\n if (taked[j] != 0)\n continue;\n \n if (reversed(arr[i], arr[j]))\n {\n taked[i] = j; \n taked[j] = -1;\n count += 2;\n }\n }\n}\n\nvar center = -1;\nfor(var i = 0; i < arr.length; i++)\n if (taked[i] == 0)\n if (pal(arr[i]))\n {\n count++;\n center = i;\n break;\n }\n\nvar ans = \"\";\nif (center != -1)\n ans = arr[center];\n\nfor(var i = 0; i < arr.length - 1; i++)\n if (taked[i] > 0)\n ans = arr[i] + ans + arr[taked[i]];\n\nprint(count * m)\nprint(ans)"}], "negative_code": [{"source_code": "var palindromicPairs = {};\nvar palindromicStrings = [];\nvar head = [], tail = [];\nvar input = [];\nvar input1 = readline().split(' ').map((val)=>{\n return parseInt(val)\n})\nfor (var m = 0; m < input1[0];m++){\n input.push(readline())\n}\ninput.forEach((val)=>{\n var interim = val.split('').reverse().join('')\n if (interim == val){\n palindromicStrings.push(val)\n }\n else {\n if (!palindromicPairs.hasOwnProperty(val)){\n palindromicPairs[interim] = val\n }\n else{\n head.push(interim)\n tail.push(val)\n }\n }\n})\nvar res = head.join('')+palindromicStrings[0]+tail.reverse().join('')\nif (head.length >0 || palindromicStrings.length>0){\n print(res.length)\n print(res)\n}\nelse{\n print(0);\n print(' ')\n}"}, {"source_code": "function reversed(first, second)\n{\n var ans = true;\n for(var i = 0; i < first.length; i++)\n {\n if (first[i] != second[first.length - 1 - i])\n {\n ans = false;\n break;\n }\n }\n return ans;\n}\n\nfunction pal(str)\n{\n var half = Math.floor(str.length / 2);\n var ans = true;\n for(var i = 0; i < half; i++)\n if (str[i] != str[str.length - 1 - i])\n {\n ans = false;\n break;\n }\n return ans;\n}\n\nvar input = readline().split(\" \").map(function(x) { return parseInt(x); }); \nvar n = input[0];\nvar m = input[1];\n\nvar arr = [];\nwhile(n--)\n arr.push(readline());\n\nvar taked = Array.apply(null, Array(arr.length)).map(Number.prototype.valueOf,0);\n\nvar count = 0;\nfor(var i = 0; i < arr.length - 1; i++)\n{\n if (taked[i] != 0)\n continue;\n\n for(var j = i + 1; j < arr.length; j++)\n {\n if (taked[j] != 0)\n continue;\n \n if (reversed(arr[i], arr[j]))\n {\n taked[i] = j; \n taked[j] = -1;\n count += 2;\n }\n }\n}\n\nvar center = -1;\nfor(var i = 0; i < arr.length; i++)\n if (taked[i] == 0)\n if (pal(arr[i]))\n {\n count++;\n center = i;\n }\n\nvar ans = \"\";\nif (center != -1)\n ans = arr[center];\n\nfor(var i = 0; i < arr.length - 1; i++)\n if (taked[i] > 0)\n ans = arr[i] + ans + arr[taked[i]];\n\nprint(count * m)\nprint(ans)"}], "src_uid": "554115bec46bb436a0a1ddf8c05a2d08"} {"nl": {"description": "One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of K participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.", "input_spec": "The first line contains five non-negative integers NS, NM, NL, NXL, NXXL not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer K (1 ≤ K ≤ 1000) which represents the number of participants. The next K lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that NS + NM + NL + NXL + NXXL ≥ K.", "output_spec": "For each contestant, print a line containing the size of the T-shirt he/she got.", "sample_inputs": ["1 0 2 0 1\n3\nXL\nXXL\nM"], "sample_outputs": ["XXL\nL\nL"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nlet ss = readline().split(' ').map(v => parseInt(v))\nlet N = +readline()\nlet s\n\nlet res = []\nwhile (s = readline()) {\n switch (s) {\n case 'S': s = 0; break\n case 'M': s = 1; break\n case 'L': s = 2; break\n case 'XL': s = 3; break\n case 'XXL': s = 4; break\n }\n\n let sts = [0, 1, -1, 2, -2, 3, -3, 4, -4, 5, -5]\n for (let j = 0; j < sts.length; j++) {\n if (ss[s + sts[j]]) {\n ss[s + sts[j]]--\n res.push(s + sts[j])\n break\n }\n }\n}\n\nres = res.map(v => {\n switch (v) {\n case 0: return 'S'\n case 1: return 'M'\n case 2: return 'L'\n case 3: return 'XL'\n case 4: return 'XXL'\n }\n})\n\nres.forEach(v => print(v))"}, {"source_code": "'use strict';\n\n/*let input = `1 0 2 0 1\n3\nXL\nXXL\nM`.split('\\n');\nfunction print(output) {\n\tconsole.log(output);\n}\nfunction readline() {\n\treturn input.shift();\n}*/\n\n//code\n\nvar storage = readline().split(' ').map(Number);\nvar n = Number(readline());\nvar sizes = [\"S\", \"M\", \"L\", \"XL\", \"XXL\"];\nfor (var i = 0; i < n; i++) {\n\tvar preference = sizes.indexOf(readline());\n\tvar j = 0;\n\twhile (true) {\n\t\tvar index = preference + Math.ceil(j / 2) * (j % 2 === 0 ? -1 : 1);\n\t\tif (index < storage.length && index >= 0 && storage[index] !== 0) {\n\t\t\tprint(sizes[index]);\n\t\t\tstorage[index]--;\n\t\t\tbreak;\n\t\t}\n\t\tj++;\n\t}\n}\n"}, {"source_code": "var n = readline().split(' ').map(Number);\nvar ans = ['S', 'M', 'L', 'XL', 'XXL'];\nvar k = +readline();\nnext: for (var i=1; i<=k; i++){\n\tvar p = readline();\n\tif (p == 'S') p = [0, 1, 2, 3, 4];\n\tif (p == 'M') p = [1, 2, 0, 3, 4];\n\tif (p == 'L') p = [2, 3, 1, 4, 0];\n\tif (p == 'XL') p = [3, 4, 2, 1, 0];\n\tif (p == 'XXL') p = [4, 3, 2, 1, 0];\n\tfor (var j=0; j<=4; j++){\n\t\tif (n[p[j]] != 0) {\n\t\t\tn[p[j]]--;\n\t\t\tprint (ans[p[j]]);\n\t\t\tcontinue next;\n\t\t}\n\t}\n}"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar N, indicator = 0, stock = {};\nrl.on('line', (input) => {\n if (indicator == 0) {\n let temp = input.split(\" \").map(item => parseInt(item));\n let S = temp[0], M = temp[1], L = temp[2], XL = temp[3], XXL = temp[4];\n stock = {\n \"S\": S,\n \"M\": M,\n \"L\": L,\n \"XL\": XL,\n \"XXL\": XXL\n };\n indicator++;\n }\n else if (indicator == 1) {\n N = parseInt(input);\n indicator++;\n }\n else {\n switch (input) {\n case \"S\":\n if (stock[\"S\"]) {\n console.log(\"S\");\n stock[\"S\"]--;\n }\n else if (stock[\"M\"]) {\n console.log(\"M\");\n stock[\"M\"]--;\n }\n else if (stock[\"L\"]) {\n console.log(\"L\");\n stock[\"L\"]--;\n }\n else if (stock[\"XL\"]) {\n console.log(\"XL\");\n stock[\"XL\"]--;\n }\n else {\n console.log(\"XXL\");\n stock[\"XXL\"]--;\n }\n break;\n\n case \"M\":\n if (stock[\"M\"]) {\n console.log(\"M\");\n stock[\"M\"]--;\n }\n else if (stock[\"L\"]) {\n console.log(\"L\");\n stock[\"L\"]--;\n }\n else if (stock[\"S\"]) {\n console.log(\"S\");\n stock[\"S\"]--;\n }\n else if (stock[\"XL\"]) {\n console.log(\"XL\");\n stock[\"XL\"]--;\n }\n else {\n console.log(\"XXL\");\n stock[\"XXL\"]--;\n }\n break;\n\n case \"L\":\n if (stock[\"L\"]) {\n console.log(\"L\");\n stock[\"L\"]--;\n }\n else if (stock[\"XL\"]) {\n console.log(\"XL\");\n stock[\"XL\"]--;\n }\n else if (stock[\"M\"]) {\n console.log(\"M\");\n stock[\"M\"]--;\n }\n else if (stock[\"XXL\"]) {\n console.log(\"XXL\");\n stock[\"XXL\"]--;\n }\n else {\n console.log(\"S\");\n stock[\"S\"]--;\n }\n break;\n\n case \"XL\":\n if (stock[\"XL\"]) {\n console.log(\"XL\");\n stock[\"XL\"]--;\n }\n else if (stock[\"XXL\"]) {\n console.log(\"XXL\");\n stock[\"XXL\"]--;\n }\n else if (stock[\"L\"]) {\n console.log(\"L\");\n stock[\"L\"]--;\n }\n else if (stock[\"M\"]) {\n console.log(\"M\");\n stock[\"M\"]--;\n }\n else {\n console.log(\"S\");\n stock[\"S\"]--;\n }\n break;\n\n default:\n if (stock[\"XXL\"]) {\n console.log(\"XXL\");\n stock[\"XXL\"]--;\n }\n else if (stock[\"XL\"]) {\n console.log(\"XL\");\n stock[\"XL\"]--;\n }\n else if (stock[\"L\"]) {\n console.log(\"L\");\n stock[\"L\"]--;\n }\n else if (stock[\"M\"]) {\n console.log(\"M\");\n stock[\"M\"]--;\n }\n else {\n console.log(\"S\");\n stock[\"S\"]--;\n }\n break;\n }\n }\n});"}, {"source_code": "const readline = require(\"readline\");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nvar findName = function (index) {\n switch (index) {\n case 0:\n return \"S\";\n break;\n case 1:\n return \"M\";\n break;\n case 2:\n return \"L\";\n break;\n case 3:\n return \"XL\";\n break;\n default:\n return \"XXL\";\n break;\n }\n};\nvar search = function (index) {\n if (cont[index] > 0) {\n console.log(findName(index));\n cont[index]--;\n } else if (index < 4 && cont[index + 1] > 0) {\n console.log(findName(index + 1));\n cont[index + 1]--;\n } else if (index > 0 && cont[index - 1] > 0) {\n console.log(findName(index - 1));\n cont[index - 1]--;\n } else if (index < 3 && cont[index + 2] > 0) {\n console.log(findName(index + 2));\n cont[index + 2]--;\n } else if (index > 1 && cont[index - 2] > 0) {\n console.log(findName(index - 2));\n cont[index - 2]--;\n } else if (index < 2 && cont[index + 3] > 0) {\n console.log(findName(index + 3));\n cont[index + 3]--;\n } else if (index > 2 && cont[index - 3] > 0) {\n console.log(findName(index - 3));\n cont[index - 3]--;\n } else if (index < 1 && cont[index + 4] > 0) {\n console.log(findName(index + 4));\n cont[index + 4]--;\n } else {\n console.log(findName(index - 4));\n cont[index - 4]--;\n }\n};\n\nvar cont = [],\n indicator = 0,\n n;\n/*\nwhile(true){\n string input = Console.ReadLine();\n}\n\n*/\n\nrl.on(\"line\", (input) => {\n if (indicator == 0) {\n cont = input.split(\" \").map((item) => parseInt(item));\n indicator++;\n } else if (indicator == 1) {\n n = parseInt(input);\n indicator++;\n } else {\n switch (input) {\n case \"S\":\n search(0);\n break;\n\n case \"M\":\n search(1);\n break;\n case \"L\":\n search(2);\n break;\n case \"XL\":\n search(3);\n break;\n default:\n search(4);\n break;\n }\n }\n});\n"}], "negative_code": [], "src_uid": "3c9d1de13e21ed16a7e5cbd2d67f4ce7"} {"nl": {"description": "You are given a rectangular grid with $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{ij}$$$ written in it.You can perform the following operation any number of times (possibly zero): Choose any two adjacent cells and multiply the values in them by $$$-1$$$. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations.You are interested in $$$X$$$, the sum of all the numbers in the grid. What is the maximum $$$X$$$ you can achieve with these operations?", "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$$$,$$$m$$$ ($$$2 \\le n$$$, $$$m \\le 10$$$). The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-100\\leq a_{ij}\\le 100$$$).", "output_spec": "For each testcase, print one integer $$$X$$$, the maximum possible sum of all the values in the grid after applying the operation as many times as you want.", "sample_inputs": ["2\n2 2\n-1 1\n1 1\n3 4\n0 -1 -2 -3\n-1 -2 -3 -4\n-2 -3 -4 -5"], "sample_outputs": ["2\n30"], "notes": "NoteIn the first test case, there will always be at least one $$$-1$$$, so the answer is $$$2$$$. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: $$$2\\times 1 + 3\\times2 + 3\\times 3 + 2\\times 4 + 1\\times 5 = 30$$$."}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [rowLen, colLen] = readLine().split(\" \").map(Number);\n let [sum, min, countMinus] = [0, Infinity, 0];\n for (let row = 0; row < rowLen; row++) {\n readLine()\n .split(\" \")\n .map((n) => {\n n = parseInt(n);\n if (n < 0) countMinus++;\n sum += Math.abs(n);\n min = Math.min(min, Math.abs(n));\n return n;\n });\n }\n if (countMinus % 2 === 1) sum -= 2 * min;\n\n console.log(sum);\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n B();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction gcd(x, y) {\n if ((typeof x !== 'number') || (typeof y !== 'number')) \n return false;\n x = Math.abs(x);\n y = Math.abs(y);\n while(y) {\n var t = y;\n y = x % y;\n x = t;\n }\n return x;\n }\n\nfunction B(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [n,m] = ti(readline().split(' '));\n let mat = new Array(n);\n for(let i = 0; i < n; i++){\n mat[i] = ti(readline().split(' '));\n }\n\n for(let i = 0; i < n; i++){\n for(let j = 1; j < m; j++){\n if(mat[i][j] < 0 && mat[i][j-1] < 0){\n mat[i][j] = -1*mat[i][j];\n mat[i][j-1] = -1*mat[i][j-1];\n }\n }\n }\n\n for(let i = 0; i < m; i++){\n for(let j = 1; j < n; j++){\n if(mat[j][i] < 0 && mat[j-1][i] < 0){\n mat[j][i] *= -1;\n mat[j-1][i] *= -1;\n }\n }\n }\n\n let count = 0;\n let min = 99999999999;\n let sum = 0;\n for(let i = 0; i < n; i++){\n for(let j = 0; j < m; j++){\n if(mat[i][j] < 0){\n count += 1;\n }\n\n min = Math.min(min, Math.abs(mat[i][j]));\n sum += Math.abs(mat[i][j]);\n }\n }\n\n if(count % 2 === 0){\n console.log(sum);\n }else{\n console.log(sum-2*min);\n }\n }\n}"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [rowLen, colLen] = readLine().split(\" \").map(Number);\n let [sum, min, foundMinus] = [0, Infinity, false];\n for (let row = 0; row < rowLen; row++) {\n readLine()\n .split(\" \")\n .map((n) => {\n n = parseInt(n);\n if (!foundMinus && n < 0) foundMinus = true;\n sum += Math.abs(n);\n min = Math.min(min, Math.abs(n));\n return n;\n });\n }\n if (foundMinus) sum -= 2 * min;\n\n console.log(sum);\n }\n}\n"}], "src_uid": "7fce446de3b01aff8f4aa420a92a096d"} {"nl": {"description": "You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \\le p_i \\le n$$$, $$$0 \\le c_i \\le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.", "output_spec": "In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.", "sample_inputs": ["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"], "sample_outputs": ["1 2 4", "-1", "5"], "notes": "NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way: "}, "positive_code": [{"source_code": "const readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction readLines(number, cb) {\n const lines = [];\n rl.on('line', function(line) {\n lines.push(line);\n if (lines.length === number) {\n rl.close();\n cb(lines);\n }\n });\n};\n\nfunction readLines(cb) {\n const lines = [];\n let read;\n\n rl.on('line', function(line) {\n if (!read) {\n read = parseInt(line);\n } else {\n lines.push(line);\n }\n if (lines.length === read) {\n rl.close();\n cb(lines);\n }\n });\n};\nreadLines(doIt);\n\nfunction doIt(lines) {\n const tree = [];\n lines.forEach(item => {\n tree.push(item.split(\" \").map(x => parseInt(x))); \n });\n tree.forEach(item => {\n let p = item[0];\n let c = item[1];\n if (c === 0 && p!==-1 && tree[p-1][1] ===1) {\n tree[p-1].push(0);\n }\n });\n const out = [];\n tree.forEach((item, idx)=>{\n if (item.length==2 && item[1] === 1)\n out.push(idx+1);\n })\n if (out.length === 0)\n console.log(-1);\n else\n console.log(out.join(' '));\n}"}], "negative_code": [{"source_code": "const readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction readLines(number, cb) {\n const lines = [];\n rl.on('line', function(line) {\n lines.push(line);\n if (lines.length === number) {\n rl.close();\n cb(lines);\n }\n });\n};\n\nfunction readLines(cb) {\n const lines = [];\n let read;\n\n rl.on('line', function(line) {\n if (!read) {\n read = parseInt(line);\n } else {\n lines.push(line);\n }\n if (lines.length === read) {\n rl.close();\n cb(lines);\n }\n });\n};\nreadLines(doIt);\n\nfunction doIt(lines) {\n const tree = [];\n lines.forEach(item => {\n tree.push(item.split(\" \").map(x => parseInt(x))); \n });\n tree.forEach(item => {\n let p = item[0];\n let c = item[1];\n if (c === 0 && p!==-1 && tree[p-1][1] ===1) {\n tree[p-1][1] = 0;\n }\n });\n const out = [];\n tree.forEach((item, idx)=>{\n if (item[1] === 1)\n out.push(idx+1);\n })\n if (out.length === 0)\n console.log(-1);\n else\n console.log(out.join(' '));\n}"}, {"source_code": "const readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction readLines(number, cb) {\n const lines = [];\n rl.on('line', function(line) {\n lines.push(line);\n if (lines.length === number) {\n rl.close();\n cb(lines);\n }\n });\n};\n\nfunction readLines(cb) {\n const lines = [];\n let read;\n\n rl.on('line', function(line) {\n if (!read) {\n read = parseInt(line);\n } else {\n lines.push(line);\n }\n if (lines.length === read) {\n rl.close();\n cb(lines);\n }\n });\n};\nreadLines(doIt);\n\nfunction doIt(lines) {\n const tree = [];\n lines.forEach(item => {\n tree.push(item.split(\" \").map(x => parseInt(x))); \n });\n console.log(lines)\n tree.forEach(item => {\n let p = item[0];\n let c = item[1];\n if (c === 0 && p!==-1 && tree[p-1][1] ===1) {\n tree[p-1][1] = 0;\n }\n });\n const out = [];\n tree.forEach((item, idx)=>{\n if (item[1] === 1)\n out.push(idx+1);\n })\n if (out.length === 0)\n console.log(-1);\n else\n console.log(out.join(' '));\n}"}], "src_uid": "1b975c5a13a2ad528b668a7c68c089f6"} {"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 — 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 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house. ", "output_spec": "Print n integers a1, a2, ..., an, 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": "readline();\n\nvar line = readline();\n\nvar heights = line.split(\" \");\n\nvar n = heights.length;\n\nvar maxRight = new Array(n);\n\nmaxRight[n - 1] = 0;\n\nvar neededFloors = [];\n\nfor (var i = n - 2; i >= 0; i--) {\n maxRight[i] = Math.max(maxRight[i + 1], heights[i + 1]);\n}\n\nfor (var i = 0; i < n; i++) {\n var difference = maxRight[i] - heights[i];\n neededFloors.push(heights[i] > maxRight[i]? 0 : difference + 1);\n}\n\nprint(neededFloors.join(\" \"));"}, {"source_code": "var n = readline();\nvar houses = readline().split(\" \");\n\nvar max = -1, L = houses.length, result = new Array(n);\nfor (var i = L-1; i>=0; --i) {\n var T = houses[i];\n result[i] = T > max ? 0 : max - T + 1;\n max = Math.max(T, max);\n}\n\nprint(result.join(\" \"));\n"}, {"source_code": "readline();\nvar houses = readline().split(\" \");\n\nvar max = -1, L = houses.length, result = [];\nfor (var i = L-1; i>=0; --i) {\n var T = houses[i];\n result.push(T > max ? 0 : max - T + 1);\n max = Math.max(T, max);\n}\n\nresult.reverse();\nprint(result.join(\" \"));\n"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = n - 1;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 0; i--)\n{\n\n\tif(houses[i] > houses[indexmax])\n\t{\n\t\tindexmax = i;\n\t\textrafloors.unshift(0);\n\t}\n\telse if(houses[i] == houses[indexmax])\n\t{\n\t\tif(i == indexmax)\n\t\t\textrafloors.unshift(0);\n\t\telse\n\t\t\textrafloors.unshift(1);\n\t}\n\telse\n\t\textrafloors.unshift(houses[indexmax] - houses[i] + 1);\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var numeric = readline(),\n\t\tfloor = readline().split(' '),\n\t\tresult = [0];\n\nfor (; floor.length > 1; ) {\n\tvar last_floor = +floor[floor.length - 1],\n\t\t\tprev_floor = +floor[floor.length - 2];\n\t\n\tif (prev_floor > last_floor) {\n\t\tresult.unshift(0);\n\t\tfloor.splice(floor.length - 1, 1);\n\t} else {\n\t\tif (last_floor === prev_floor) {\n\t\t\tresult.unshift(1);\n\t\t\tfloor.splice(floor.length - 1, 1);\n\t\t} else {\n\t\t\tresult.unshift( (last_floor - prev_floor) + 1 );\n\t\tfloor.splice(floor.length - 2, 1);\n\t\t}\n\t}\n}\n\n//result.splice(0,1);\nprint(result.join(' '));"}, {"source_code": "var numeric = readline(),\n\t\tfloor = readline().split(' '),\n\t\tresult = [0];\n\nfor (; floor.length; ) {\n\tvar last_floor = +floor[floor.length - 1],\n\t\t\tprev_floor = +floor[floor.length - 2];\n\t\n\tif (prev_floor > last_floor) {\n\t\tresult.unshift(0);\n\t\tfloor.pop();\n\t} else {\n\t\tif (last_floor === prev_floor) {\n\t\t\tresult.unshift(1);\n\t\t\tfloor.pop();\n\t\t} else {\n\t\t\tresult.unshift( (last_floor - prev_floor) + 1 );\n\t\tfloor.splice(floor.length - 2, 1);\n\t\t}\n\t}\n}\n\nresult.splice(0,1);\nprint(result.join(' '));"}, {"source_code": "var numeric = readline(),\n\t\tfloor = readline().split(' '),\n\t\tresult = [0];\n\nfor (; floor.length; ) {\n\tvar last_floor = +floor[floor.length - 1],\n\t\t\tprev_floor = +floor[floor.length - 2];\n\t\n\tif (prev_floor > last_floor) {\n\t\tresult.unshift(0);\n\t\tfloor.splice(floor.length - 1, 1);\n\t} else {\n\t\tif (last_floor === prev_floor) {\n\t\t\tresult.unshift(1);\n\t\t\tfloor.splice(floor.length - 1, 1);\n\t\t} else {\n\t\t\tresult.unshift( (last_floor - prev_floor) + 1 );\n\t\tfloor.splice(floor.length - 2, 1);\n\t\t}\n\t}\n}\n\nresult.splice(0,1);\nprint(result.join(' '));"}, {"source_code": "/******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n\n\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(1);\n\tvar List = __webpack_require__(2);\n\tvar n = parseInt(readline());\n\tvar xs = List.map(parseInt, readline().split(' '));\n\tvar result = [];\n\tvar highest = 0;\n\tfor (var i = xs.length - 1; i >= 0; i--) {\n\t result.push(Prelude_1.max(highest + 1, xs[i]) - xs[i]);\n\t highest = Prelude_1.max(highest, xs[i]);\n\t}\n\tresult = List.reverse(result);\n\tprint(result.join(\" \"));\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction min(a, b) {\n\t return a < b ? a : b;\n\t}\n\texports.min = min;\n\tfunction max(a, b) {\n\t return a < b ? b : a;\n\t}\n\texports.max = max;\n\tfunction curry(f) {\n\t return function (x) { return function (y) { return f(x, y); }; };\n\t}\n\texports.curry = curry;\n\tfunction uncurry(f) {\n\t return function (x, y) { return f(x)(y); };\n\t}\n\texports.uncurry = uncurry;\n\tfunction id(x) {\n\t return x;\n\t}\n\texports.id = id;\n\tfunction constant(x) {\n\t return function (_) { return x; };\n\t}\n\texports.constant = constant;\n\tfunction flip(f) {\n\t return function (y) { return function (x) { return f(x)(y); }; };\n\t}\n\texports.flip = flip;\n\tfunction flip2(f) {\n\t return function (y, x) { return f(x, y); };\n\t}\n\texports.flip2 = flip2;\n\tfunction compose(g, f) {\n\t return function (x) { return g(f(x)); };\n\t}\n\texports.compose = compose;\n\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(1);\n\tfunction add(xs, ys) {\n\t return xs.concat(ys);\n\t}\n\texports.add = add;\n\tfunction head(xs) {\n\t return xs[0];\n\t}\n\texports.head = head;\n\tfunction last(xs) {\n\t return xs[xs.length - 1];\n\t}\n\texports.last = last;\n\tfunction tail(xs) {\n\t return xs.slice(1);\n\t}\n\texports.tail = tail;\n\tfunction init(xs) {\n\t return xs.slice(0, xs.length - 1);\n\t}\n\texports.init = init;\n\tfunction map(f, xs) {\n\t var result = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t result[i] = f(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.map = map;\n\tfunction reverse(xs) {\n\t return xs.slice().reverse();\n\t}\n\texports.reverse = reverse;\n\tfunction intersperse(x, xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = new Array(xs.length + xs.length - 1);\n\t for (var i = 0; i + 1 < xs.length; i++) {\n\t result[i + i] = xs[i];\n\t result[i + i + 1] = x;\n\t }\n\t result[result.length - 1] = xs[xs.length - 1];\n\t return result;\n\t}\n\texports.intersperse = intersperse;\n\tfunction intercalate(xs, xss) {\n\t return concat(intersperse(xs, xss));\n\t}\n\texports.intercalate = intercalate;\n\tfunction foldl(f, initial, xs) {\n\t var result = initial;\n\t for (var i = 0; i < xs.length; i++) {\n\t result = f(result, xs[i]);\n\t }\n\t return result;\n\t}\n\texports.foldl = foldl;\n\tfunction foldr(f, initial, xs) {\n\t var result = initial;\n\t for (var i = xs.length - 1; i >= 0; i--) {\n\t result = f(xs[i], result);\n\t }\n\t return result;\n\t}\n\texports.foldr = foldr;\n\tfunction concat(xss) {\n\t var total = sum(map(function (xs) { return xs.length; }, xss));\n\t var result = new Array(total);\n\t var m = 0;\n\t for (var i = 0; i < xss.length; i++) {\n\t var xs = xss[i];\n\t for (var j = 0; j < xs.length; j++) {\n\t result[m++] = xs[j];\n\t }\n\t }\n\t return result;\n\t}\n\texports.concat = concat;\n\tfunction sum(xs) {\n\t var result = 0;\n\t for (var i = 0; i < xs.length; i++) {\n\t result += xs[i];\n\t }\n\t return result;\n\t}\n\texports.sum = sum;\n\tfunction product(xs) {\n\t var result = 1;\n\t for (var i = 0; i < xs.length; i++) {\n\t result *= xs[i];\n\t }\n\t return result;\n\t}\n\texports.product = product;\n\tfunction maximum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result < xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.maximum = maximum;\n\tfunction minimum(xs) {\n\t var result = xs[0];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (result > xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.minimum = minimum;\n\tfunction replicate(n, x) {\n\t var result = new Array(n);\n\t for (var i = 0; i < result.length; i++) {\n\t result[i] = x;\n\t }\n\t return result;\n\t}\n\texports.replicate = replicate;\n\tfunction take(n, xs) {\n\t return xs.slice(0, n);\n\t}\n\texports.take = take;\n\tfunction drop(n, xs) {\n\t return xs.slice(n);\n\t}\n\texports.drop = drop;\n\tfunction splitAt(n, xs) {\n\t return [take(n, xs), drop(n, xs)];\n\t}\n\texports.splitAt = splitAt;\n\tfunction takeWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(0, i);\n\t }\n\t }\n\t return xs.slice();\n\t}\n\texports.takeWhile = takeWhile;\n\tfunction dropWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(i);\n\t }\n\t }\n\t return [];\n\t}\n\texports.dropWhile = dropWhile;\n\tfunction group(xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = [];\n\t var last = [xs[0]];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (last[0] === xs[i]) {\n\t last.push(xs[i]);\n\t }\n\t else {\n\t result.push(last);\n\t last = [xs[i]];\n\t }\n\t }\n\t result.push(last);\n\t return result;\n\t}\n\texports.group = group;\n\tfunction filter(f, xs) {\n\t var result = [];\n\t for (var i = 0; i < xs.length; i++) {\n\t if (f(xs[i]))\n\t result.push(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.filter = filter;\n\tfunction zip(xs, ys) {\n\t var n = Prelude_1.min(xs.length, ys.length);\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = [xs[i], ys[i]];\n\t }\n\t return result;\n\t}\n\texports.zip = zip;\n\tfunction unzip(xs) {\n\t var r1 = new Array(xs.length);\n\t var r2 = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t r1[i] = xs[i][0];\n\t r2[i] = xs[i][1];\n\t }\n\t return [r1, r2];\n\t}\n\texports.unzip = unzip;\n\n\n/***/ }\n/******/ ]);"}, {"source_code": "var n = readline();\nvar h = readline().split(\" \");\nvar res = [];\nvar flag;\n// for(var i = 0; i < n; i++){\n// \tvar max = parseInt(h[i]);\n// \tfor(var j = i+1; j < n; j++){\n// \t\tflag = (parseInt(h[j]) == max) ? 1 : 0;\n// \t\tmax = (parseInt(h[j]) > max) ? parseInt(h[j]) : max;\n// \t}\n// \tvar r = (max == parseInt(h[i])) ? (flag) ? 1 : 0 : (max - parseInt(h[i]) + 1);\n// \tres.push(r);\n// }\n// print(res.join(' '));\nres = [];\nvar max = -1;\nfor(var i = n-1; i >= 0; i--){\n\tif(parseInt(h[i]) > max){\n\t\tmax = parseInt(h[i]);\n\t\tflag = 1;\n\t}\n\telse\n\t\tflag = 0;\n\tvar r = (flag) ? 0 : (max - parseInt(h[i]) + 1);\n\tres.push(r);\n}\nprint(res.reverse().join(' '));"}, {"source_code": "var n = parseInt(readline());\nvar input = readline().split(' ').map(function (item) {\n\treturn parseInt(item);\n})\nvar result = [];\ninput.reduceRight(function (prev, curr) {\n\tif(curr > prev){\n\t\tresult.push(0);\n\t} else if (curr === prev) {\n\t\tresult.push(1);\n\t} else {\n\t\tresult.push(prev - curr + 1);\n\t}\n\treturn Math.max(prev, curr);\n}, 0)\nresult = result.reverse();\nprint(result.join(' '));"}, {"source_code": "n = +readline();\nh = readline().split(\" \").map(Number);\n\n\nm = [];\nm[n] = h[n] = 0;\n\nfor (var i = n-1; i >= 0; --i) {\n\t//write(i + \" = \" + h[i+1] + \", \" + m[i+1] + \"\\n\");\n\tm[i] = Math.max(h[i+1], m[i+1]);\n}\n\n\nanswer = \"\";\nfor (var i = 0; i < n; i++) {\n\tif (m[i] >= h[i]) {\n\t\tanswer += (m[i]+1 - h[i]) + \" \";\n\t} else {\n\t\tanswer += \"0 \";\n\t}\n}\n\nwrite(answer);"}], "negative_code": [{"source_code": "readline();\n\nvar line = readline();\n\nvar heights = line.split(\" \");\n\nvar n = heights.length;\n\nvar maxRight = new Array(n);\n\nmaxRight[n - 1] = 0;\n\nvar neededFloors = [];\n\nfor (var i = n - 2; i >= 0; i--) {\n maxRight[i] = Math.max(maxRight[i + 1], heights[i + 1]);\n}\n\nfor (var i = 0; i < n; i++) {\n var difference = maxRight[i] - heights[i];\n neededFloors.push(heights[i] > maxRight[i]? 0 : difference);\n}\n\nprint(neededFloors.join(\" \"));"}, {"source_code": "readline();\n\nvar line = readline();\n\nvar heights = line.split(\" \");\n\nvar n = heights.length;\n\nvar maxRight = new Array(n);\n\nmaxRight[n - 1] = 0;\n\nvar neededFloors = [];\n\nfor (var i = n - 2; i >= 0; i--) {\n maxRight[i] = Math.max(maxRight[i - 1], heights[i - 1]);\n}\n\nfor (var i = 0; i < n; i++) {\n var difference = maxRight[i] - heights[i];\n neededFloors.push(heights[i] > maxRight[i]? 0 : difference);\n}\n\nprint(neededFloors.join(\" \"));"}, {"source_code": "readline();\n\nvar line = readline();\n\nvar heights = line.split(\" \");\n\nvar n = heights.length;\n\nvar maxRight = new Array(n);\n\nmaxRight[n - 1] = 0;\n\nvar neededFloors = [];\n\nfor (var i = n - 2; i >= 0; i--) {\n maxRight[i] = Math.max(maxRight[i - 1], heights[i - 1]);\n}\n\nfor (var i = n - 1; i >= 0; i--) {\n var difference = maxRight[i] - heights[i];\n neededFloors.push(heights[i] < maxRight[i]? difference : 0);\n}\n\nprint(neededFloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = 0;\nvar extrafloors = [];\n\nfor(var i = n; i >= 1; i--)\n{\n\tif(houses[i] > houses[indexmax])\n\t\textrafloors.unshift(houses[indexmax] + 1 - houses[i]);\n\telse\n\t{\n\t\textrafloors.unshift(0);\n\t\tindexmax = i;\n\t}\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = n - 1;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 0; i--)\n{\n\tif(houses[i] >= houses[indexmax])\n\t{\n\t\textrafloors.unshift(0);\n\t\tindexmax = i;\n\t}\n\telse\n\t\textrafloors.unshift(houses[indexmax] - houses[i] + 1);\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = 0;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 1; i--)\n{\n\tif(houses[i] > houses[indexmax])\n\t\textrafloors.unshift(houses[indexmax] + 1 - houses[i]);\n\telse\n\t{\n\t\textrafloors.unshift(0);\n\t\tindexmax = i;\n\t}\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar max = 0;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 0; i--)\n{\n\tif(houses[i] < max)\n\t\textrafloors.unshift(max - houses[i] + 1);\n\telse\n\t{\n\t\textrafloors.unshift(0);\n\t\tmax = houses[i];\n\t}\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = n - 1;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 0; i--)\n{\n\tif(houses[i] > houses[indexmax])\n\t\textrafloors.unshift(houses[indexmax] + 1 - houses[i]);\n\telse\n\t{\n\t\textrafloors.unshift(0);\n\t\tindexmax = i;\n\t}\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = n - 1;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 0; i--)\n{\n\tif(houses[i] < houses[indexmax])\n\t\textrafloors.unshift(houses[indexmax] + 1 - houses[i]);\n\telse\n\t{\n\t\textrafloors.unshift(0);\n\t\tindexmax = i;\n\t}\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = n - 1;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 0; i--)\n{\n\tif(houses[i] < houses[indexmax])\n\t\textrafloors.unshift(houses[indexmax] - houses[i] + 1);\n\telse\n\t{\n\t\textrafloors.unshift(0);\n\t\tindexmax = i;\n\t}\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var n = parseInt(readline());\nvar houses = readline().split(' ').map(function(c){ return parseInt(c); });\nvar indexmax = n - 1;\nvar extrafloors = [];\n\nfor(var i = n - 1; i >= 0; i--)\n{\n\tif(houses[i] > houses[indexmax])\n\t{\n\t\textrafloors.unshift(0);\n\t\tindexmax = i;\n\t}\n\telse\n\t\textrafloors.unshift(houses[indexmax] - houses[i] + 1);\n}\n\nprint(extrafloors.join(\" \"));"}, {"source_code": "var numeric = readline(),\n\t\tfloor = readline().split(' '),\n\t\tresult = [0];\n\n\nfor (; floor.length; ) {\n\tvar last_floor = +floor[floor.length - 1],\n\t\t\tprev_floor = +floor[floor.length - 2];\n\t\n\tif (prev_floor > last_floor) {\n\t\tresult.unshift(0);\n\t\tfloor.splice(floor.length - 1, 1);\n\t} else {\n\t\tif (last_floor === prev_floor) {\n\t\t\tresult.unshift(0);\n\t\t\tfloor.splice(floor.length - 1, 1);\n\t\t} else {\n\t\t\tresult.unshift( (last_floor - prev_floor) + 1 );\n\t\tfloor.splice(floor.length - 2, 1);\n\t\t}\n\t}\n}\nresult.splice(0,1);\nprint(result.join(' '));"}, {"source_code": "var numeric = readline(),\n\t\tfloor = readline().split(' '),\n\t\tresult = [0];\n\nfor (; floor.length; ) {\n\tvar last_floor = +floor[floor.length - 1],\n\t\t\tprev_floor = +floor[floor.length - 2];\n\t\n\tif (prev_floor > last_floor) {\n\t\tresult.unshift(0);\n\t\tfloor.splice(floor.length - 1, 1);\n\t} else {\n\t\tif (last_floor === prev_floor) {\n\t\t\tresult.unshift(0);\n\t\t\tfloor.splice(floor.length - 1, 1);\n\t\t} else {\n\t\t\tresult.unshift( (last_floor - prev_floor) + 1 );\n\t\tfloor.splice(floor.length - 2, 1);\n\t\t}\n\t}\n}\n\nresult.splice(0,1);\nprint(result.join(' '));"}, {"source_code": "var numeric = readline(),\n\t\tfloor = readline().split(' '),\n\t\tresult = [0];\n\n\nfor (; floor.length; ) {\n\tvar last_floor = +floor[floor.length - 1],\n\t\t\tprev_floor = floor[floor.length - 2];\n\t\n\tif (prev_floor > last_floor) {\n\t\tresult.unshift(0);\n\t\tfloor.splice(floor.length - 1, 1);\n\t} else {\n\t\tif (last_floor == prev_floor) {\n\t\t\tresult.unshift(0);\n\t\t\tfloor.splice(floor.length - 1, 1);\n\t\t} else {\n\t\t\tresult.unshift(last_floor + 1 - prev_floor);\n\t\tfloor.splice(floor.length - 2, 1);\n\t\t}\n\t}\n}\nresult.splice(0,1);\nprint(result.join(' '));"}, {"source_code": "var numeric = readline(),\n\t\tfloor = readline().split(' '),\n\t\tresult = [0];\n\nfor (; floor.length > 0; ) {\n\tvar last_floor = +floor[floor.length - 1],\n\t\t\tprev_floor = +floor[floor.length - 2];\n\t\n\tif (prev_floor > last_floor) {\n\t\tresult.unshift(0);\n\t\tfloor.splice(floor.length - 1, 1);\n\t} else {\n\t\tif (last_floor === prev_floor) {\n\t\t\tresult.unshift(1);\n\t\t\tfloor.splice(floor.length - 1, 1);\n\t\t} else {\n\t\t\tresult.unshift( (last_floor - prev_floor) + 1 );\n\t\tfloor.splice(floor.length - 2, 1);\n\t\t}\n\t}\n}\n\n//result.splice(0,1);\nprint(result.join(' '));"}, {"source_code": "var n = parseInt(readline());\nvar input = readline().split(' ').map(function (item) {\n\treturn parseInt(item);\n})\nvar max = input.reduce(function (prev, curr) {\n\treturn Math.max(prev, curr);\n}, 0)\nprint(input.map(function (item) {\n\treturn (item === max) ? 0 : max - item + 1;\n}).join(' '));"}, {"source_code": "var n = parseInt(readline());\nvar input = readline().split(' ').map(function (item) {\n\treturn parseInt(item);\n})\nvar result = [];\ninput.reduceRight(function (prev, curr) {\n\tvar max = Math.max(prev, curr);\n\tif(curr === max){\n\t\tresult.push(0);\n\t} else {\n\t\tresult.push(max - curr + 1);\n\t}\n\treturn max;\n}, 0)\nresult = result.reverse();\nprint(result.join(' '));"}], "src_uid": "e544ed0904e2def0c1b2d91f94acbc56"} {"nl": {"description": "A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).Find a way to cover some cells with sand so that exactly k islands appear on the n × n map, or determine that no such way exists. ", "input_spec": "The single line contains two positive integers n, k (1 ≤ n ≤ 100, 0 ≤ k ≤ n2) — the size of the map and the number of islands you should form.", "output_spec": "If the answer doesn't exist, print \"NO\" (without the quotes) in a single line. Otherwise, print \"YES\" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n. If there are multiple answers, you may print any of them. You should not maximize the sizes of islands.", "sample_inputs": ["5 2", "5 25"], "sample_outputs": ["YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS", "NO"], "notes": null}, "positive_code": [{"source_code": "function toi(x){return parseInt(x);}\nvar s=readline().split(\" \").map(toi);\nvar n=s[0];\nvar k=s[1];\nvar num=0;\nvar res=\"\";\nfor(var i=0;i (n*n+1)/2) {\n\tprint( 'NO' );\n} else {\n\tprint( 'YES' );\n\tvar cur = 0;\n\tfor (var i=0; i Math.floor(n*n)/2+n%2) {\n\tprint('NO');\n}\nelse {\n\tprint('YES');\n\tfor (i = 0 ; i total )\n print(\"NO\");\nelse {\n print(\"YES\");\n var i, j, k = 0;\n for(i = 0; i < N; i ++) {\n for(j = 0; j < N; j ++) {\n if( (i + j) % 2 == 0 && k < K ) {\n write('L');\n k ++;\n } else write('S'); \n }\n print(\"\"); \n }\n}"}], "negative_code": [{"source_code": "var s = readline().split( ' ' );\n\tn = parseInt( s[0] ),\n\tk = parseInt( s[1] );\n\t\nif (k > (n+1)/2) {\n\tprint( 'NO' );\n} else {\n\tvar cur = 0;\n\tfor (var i=0; i (n+1)/2) {\n\tprint( 'NO' );\n} else {\n\tvar cur = 0;\n\tfor (var i=0; i (n*n+1)/2) {\n\tprint( 'NO' );\n} else {\n\tvar cur = 0;\n\tfor (var i=0; i Math.floor(n/2)+n%2){\n\tprint('NO');\n}\nelse {\n\tprint('Yes');\n\tprevLand = false;\n\tfor (i = 0 ; i Math.floor(n/2)+n%2){\n\tprint('NO');\n}\nelse {\n\tprint('YES');\n\tprevLand = false;\n\tfor (i = 0 ; i Math.floor(n*n)/2+k%2) {\n\tprint('NO');\n}\nelse {\n\tprint('YES');\n\tfor (i = 0 ; i {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n // your code goes here\r\n \r\nvar t = parseInt(readline());\r\n\r\nwhile (t--) {\r\n\r\n let mp = new Map();\r\n let mp1 = new Map();\r\n\r\n let [ch, ch1] = readline().trim().split(\" \");\r\n\r\n for (let i = 0; i < ch.length; i++) {\r\n if (mp.has(ch[i]))\r\n mp.set(ch[i], mp.get(ch[i]) + 1);\r\n else\r\n mp.set(ch[i], 1);\r\n }\r\n\r\n for (let i = 0; i < ch1.length; i++) {\r\n if (mp1.has(ch1[i]))\r\n mp1.set(ch1[i], mp1.get(ch1[i]) + 1);\r\n else\r\n mp1.set(ch1[i], 1);\r\n }\r\n\r\n let s = \"\";\r\n\r\n for (let i = 0; i < ch.length; i++) {\r\n if (mp.get(ch[i]) <= mp1.get(ch[i]))\r\n s += ch[i];\r\n else\r\n mp.set(ch[i], mp.get(ch[i]) - 1);\r\n }\r\n\r\n //console.log(\"map size \", mp.size);\r\n\r\n if (s === ch1)\r\n console.log(\"YES\");\r\n else\r\n console.log(\"NO\");\r\n}\r\n\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// ********** Code Start **********\r\n \r\nfunction main() {\r\n // your code goes here\r\n \r\nvar t = parseInt(readline());\r\n \r\nwhile (t--) {\r\n \r\n let mp = new Map();\r\n let mp1 = new Map();\r\n \r\n let [ch, ch1] = readline().trim().split(\" \");\r\n \r\n for (let i = 0; i < ch.length; i++) {\r\n if (mp.has(ch[i]))\r\n mp.set(ch[i], mp.get(ch[i]) + 1);\r\n else\r\n mp.set(ch[i], 1);\r\n }\r\n \r\n for (let i = 0; i < ch1.length; i++) {\r\n if (mp1.has(ch1[i]))\r\n mp1.set(ch1[i], mp1.get(ch1[i]) + 1);\r\n else\r\n mp1.set(ch1[i], 1);\r\n }\r\n \r\n let s = \"\";\r\n \r\n for (let i = 0; i < ch.length; i++) {\r\n if (mp.get(ch[i]) <= mp1.get(ch[i]))\r\n s += ch[i];\r\n else\r\n mp.set(ch[i], mp.get(ch[i]) - 1);\r\n }\r\n \r\n //console.log(\"map size \", mp.size);\r\n \r\n if (s === ch1)\r\n console.log(\"YES\");\r\n else\r\n console.log(\"NO\");\r\n}}"}, {"source_code": "const readline = require('readline')\n\nlet inputs = []\nlet lineNum = 0\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n crlfDelay: Infinity\n})\n\nrl.on('line', input => {\n inputs.push(input)\n})\n\nrl.on('close', () => {\n let n = readLine()\n n = Number(n)\n for(let i=0; i 0)\n let idx = s.length-1\n for(let i=t.length-1; i>=0; i--){\n let char = t[i]\n let flag = false\n for(let j=idx; j>=0; j--){\n if(arr[j] !== 0) continue\n if(s[j] !== char){\n for(let k=j; k>=0; k--){\n if(s[k] === s[j]){\n arr[k] = -1\n }\n }\n }else{\n flag = true\n arr[j] = 1\n idx = j-1\n break\n }\n }\n if(!flag){\n console.log('NO')\n return\n }\n }\n console.log('YES')\n}\n\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(s, t) {\r\n const map = new Map();\r\n\r\n for (let i = 0; i < t.length - 1; i++) {\r\n var _map$get;\r\n\r\n const c = t[i];\r\n map.set(c, ((_map$get = map.get(c)) !== null && _map$get !== void 0 ? _map$get : 0) + 1);\r\n }\r\n\r\n for (let i = s.length - 1, j = t.length - 1; i >= 0; i--) {\r\n if (s[i] === t[j]) {\r\n j--;\r\n map.set(t[j], map.get(t[j]) - 1);\r\n } else {\r\n if (map.get(s[i])) return false;\r\n }\r\n\r\n if (j === -1) return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n// const inputs = fs.readFileSync(path.join(__dirname, './codeforces.test.txt'), 'utf-8').split('\\n')\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nvoid function main() {\r\n const _ = Number(inputs[0]);\r\n\r\n for (let __ = 1; __ <= _; __++) {\r\n const [s, t] = inputs[__].trim().split(' ');\r\n\r\n console.log(solve(s, t) ? 'YES' : 'NO');\r\n }\r\n}();\r\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nfunction print(x) {\r\n console.log(x);\r\n}\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n // your code goes here\r\n\r\n let t = parseInt(readline());\r\n\r\n while (t--) {\r\n\r\n let mp = new Map();\r\n let mp1 = new Map();\r\n\r\n let [ch, ch1] = readline();\r\n\r\n for (let i = 0; i < ch.length; i++) {\r\n if (mp.has(ch[i]))\r\n mp.set(ch[i], mp.get(ch[i]) + 1);\r\n else\r\n mp.set(ch[i], 1);\r\n }\r\n\r\n for (let i = 0; i < ch1.length; i++) {\r\n if (mp1.has(ch1[i]))\r\n mp1.set(ch1[i], mp1.get(ch1[i]) + 1);\r\n else\r\n mp1.set(ch1[i], 1);\r\n }\r\n\r\n let s = \"\";\r\n\r\n for (let i = 0; i < ch.length; i++) {\r\n if (mp.get(ch[i]) <= mp1.get(ch[i]))\r\n s += ch[i];\r\n else\r\n mp.set(ch[i], mp.get(ch[i]) - 1);\r\n }\r\n\r\n //console.log(\"map size \", mp.size);\r\n\r\n if (s == ch1)\r\n console.log(\"YES\");\r\n else\r\n console.log(\"NO\");\r\n }\r\n\r\n\r\n}\r\n"}], "src_uid": "d4b6505799f21d3147b9c1a0604b88b6"} {"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$$$) — 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 — \"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": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readALine() {\n return inputString[currentLine++];\n}\n\nfunction printALine(str) {\n console.log(str);\n}\n\nfunction stringArrayToNumbers(str) {\n var array = str.split(\" \");\n var result = [];\n for( var i = 0; i < array.length; i++ ) {\n result.push( parseInt(array[i]) );\n }\n return result;\n}\n\nfunction stringArrayToBigInts(str) {\n var array = str.split(\" \");\n var result = [];\n for( var i = 0; i < array.length; i++ ) {\n result.push( BigInt(array[i]) );\n }\n return result;\n}\n\n// ======================================================\n// A. Shuffle Hashing\n// https://codeforces.com/problemset/problem/1278/A\n// ======================================================\n\n// Convert p to array. Sort the array then convert it back to a string.\nfunction _process(str) {\n var arr = str.split('');\n arr.sort();\n return arr.join('');\n}\n\nfunction doIt( p, h ) {\n\n //printALine(\"P=\" + p + \" H=\" + h);\n var processedP = _process(p);\n //printALine(\" Processed P=\" + processedP);\n \n for( var i = 0; i < h.length; i++ ) {\n var str = h.substring(i, i + p.length); \n var processedStr = _process(str);\n //printALine(\" Substring=\" + str + \" Processed=\" + processedStr);\n if( processedStr == processedP ) {\n return \"YES\"; \n }\n }\n \n return \"NO\";\n \n}\n\nfunction main() {\n\n var numOfTests = parseInt(readALine());\n for( var i = 0; i < numOfTests; i++ ) {\n var string1 = readALine();\n var string2 = readALine();\n var result = doIt( string1, string2 );\n printALine(result);\n }\n \n}\n\n\n\n\n\n"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let j = 0; j < t; j++) {\n // wr(j)\n let p = arr[2 * j]\n const h = arr[2 * j + 1]\n\n const pa = p.split('')\n const ha = h.split('')\n\n const pl = p.length, hl = h.length\n p = pa.sort().join('')\n let flag = false\n\n for(let i = 0; i < hl - pl + 1; i++) {\n let t = h.substr(i, pl)\n t = t.split('').sort().join('')\n if(t == p) {\n flag = true\n break\n }\n }\n flag ? wr('YES') : wr('NO')\n }\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction max(...x) {\n return Math.max(...x)\n}\n\nfunction min(...x) {\n return Math.min(...x)\n}\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet index = 0;\nlet p = '', h = '';\n\nreadline.on('line', line => {\n if (index++) {\n if (!p) {\n p = line;\n return;\n } else {\n h = line;\n let tmp = p, flag = false;\n for(let i = 0, j = 0; i < h.length; ) {\n let ind = tmp.indexOf(h[i]);\n if (ind != -1) {\n tmp = tmp.slice(0, ind) + tmp.slice(ind + 1);\n if (!tmp.length) flag = true;\n i++;\n } else {\n tmp = p;\n j++;\n i = j;\n }\n }\n if (flag) console.log(\"YES\");\n else console.log(\"NO\");\n }\n p = '';\n }\n});\n\n// readline.on(\"close\", () => {\n// console.log(count, values);\n// });\n"}, {"source_code": "var print = this.print || require('lol-io').print; //print --> outputs result and adds (enter)\nvar write = this.write || require('lol-io').write; //write --> creates output.txt with output\nvar readline = this.readline || require('lol-io').readline; //readline --> reads unread line of input.txt\n\nvar t, p, h, sorted, answer, substring;\n\nt = Number(readline());\n\nfunction check (array1, array2) {\n\n if ((array1.length == array2.length) && array1.every(function(element, index) {\n return element === array2[index]})) {return true} else {return false}\n}\n\nfor (i = 0; i < t; i++) { //Loop each test\n\n p = readline().replace(/\\r$/, '');\n h = readline().replace(/\\r$/, '');\n answer = \"NO\";\n sorted = p.split('').sort();\n\n for (k = 0; k < h.length - p.length + 1; k++) { //\n\n for (j = 0; j < h.length; j++) {\n substring = h.substr(j, p.length).split('').sort();\n\n if (check(substring, sorted)) {\n answer = \"YES\";\n break;\n }\n }\n }\n\n print(answer);\n}"}, {"source_code": "var t = parseInt(readline(), 10),\n p = [],\n h = [];\n\nfor(var i=1; i<=t; i++) {\n p = readline().split('').sort();\n h = readline().split('');\n \n var demo_p = [], demo_p_sort = [];\n \n for(var j=0; j=p.length-1) {\n demo_p_sort = [...demo_p].sort();\n \n if(demo_p_sort.join('') === p.join('')) {\n print('YES');\n break;\n } else if(j === h.length - 1) print('NO');\n else demo_p.shift();\n \n } else if(j === h.length - 1) print('NO');\n }\n}"}], "negative_code": [{"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const n = parseInt(arr[0])\n\n const a = arr[1].split(' ').map(a => parseInt(a))\n\n let ans = 1\n if(n == 1) {\n console.log(1)\n return\n }\n for(let i = 1; i < n; i++) {\n if(n >= 2 && a[i] >= a[i - 1] && (i + 1) % 2 == 0) ans = max(ans, 2)\n if(i >= 3 && n >= 4 && a[i] >= a[i - 1] && a[i - 1] >= a[i - 2] && a[i - 2] >= a[i - 3] && (i + 1) % 4 == 0) ans = max(ans, 4)\n if(i >= 7 && n >= 8 && a[i] >= a[i - 1] && a[i - 1] >= a[i - 2] && a[i - 2] >= a[i - 3] && a[i - 3] >= a[i - 4] && a[i - 4] >= a[i - 5] && a[i - 5] >= a[i - 6] && a[i - 6] >= a[i - 7] && (i + 1) % 8 == 0) ans = max(ans, 8)\n let flag = true\n if(i == 15) {\n for(let j = 1; j < n; j++) {\n if(a[j] < a[j - 1]) {\n flag = false\n break\n }\n }\n }\n if(flag && i == 15) {\n ans = 16\n }\n }\n wr(ans)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction max(...x) {\n return Math.max(...x)\n}\n\nfunction min(...x) {\n return Math.min(...x)\n}\n"}], "src_uid": "48151011c3d380ab303ae38d0804176a"} {"nl": {"description": "Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.", "input_spec": "The first line of input contains three integers y, k, n (1 ≤ y, k, n ≤ 109;  ≤ 105).", "output_spec": "Print the list of whitespace-separated integers — all possible values of x in ascending order. You should print each possible value of x exactly once. If there are no such values of x print a single integer -1.", "sample_inputs": ["10 1 10", "10 6 40"], "sample_outputs": ["-1", "2 8 14 20 26"], "notes": null}, "positive_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', inputStd => inputString += inputStd);\nprocess.stdin.on('end', () => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n solve();\n});\nlet readLine = () => inputString[currentLine++];\n\nfunction solve(){\n let y, k, n;\n let line = readLine().split(' ').map(Number);\n y = line[0], k = line[1], n = line[2];\n let arr = [];\n\n for(let i = k; i <= n; i += k){\n if(i-y > 0) arr.push(i-y);\n }\n if(arr.length) \n for(let i of arr) \n process.stdout.write(`${i} `);\n else \n console.log(-1);\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n const [y, k, n] = readLine().split(\" \").map(Number);\n const result = [];\n for (let i = 1; i * k <= n; i++) {\n const num = k * i;\n if (num > y) {\n result.push(num - y);\n }\n }\n if (result.length) console.log(result.join(\" \"));\n else console.log(-1);\n}\n"}, {"source_code": "print(function(y, k, n) {\n\tvar i,ans = [];\n\tfor (i = k; i <= n; i += k)\n\t\tans.push(i);\n\n\tans = ans.map(function(v) {\n\t\treturn v - y;\n\t}).filter(function(v) {\n\t\treturn v >= 1;\n\t});\n\n\tif (ans.length === 0) return -1;\n\treturn ans.join(' ');\n\n} .apply(0, readline().split(' ').map(Number)));"}, {"source_code": "print(function(y, k, n) {\n\tvar i,\n\t\tans = [];\n\n\tfor (i = k * Math.ceil(y / k) - y, l = n - y; i <= l; i += k)\n\t\tif (i >= 1) ans.push(i);\n\n\tif (ans.length === 0) return -1;\n\treturn ans.join(' ');\n\n} .apply(0, readline().split(' ').map(Number)));"}, {"source_code": "print(function(y, k, n) {\n\n\tvar ans = [];\n\tfor (var i = k, l = Math.min(1e9,n); i <= l; i+=k)\n\t\tans.push(i);\n\n\tans = ans.map(function(v) {\n\t\treturn v - y;\n\t}).filter(function(v) {\n\t\treturn v >= 1;\n\t});\n\n\tif(ans.length===0) return -1;\n\treturn ans.join(' ');\n\n\n} .apply(0, readline().split(' ').map(Number)));"}, {"source_code": ";(function () {\n\n\tprint(function (y, k, n) {\n\t\tvar r = [], l = 0;\n\n\t\twhile (++l * k <= n)\n\t\t\tif (l*k > y)\n\t\t\t\tr.push( l*k - y);\n\n\t\tif (!r.length) return -1;\n\t\telse return r.join(' ');\n\t}.apply(0, readline().split(' ').map(Number)));\n\n}).call(this);"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar data = tokenizeIntegers(readline()),\n\t\ty = data[0], k = data[1], n = data[2],\n\t\tresult = [];\n\tfor (var sum = Math.ceil((y+1)/k)*k; sum <= n; sum += k) {\n\t\tresult.push(sum-y);\n\t}\n\tif (result.length == 0) {\n\t\tprint(-1);\n\t} else {\n\t\tprint(result.join(' '));\n\t}\n}\n\nmain();\n"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', inputStd => inputString += inputStd);\nprocess.stdin.on('end', () => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n solve();\n});\nlet readLine = () => inputString[currentLine++];\n\nfunction solve(){\n let y, k, n;\n let line = readLine().split(' ').map(Number);\n y = line[0], k = line[1], n = line[2];\n let arr = [];\n\n for(let i = k*2; i <= n; i += k){\n if(i-y > 0) arr.push(i-y);\n }\n if(arr.length) \n for(let i of arr) \n process.stdout.write(`${i} `);\n else \n console.log(-1);\n}\n"}, {"source_code": "print(function(y, k, n) {\n\n\tvar ans = [];\n\tfor (var i = 1, l = Math.min(1e5,n); i <= l; i++)\n\t\tif (i % k === 0) ans.push(i);\n\n\tans = ans.map(function(v) {\n\t\treturn v - y;\n\t}).filter(function(v) {\n\t\treturn v >= 1;\n\t});\n\n\tif(ans.length===0) return -1;\n\treturn ans.join(' ');\n\n\n} .apply(0, readline().split(' ').map(Number)));"}, {"source_code": "print(function(y, k, n) {\n\tvar i,\n\t\tans = [];\n\n\tif (y === k) return -1;\n\tfor (i = k * Math.ceil(y / k) - y, l = n - y; i <= l; i += k)\n\t\tans.push(i);\n\n\tif (ans.length === 0) return -1;\n\treturn ans.join(' ');\n\n} .apply(0, readline().split(' ').map(Number)));"}, {"source_code": "print(function(y, k, n) {\n\tvar i,\n\t\tans = [];\n\n\tfor (i = k * Math.ceil(y / k) - y, l = n - y; i <= l; i += k)\n\t\tans.push(i);\n\n\tif (ans.length === 0) return -1;\n\treturn ans.join(' ');\n\n} .apply(0, readline().split(' ').map(Number)));"}], "src_uid": "2deda3a05740e1184735bf437e3850a8"} {"nl": {"description": "You have an image file of size $$$2 \\times 2$$$, consisting of $$$4$$$ pixels. Each pixel can have one of $$$26$$$ different colors, denoted by lowercase Latin letters.You want to recolor some of the pixels of the image so that all $$$4$$$ pixels have the same color. In one move, you can choose no more than two pixels of the same color and paint them into some other color (if you choose two pixels, both should be painted into the same color).What is the minimum number of moves you have to make in order to fulfill your goal?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. Each test case consists of two lines. Each of these lines contains two lowercase letters of Latin alphabet without any separators, denoting a row of pixels in the image.", "output_spec": "For each test case, print one integer — the minimum number of moves you have to make so that all $$$4$$$ pixels of the image have the same color.", "sample_inputs": ["5\n\nrb\n\nbr\n\ncc\n\nwb\n\naa\n\naa\n\nab\n\ncd\n\nyy\n\nxx"], "sample_outputs": ["1\n2\n0\n3\n1"], "notes": "NoteLet's analyze the test cases of the example.In the first test case, you can paint the bottom left pixel and the top right pixel (which share the same color) into the color r, so all pixels have this color.In the second test case, two moves are enough: paint both top pixels, which have the same color c, into the color b; paint the bottom left pixel into the color b. In the third test case, all pixels already have the same color.In the fourth test case, you may leave any of the pixels unchanged, and paint all three other pixels into the color of that pixel in three moves.In the fifth test case, you can paint both top pixels into the color x."}, "positive_code": [{"source_code": "const t = Number(readline());\r\n\r\nfor (i = 0; i < t; i++) {\r\n currentImage = readline() + readline();\r\n\r\n uniqueColors = new Set(currentImage.split(''));\r\n nrOfUniqueColors = [...uniqueColors].length;\r\n\r\n print(nrOfUniqueColors - 1);\r\n}\r\n"}, {"source_code": "var t = Number(readline())\n\nfor (var i=0; i inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n for (let test = 0; test < N; test++) {\r\n let pixels = readline().split('').concat(readline().split(''));\r\n let freq = {};\r\n\r\n for (let i = 0; i < 4; i++) {\r\n if (freq[pixels[i]]) {\r\n freq[pixels[i]]++;\r\n } else {\r\n freq[pixels[i]] = 1;\r\n }\r\n }\r\n\r\n output(Object.keys(freq).length - 1);\r\n }\r\n}\r\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n for(let i=1;i<=t;i++)\r\n {\r\n let x=line[2*i-1];\r\n let y=line[2*i];\r\n let a=new Array(4);\r\n a[0]=x[0].charCodeAt();\r\n a[1]=x[1].charCodeAt();\r\n a[2]=y[0].charCodeAt();\r\n a[3]=y[1].charCodeAt();\r\n a.sort(function(x,y) {\r\n return x-y;\r\n })\r\n if(a[0]===a[3]) console.log(0);\r\n else if((a[0]==a[1]&&a[0]==a[2])||(a[1]==a[2]&&a[1]==a[3])) console.log(1);\r\n else if((a[0]==a[1])&&(a[2]==a[3])) console.log(1);\r\n else if((a[0]==a[1])||(a[1]==a[2])||(a[2]==a[3])) console.log(2);\r\n else console.log(3);\r\n }\r\n})"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const arr = lines.slice(l, l + 2).map(str => str.trim())\n l += 2\n output[i] = solve(arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(arr) {\n const map = {}\n update(arr[0][0])\n update(arr[0][1])\n update(arr[1][0])\n update(arr[1][1])\n const ks = Object.keys(map)\n if (ks.length === 1) {\n return 0\n } else if (ks.length === 2) {\n return 1\n } else if (ks.length === 3) {\n return 2\n } else if (ks.length === 4) {\n return 3\n }\n function update(ch) {\n map[ch] = (map[ch] || 0) + 1\n }\n}\n"}, {"source_code": "// Common Template Starts //\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\"\r\nlet currentLine = 0\r\n\r\nprocess.stdin.on(\"data\", inputStdin => inputString += inputStdin)\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => string.trim())\r\n main()\r\n})\r\n\r\nconst readline = () => inputString[currentLine++]\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n let t = parseInt(readline())\r\n while (t--) {\r\n // let n = parseInt(readline())\r\n let l1 = readline()\r\n let l2 = readline()\r\n console.log( solve(l1, l2) )\r\n }\r\n}\r\n// Driver Function Ends //\r\n\r\n// MAIN LOGIC\r\nconst solve = (l1, l2) => {\r\n let colors = (l1+l2).split('')\r\n let unique = uniqueArray( colors ) \r\n\r\n // if( unique.length == 1 ) return 0\r\n // if( unique.length == 2 ) return 1\r\n // if( unique.length == 3 ) return 2\r\n // if( unique.length == 4 ) return 3\r\n\r\n return unique.length - 1\r\n}\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)"}, {"source_code": "var readline=require('readline')\r\nvar r1=readline.createInterface({\r\n input:process.stdin,\r\n output:process.stdout\r\n})\r\nvar i=0\r\nvar t;\r\nvar a,b,c,d;\r\nr1.question('',function (x){t=parseInt(x);test();})\r\nasync function test(){\r\n r1.question('',function (x){\r\n a=x[0]\r\n b=x[1]\r\n r1.question('',function (x){\r\n c=x[0]\r\n d=x[1]\r\n if(a!==b&&a!==c&&a!==d&&b!==c&&b!==d&&c!==d)\r\n console.log('3\\n')\r\n else if(a===b&&b===c&&c===d)\r\n console.log('0\\n')\r\n else if((a===b&&b===c)||(a===b&&b===d)||(a===c&&d===c)||(d===b&&b===c))\r\n console.log('1\\n')\r\n else if((a===b&&c===d)||(a===c&&b===d)||(a===d&&b===c))\r\n console.log('1\\n')\r\n else\r\n console.log('2\\n')\r\n i++;\r\n if(i {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", (_) => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((string) => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n/***\nEducational Codeforces Round 134 (Div. 2)\n2022-08-26\n\nA. Image\n***/\n\nfunction main() {\n // INPUT: Number of test cases\n let t = readline();\n t = parseInt(t);\n for (let tc = 0; tc < t; tc++) {\n const colors = new Set();\n\n // INPUT: two rows with 2 colors each\n let row = readline();\n colors.add(row.charAt(0));\n colors.add(row.charAt(1));\n row = readline();\n colors.add(row.charAt(0));\n colors.add(row.charAt(1));\n\n console.log(colors.size - 1);\n }\n}\n"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n\r\nvar T = readline();\r\nvar inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n var [n, k] = readline().split('')//.map((x) => parseInt(x));\r\n var [a, b] = readline().split('')//.map((x) => parseInt(x));\r\n var s = a+b+n+k;\r\n // console.log(s)\r\n var cnt = {\r\n [a]: 0,[b]:0,[n]:0,[k]:0\r\n }\r\n for(var i=0;i<4;i++) cnt[s[i]]++;\r\n var num = [];\r\n \r\n var ct = [0,0,0,0,0];\r\n for(var i=0;i<4;i++) {\r\n if(!s.slice(i+1, 4).includes(s[i])) ct[cnt[s[i]]]+=1\r\n }\r\n // console.log(cnt, ct)\r\n if(ct[4]) console.log(0);\r\n else if(ct[3]||ct[2]>1) console.log(1)\r\n else if(ct[2]) console.log(2);\r\n else console.log(3)\r\n\r\n}\r\n"}, {"source_code": "'use strict';\n\nconst fs = require('fs');\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function() {\n inputString = inputString.split('\\n');\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction isPossible(n, x, heights) { \n heights.sort();\n heights.sort(function(a, b) {\n return a - b;\n });\n // //console.log(heights)\n \n let front = []\n let back = []\n \n for (let i = 0; i < heights.length; i++) {\n if (i < n) {\n front.push(heights[i])\n } else {\n back.push(heights[i])\n }\n }\n \n // //console.log(front)\n // //console.log(back)\n for (let j = 0; j < front.length; j++) {\n if (back[j] - front[j] < x) {\n // //console.log(back[j] + \" \" + front[j])\n return \"NO\";\n }\n }\n \n return \"YES\";\n}\n\nfunction calc(a, m) {\n let s = \"\";\n for (let index = 0; index < m; index++) {\n s += \"B\"\n }\n\n for (let index = 0; index < a.length; index++) {\n let ai = a[index];\n\n if (ai < (m + 1 - ai)) {\n let _s = s.replaceAt(ai - 1, \"A\");\n if (compare(_s, s) < 0) {\n s = _s;\n continue;\n } else if (compare(_s, s) >= 0) {\n let __ss = s.replaceAt(m + 1 - ai - 1, \"A\");\n if (compare(__ss, s) < 0) {\n s = __ss;\n continue;\n } \n }\n } else {\n let _s = s.replaceAt(m + 1 - ai - 1, \"A\");\n if (compare(_s, s) < 0) {\n s = _s;\n continue;\n } if (compare(_s, s) >= 0) {\n let __ss = s.replaceAt(ai - 1, \"A\");\n if (compare(__ss, s) < 0) {\n s = __ss;\n continue;\n }\n } \n }\n}\n\n return s;\n}\n\nfunction compare(s1, s2) {\n return s1.localeCompare(s2)\n}\n\nString.prototype.replaceAt = function(index, replacement) {\n return this.substring(0, index) + replacement + this.substring(index + replacement.length);\n}\n\n\nfunction main() {\n const test_cases = parseInt(readLine().trim(), 10);\n\n for (let gItr = 0; gItr < test_cases; gItr++) {\n // const arr1 = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n // const arr2 = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n const line1 = readLine().trim()\n const line2 = readLine().trim()\n const color1 = line1[0]\n const color2 = line1[1]\n const color3 = line2[0]\n const color4 = line2[1]\n\n let mySet = new Set()\n mySet.add(color1)\n mySet.add(color2)\n mySet.add(color3)\n mySet.add(color4)\n\n if (mySet.size == 4) {\n console.log(3)\n } else if (mySet.size == 3) {\n console.log(2)\n } else if (mySet.size == 2) {\n console.log(1)\n } else if (mySet.size == 1) {\n console.log(0)\n }\n }\n\n\n // ws.end();\n}\n"}, {"source_code": "let readline = require(\"readline\");\r\nlet rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nlet input = [];\r\nrl.on(\"line\", function (line) {\r\n input.push(line);\r\n\r\n if (input.length === +input[0] * 2 + 1) {\r\n // call your function here\r\n solve(input);\r\n rl.close();\r\n }\r\n});\r\n\r\nlet solve = (input) => {\r\n let set = new Set();\r\n\r\n for (let i = 1; i < input.length; i += 2) {\r\n let colors = input[i].split(\"\");\r\n set.add(colors[0]);\r\n set.add(colors[1]);\r\n colors = input[i + 1].split(\"\");\r\n set.add(colors[0]);\r\n set.add(colors[1]);\r\n\r\n if (set.size === 1) console.log(0);\r\n if (set.size === 4) console.log(3);\r\n if (set.size === 2) console.log(1);\r\n if (set.size === 3) console.log(2);\r\n set.clear();\r\n }\r\n};\r\n"}, {"source_code": "\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '', currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => { inputString += inputStdin; });\r\nprocess.stdin.on('end', _ => { \r\n inputString = inputString.trim().split('\\n').map(string => string.trim());\r\n main(); \r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const t = +readLine();\r\n for(let i = 0; i < t; i++){\r\n // const n = +readLine();\r\n const ab = readLine();\r\n const cd = readLine();\r\n let result = myFunc(ab[0], ab[1], cd[0], cd[1]);\r\n console.log(result);\r\n }\r\n}\r\n\r\nfunction myFunc(a, b, c, d){\r\n \r\n let set = new Set();\r\n set.add(a);\r\n set.add(b);\r\n set.add(c);\r\n set.add(d);\r\n\r\n if(set.size == 1) return 0;\r\n if(set.size == 2) return 1;\r\n if(set.size == 3) return 2;\r\n if(set.size == 4) return 3;\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "let fs = require(\"fs\");\r\nlet sc = {\r\n _buf: new Buffer.alloc(1 << 14),\r\n _bufPos: 0,\r\n _bufLen: 0,\r\n _ensure: function ()\r\n {\r\n if (this._bufPos === this._bufLen)\r\n {\r\n this._bufPos = 0;\r\n this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);\r\n }\r\n },\r\n _isws: function (ch)\r\n {\r\n return ch === 32 || ch === 9 || ch === 10 || ch === 13;\r\n },\r\n _islf: function (ch)\r\n {\r\n return ch === 10 || ch === 13;\r\n },\r\n _peekChar: function ()\r\n {\r\n this._ensure();\r\n return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];\r\n },\r\n _skipWs: function ()\r\n {\r\n while (this._isws(this._peekChar()))\r\n this._bufPos++;\r\n },\r\n _readUntil: function (stop)\r\n {\r\n this._ensure();\r\n if (this._bufPos === this._bufLen)\r\n throw new Error(\"eof\");\r\n let start = this._bufPos;\r\n let before = null;\r\n for (; ;)\r\n {\r\n if (this._bufPos === this._bufLen)\r\n {\r\n let len = this._bufPos - start, preLen = (before ? before.length : 0);\r\n let nbuf = new Buffer(len + preLen);\r\n if (before)\r\n before.copy(nbuf);\r\n before = nbuf;\r\n this._buf.copy(before, preLen, start);\r\n this._ensure();\r\n start = this._bufPos;\r\n }\r\n if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;\r\n this._bufPos++;\r\n }\r\n if (!before)\r\n return this._buf.toString(\"utf8\", start, this._bufPos);\r\n let after = this._buf.slice(start, this._bufPos);\r\n let res = new Buffer(before.length + after.length);\r\n before.copy(res);\r\n after.copy(res, before.length);\r\n return res.toString();\r\n },\r\n\r\n nextToken: function ()\r\n {\r\n this._skipWs();\r\n return this._readUntil(this._isws);\r\n },\r\n L: function ()\r\n {\r\n let line = this._readUntil(this._islf);\r\n if (this._peekChar() === 13) this._bufPos++;\r\n if (this._peekChar() === 10) this._bufPos++;\r\n return line;\r\n },\r\n N: function ()\r\n {\r\n return +this.nextToken();\r\n },\r\n S: function ()\r\n {\r\n return this.nextToken();\r\n }\r\n};\r\n\r\n// DO NOT CHANGE TEMPLATE BEFORE\r\n\r\nconst Def = Number(1e9);\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nconst Solve = () =>\r\n{\r\n let s = sc.S() + sc.S();\r\n // console.log(`s = ${s}`);\r\n\r\n let count = 0, map = new Map();\r\n for (let ch of s)\r\n {\r\n if (!map.has(ch))\r\n {\r\n ++count;\r\n map.set(ch, 1);\r\n }\r\n }\r\n\r\n console.log(count - 1);\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\nconst main = () =>\r\n{\r\n let cases = sc.N();\r\n while (cases-- > 0) Solve();\r\n\r\n // Solve();\r\n}\r\nmain();\r\n\r\n"}, {"source_code": "const fs = require(\"fs\");\n\nconst input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\n\nconst testCases = [];\nlet T;\n\nfunction parseInput() {\n T = parseInt(input[0]);\n let index = 0;\n\n for (let i = 0; i < T; i++) {\n index++;\n const [a, b] = input[index].split(\"\");\n index++;\n const [c, d] = input[index].split(\"\");\n const testCase = {\n a: [a, b, c, d],\n };\n\n testCases.push(testCase);\n }\n}\n\nfunction solution(testCase) {\n const { a } = testCase;\n // console.log(a);\n\n const dict = {};\n a.forEach((v) => {\n if (!dict[v]) dict[v] = 0;\n dict[v]++;\n });\n\n const b = Object.values(dict).sort((c, d) => c - d);\n // console.error(b);\n\n console.log(b.length - 1);\n}\n\nparseInput();\n\ntestCases.forEach(solution);\n"}], "negative_code": [{"source_code": "const t = Number(readline());\r\n// const t = Number('5');\r\n// print(t);\r\n\r\n// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];\r\n\r\nfor (i = 0; i < t; i++) {\r\n // const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];\r\n currentImage = readline() + readline();\r\n print(currentImage);\r\n\r\n uniqueColors = new Set(currentImage.split(''));\r\n nrOfUniqueColors = [...uniqueColors].length;\r\n\r\n // console.log(nrOfUniqueColors - 1);\r\n print(nrOfUniqueColors - 1);\r\n}\r\n"}, {"source_code": "const t = Number(readline());\r\n// const t = Number('5');\r\n// print(t);\r\n\r\n// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];\r\n\r\nfor (i = 0; i < t; i++) {\r\n // const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];\r\n const currentImage = readline() + readline();\r\n print(currentImage);\r\n\r\n const uniqueColors = new Set(currentImage.split(''));\r\n const nrOfUniqueColors = [...uniqueColors].length;\r\n\r\n // console.log(nrOfUniqueColors - 1);\r\n print(nrOfUniqueColors - 1);\r\n}\r\n"}, {"source_code": "const t = Number(readline());\r\n// const t = Number('5');\r\n// print(t);\r\n\r\n// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];\r\n\r\nfor (i = 0; i < t; i++) {\r\n // const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];\r\n const currentImage = readline() + readline();\r\n // print(5);\r\n\r\n const uniqueColors = new Set(currentImage.split(''));\r\n const nrOfUniqueColors = [...uniqueColors].length;\r\n\r\n // console.log(nrOfUniqueColors - 1);\r\n print(nrOfUniqueColors - 1);\r\n}\r\n"}, {"source_code": "const t = Number(readline());\r\n// const t = Number('5');\r\nprint(t);\r\n\r\n// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];\r\n\r\n// for (let i = 0; i < t; i++) {\r\n// const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];\r\n// const currentImage = readline() + readline();\r\n// print(5);\r\n\r\n// const uniqueColors = new Set(currentImage.split(''));\r\n// const nrOfUniqueColors = [...uniqueColors].length;\r\n\r\n// console.log(nrOfUniqueColors - 1);\r\n// // print(nrOfUniqueColors - 1);\r\n// }\r\n\r\nfor (i = 0; i < t; i++) {\r\n print(t);\r\n}\r\n"}, {"source_code": "const t = Number(readline());\r\n// const t = Number('5');\r\nprint(t);\r\n\r\n// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];\r\n\r\n// for (let i = 0; i < t; i++) {\r\n// const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];\r\n// const currentImage = readline() + readline();\r\nprint(5);\r\n\r\n// const uniqueColors = new Set(currentImage.split(''));\r\n// const nrOfUniqueColors = [...uniqueColors].length;\r\n\r\n// console.log(nrOfUniqueColors - 1);\r\n// // print(nrOfUniqueColors - 1);\r\n// }\r\n"}, {"source_code": "const t = Number(readline());\r\n// const t = Number('5');\r\nprint(t);\r\n\r\n// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];\r\n\r\n// for (let i = 0; i < t; i += 1) {\r\n// const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];\r\n// // const currentImage = readline() + readline();\r\n\r\n// const uniqueColors = new Set(currentImage.split(''));\r\n// const nrOfUniqueColors = [...uniqueColors].length;\r\n\r\n// console.log(nrOfUniqueColors - 1);\r\n// // print(nrOfUniqueColors - 1);\r\n// }\r\n"}, {"source_code": "var repeatTimes = readline();\r\n\r\nwhile (repeatTimes--) {\r\n var str1 = readline()\r\n var str2 = readline()\r\n var set1 = new Set()\r\n set1.add(str1[0])\r\n set1.add(str1[1])\r\n set1.add(str2[0])\r\n set1.add(str2[1])\r\n print(set1.size)\r\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nvar input = '';\r\nprocess.stdin.on('data', function(chunk) {\r\n input += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', function() {\r\n const lines = input.trim().split('\\n');\r\n for (let i = 1; i < lines.length; i += 2) {\r\n const colors = (lines[i] + lines[i + 1]).split('');\r\n const colorSet = new Set(colors);\r\n process.stdout.write(String(colorSet.size - 1) + '\\n');\r\n }\r\n});\r\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nvar input = '';\nprocess.stdin.on('data', function(chunk) {\n input += chunk;\n});\n\nprocess.stdin.on('end', function() {\n const lines = input.trim().split('\\n');\n for (let i = 1; i < lines.length; i += 2) {\n const colors = (lines[i] + lines[i + 1]).split('');\n const colorSet = new Set(colors);\n process.stdout.write(String(colorSet.size - 1) + '\\n');\n }\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nvar input = '';\nprocess.stdin.on('data', function(chunk) {\n input += chunk;\n});\n\nprocess.stdin.on('end', function() {\n const lines = input.trim().split('\\n');\n for (let i = 1; i < lines.length; i += 2) {\n const colors = (lines[i] + lines[i + 1]).split('');\n const colorSet = new Set(colors);\n console.log(String(colorSet.size - 1));\n }\n});\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nvar input = '';\nprocess.stdin.on('data', function(chunk) {\n input += chunk;\n});\n\nprocess.stdin.on('end', function() {\n const lines = input.trim().split('\\n');\n for (let i = 1; i < lines.length; i += 2) {\n const colors = (lines[i] + lines[i + 1]).split('');\n const colorSet = new Set(colors);\n console.log(colorSet.size - 1);\n }\n});\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n for (let test = 0; test < N; test++) {\r\n let pixels = readline().split('').concat(readline().split(''));\r\n let freq = {};\r\n\r\n for (let i = 0; i < 4; i++) {\r\n if (freq[pixels[i]]) {\r\n freq[pixels[i]]++;\r\n } else {\r\n freq[pixels[i]] = 1;\r\n }\r\n }\r\n\r\n const count = Object.keys(freq).length;\r\n let values = Object.keys(freq).map(key => freq[key]);\r\n\r\n if (count === 1) {\r\n output(0);\r\n } else if (count === 2) {\r\n if (values.includes(3)) {\r\n output(3);\r\n } else {\r\n output(2);\r\n }\r\n } else if (count === 3) {\r\n output(3);\r\n } else if (count === 4) {\r\n output(4);\r\n }\r\n }\r\n}\r\n"}], "src_uid": "a9143235c8e2b6b188ea3fc8a90f0c80"} {"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$$$) — the number of test cases. The first line of each test case contains a positive integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$) — the number of cosplayers in the initial line. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ — 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 buf='';\r\n\r\nprocess.stdin.on('readable', function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end', function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=line[0];\r\n for(let _=1;_<=t;_++)\r\n {\r\n let n=parseInt(line[2*_-1]);\r\n let s=line[2*_];\r\n // console.log(n,s);\r\n let ans=0;\r\n let cnt=0;\r\n let sum=0;\r\n for(let i=0;i1)\r\n {\r\n if(cnt<2)\r\n {\r\n ans+=2-cnt;\r\n }\r\n }\r\n cnt=0;\r\n }\r\n else\r\n {\r\n cnt++;\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n})"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\n\nconst calc = (n, line)=>{\n let pos = -1;\n let res = 0;\n for (let i = 0; i < n; i++) {\n if (line[i] === '0') {\n if (pos === -1) {\n pos = i;\n continue;\n }\n let diff = i - pos;\n if (diff > 2) {\n pos = i;\n continue;\n }\n res += 2 - diff + 1; \n pos = i;\n }\n }\n return res;\n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let n = +readline();\n let line = readline();\n console.log(`${calc(n, line)}`);\n }\n}\n\n\n\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n let b = readline().split('').map(Number);\r\n\r\n let ans = 0;\r\n let count = 2;\r\n for (let c of b) {\r\n if (c === 1) count++;\r\n else {\r\n ans += Math.max(2 - count, 0);\r\n count = 0;\r\n }\r\n }\r\n\r\n output(ans);\r\n }\r\n}\r\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n\tvar t = lines[0];\n\tvar n = 0;\n\tfor(i = 1; i <= t * 2; i++){\n\t if(i % 2 == 1){\n\t n = lines[i];\n\t }else{\n\t var s = lines[i].split('').map(Number);\n\t var ans = 0;\n\t for(j = 0; j < n; j++){\n\t if(s[j] == 1){\n\t continue;\n\t }\n\t if(j < n - 1 && s[j + 1] === 0){\n\t ans += 2;\n\t }else if(j < n - 2 && s[j + 1] == 1 && s[j + 2] === 0){\n\t ans++;\n\t }\n\t }\n\t console.log(ans);\n\t }\n\t}\n});\n\n"}, {"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n let testCases = parseInt(data.shift());\r\n\r\n while(testCases--) { \r\n\r\n const n = readLine();\r\n\r\n const a = readLine();\r\n\r\n const res = main(a);\r\n\r\n console.log(res)\r\n }\r\n});\r\n\r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n\r\n\r\nfunction main(a){\r\n let ans = 0;\r\n let cnt = 2;\r\n for (let index = 0; index < a.length; index++) {\r\n if(a[index] == 1){\r\n cnt++;\r\n } else{\r\n ans += Math.max(2 - cnt,0);\r\n cnt = 0;\r\n }\r\n }\r\n return ans;\r\n}\r\n"}, {"source_code": "// problems/contest1658/A/src/ts/solution.ts\nvar lines = [];\nrequire(\"readline\").createInterface({\n input: process.stdin\n}).on(\"line\", (line) => lines.push(line));\nprocess.stdin.on(\"end\", () => {\n main(lines);\n});\nfunction main(lines2) {\n let i = 0;\n for (let t = Number(lines2[i++]); t > 0; t--) {\n const n = Number(lines2[i++]);\n const s = lines2[i++];\n console.log(solve(n, s));\n }\n}\nfunction solve(n, s) {\n let res = 0;\n let p = -1;\n for (let i = 0; i < n; i++) {\n if (s[i] === \"0\") {\n if (p >= 0) {\n if (p + 1 === i)\n res += 2;\n else if (p + 2 === i)\n res += 1;\n }\n p = i;\n }\n }\n return res;\n}\n"}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\nconst N = Number(inputs[0])\r\nfor (let _ = 0, __ = 1; _ < N; _++) {\r\n const n = Number(inputs[__++]),\r\n data = inputs[__++]\r\n main(n, data)\r\n}\r\n\r\nfunction main(n, data) {\r\n let res = 0\r\n for (let i = 1; i < n; i++) {\r\n if (data[i - 1] === '0') {\r\n if (data[i] === '0') res += 2\r\n else if (data[i] === '1' && i + 1 !== n && data[i + 1] !== '1') res++\r\n }\r\n }\r\n console.log(res)\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const str = lines[l++]\n output[i] = solve(n, str)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, str) {\n let ans = 0\n let prev\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '0') {\n if (prev >= 0) {\n ans += Math.max(0, 3 - (i - prev))\n }\n prev = i\n }\n }\n return ans\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar S = next();\r\n\t\tvar output = 0;\r\n\t\tfor(var i = 0; i < N - 1; i++){\r\n\t\t\tif(S[i] == \"0\" && S[i + 1] == \"0\"){\r\n\t\t\t\toutput += 2;\r\n\t\t\t}else if(i > 0 && S[i - 1] == \"0\" && S[i] == \"1\" && S[i + 1] == \"0\"){\r\n\t\t\t\toutput++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}, {"source_code": "/*\r\nINPUT\r\n9\r\n3\r\n000\r\n3\r\n001\r\n3\r\n010\r\n3\r\n011\r\n3\r\n100\r\n3\r\n101\r\n3\r\n110\r\n3\r\n111\r\n19\r\n1010110000100000101\r\n*/\r\n\r\nvar t = Number(readline());\r\n\r\nfor(var i = 0; i < t; i++) {\r\n readline();\r\n var s = readline();\r\n\r\n var lastZero = -Infinity;\r\n var total = 0;\r\n\r\n for(var j = 0; j < s.length; j++) {\r\n if(s[j] == '0') {\r\n if(lastZero == j - 1) {\r\n total += 2;\r\n }\r\n if(lastZero == j - 2) {\r\n total += 1;\r\n }\r\n lastZero = j;\r\n }\r\n }\r\n\r\n print(total);\r\n}"}], "negative_code": [{"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable', function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end', function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n console.log(1);\r\n setTimeout(()=>{\r\n console.log(3);\r\n },1000);\r\n console.log(2);\r\n})"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable', function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end', function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n console.log(1);\r\n setTimeout(()=>{\r\n console.log(3);\r\n },100);\r\n console.log(2);\r\n})"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable', function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end', function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n console.log(1);\r\n})"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable', function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('read', function(){\r\n const {EOL}=requrie('os');\r\n let line=buf.split(EOL);\r\n console.log(1);\r\n setTimeout(()=>{\r\n console.log(3);\r\n },100);\r\n console.log(2);\r\n})"}, {"source_code": "const lines = [];\r\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\r\nrl.on('line', line => lines.push(line));\r\nrl.on('close', main);\r\nlet rli = 0;\r\nfunction readline() {\r\n return lines[rli++];\r\n}\r\n\r\nconst ra = ()=>readline().split(' ').map(a=>+a);\r\n\r\nfunction div(val, by){\r\n return (val - val % by) / by;\r\n}\r\n\r\n\r\nconst calc = (n, line)=>{\r\n let pos = -1;\r\n let res = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (line[i] === '0') {\r\n if (pos === -1) {\r\n pos = i;\r\n continue;\r\n }\r\n let diff = i - pos;\r\n if (diff > 2) {\r\n pos = i;\r\n continue;\r\n }\r\n res += 2 - diff + 1; \r\n pos = i;\r\n }\r\n }\r\n return res;\r\n};\r\n\r\nfunction main() {\r\n let T = +readline();\r\n for (let t = 1; t <= T; t++){\r\n let n = +readline();\r\n let line = readline();\r\n console.log(`Case #${t}: ${calc(n, line)}`);\r\n }\r\n}\r\n\r\n\r\n\r\n"}], "src_uid": "9966bfdc9677a9dd558684a00977cd58"} {"nl": {"description": "There is a graph of $$$n$$$ rows and $$$10^6 + 2$$$ columns, where rows are numbered from $$$1$$$ to $$$n$$$ and columns from $$$0$$$ to $$$10^6 + 1$$$: Let's denote the node in the row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$.Initially for each $$$i$$$ the $$$i$$$-th row has exactly one obstacle — at node $$$(i, a_i)$$$. You want to move some obstacles so that you can reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $$$u$$$ or $$$v$$$ coins, as below: If there is an obstacle in the node $$$(i, j)$$$, you can use $$$u$$$ coins to move it to $$$(i-1, j)$$$ or $$$(i+1, j)$$$, if such node exists and if there is no obstacle in that node currently. If there is an obstacle in the node $$$(i, j)$$$, you can use $$$v$$$ coins to move it to $$$(i, j-1)$$$ or $$$(i, j+1)$$$, if such node exists and if there is no obstacle in that node currently. Note that you can't move obstacles outside the grid. For example, you can't move an obstacle from $$$(1,1)$$$ to $$$(0,1)$$$. Refer to the picture above for a better understanding. Now you need to calculate the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$u$$$ and $$$v$$$ ($$$2 \\le n \\le 100$$$, $$$1 \\le u, v \\le 10^9$$$) — the number of rows in the graph and the numbers of coins needed to move vertically and horizontally respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$) — where $$$a_i$$$ represents that the obstacle in the $$$i$$$-th row is in node $$$(i, a_i)$$$. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^4$$$.", "output_spec": "For each test case, output a single integer — the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles. It can be shown that under the constraints of the problem there is always a way to make such a trip possible.", "sample_inputs": ["3\n2 3 4\n2 2\n2 3 4\n3 2\n2 4 3\n3 2"], "sample_outputs": ["7\n3\n3"], "notes": "NoteIn the first sample, two obstacles are at $$$(1, 2)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(2, 2)$$$ to $$$(2, 3)$$$, then to $$$(1, 3)$$$. The total cost is $$$u+v = 7$$$ coins. In the second sample, two obstacles are at $$$(1, 3)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(1, 3)$$$ to $$$(2, 3)$$$. The cost is $$$u = 3$$$ coins. "}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = BigInt(1e9 + 7);\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [n, u, v] = iInpArr();\r\n let arr = iInpArr();\r\n let flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (arr[i] !== arr[i + 1]) {\r\n flag = true;\r\n break;\r\n }\r\n }\r\n if (!flag) {\r\n console.log(v + Math.min(u, v));\r\n continue;\r\n }\r\n flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (Math.abs(arr[i] - arr[i + 1]) >= 2) {\r\n console.log(0);\r\n flag = true;\r\n break;\r\n }\r\n }\r\n if (!flag) console.log(Math.min(u, v));\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n // var x = new Array(n)\r\n var [n, u, v] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var ans = false\r\n for (let i = 0; i < n - 1; i++) {\r\n if (Math.abs(a[i] - a[i + 1]) > 1) ans = true\r\n }\r\n // console.log('ansans')\r\n // console.log(ans)\r\n // console.log(a)\r\n if (ans) return console.log(0)\r\n\r\n var existOne = false\r\n for (let i = 0; i < n - 1; i++) {\r\n if (Math.abs(a[i] - a[i + 1]) === 1) existOne = true\r\n }\r\n\r\n if (existOne) return console.log(Math.min(u, v))\r\n\r\n var min1 = v + v\r\n var min2 = u + v\r\n console.log(Math.min(min1, min2))\r\n\r\n })\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, u, v] = rna();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet mxdf = 0;\r\n\t\tfor (let i = 1; i < n; i++) {\r\n\t\t\tmxdf = Math.max(mxdf, Math.abs(a[i] - a[i-1]));\r\n\t\t}\r\n\r\n\t\tlet ans;\r\n\t\tif (mxdf >= 2) \r\n\t\t\tans = 0;\r\n\t\telse if (mxdf == 1) {\r\n\t\t\tans = Math.min(u, v);\r\n\t\t} else {\r\n\t\t\tans = v + Math.min(u, v);\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require(\"readline\");\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nlet input = [];\r\nrl.on('line', line => {\r\n input.push(line);\r\n})\r\nrl.on('close', line => {\r\n var t = Number(input[0]);\r\n var index = 1;\r\n for (var a = 0; a < t; a++) {\r\n var [n, u, v] = input[index].split(\" \").map((i) => {\r\n return Number(i);\r\n });\r\n index++;\r\n var arr = input[index].split(\" \").map((i) => {\r\n return Number(i);\r\n });\r\n index++;\r\n var min = Infinity;\r\n for (var i = 1; i < arr.length; i++) {\r\n if (Math.abs(arr[i] - arr[i - 1]) > 1) {\r\n min = 0;\r\n } else if (Math.abs(arr[i] - arr[i - 1]) === 1) {\r\n min = Math.min(min, u, v);\r\n } else {\r\n min = Math.min(min, u + v, v + v);\r\n }\r\n }\r\n console.log(min);\r\n }\r\n \r\n})"}, {"source_code": "function readStringArray() {\r\n return readline().split(\" \");\r\n}\r\nfunction readNumArray() {\r\n return readStringArray().map(Number);\r\n}\r\n\r\nfunction main() {\r\n var testCasesNum = +readline();\r\n \r\n for (var i = 0; i < testCasesNum; i++) {\r\n var nuv = readNumArray();\r\n var u = nuv[1];\r\n var v = nuv[2];\r\n var arr = readNumArray();\r\n var diff = maxDiff(arr);\r\n if (diff === 2) {\r\n print(0);\r\n }\r\n if (diff === 1) {\r\n print(Math.min(u, v));\r\n }\r\n if (diff === 0) {\r\n print(v + Math.min(u, v));\r\n }\r\n }\r\n}\r\n\r\nfunction maxDiff(arr) {\r\n var max = 0;\r\n for (var j = 1; j < arr.length; j++) {\r\n var diff = Math.abs(arr[j] - arr[j - 1]);\r\n if (diff > max) {\r\n if (diff > 1) {\r\n return 2;\r\n }\r\n max = diff;\r\n }\r\n }\r\n return max;\r\n}\r\nmain();"}, {"source_code": "main = () => {\r\n\tallans=[];\r\n\tt=readInt();\r\n\tfor (_=0;_1){\r\n\t\t\t\thaveLargeGap=true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse if (gap===1) haveOneGap=true;\r\n\t\t}\r\n\t\tif (haveLargeGap) allans.push(0);\r\n\t\telse if (haveOneGap) allans.push(Math.min(u,v));\r\n\t\telse allans.push(v+Math.min(u,v));\r\n\t}\r\n\tmultiLineArrayPrint(allans);\r\n}\r\n\r\nreadInt = () => parseInt(readline());\r\nreadString = () => readline();\r\nreadIntArr = () => readline().split(\" \").map(zzzz => parseInt(zzzz));\r\noneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));\r\nmultiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\\n'));\r\nmultiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\\n'));\r\n\r\nfor (_ = 0; _ < 1; _++) {\r\n\tmain();\r\n}\r\n\r\n// newline for testing\r\n //newline for testing\r\n// codeforces js cannot use \"let\" keyword"}], "negative_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = BigInt(1e9 + 7);\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [n, u, v] = iInpArr();\r\n let arr = iInpArr();\r\n let flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (arr[i] !== arr[i + 1]) {\r\n flag = true;\r\n break;\r\n }\r\n }\r\n if (!flag) {\r\n console.log(u + v);\r\n continue;\r\n }\r\n flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (Math.abs(arr[i] - arr[i + 1]) >= 2) {\r\n console.log(0);\r\n flag = true;\r\n break;\r\n }\r\n }\r\n if (!flag) console.log(Math.min(u, v));\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = BigInt(1e9 + 7);\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [n, u, v] = iInpArr();\r\n let arr = iInpArr();\r\n let flag = false;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (arr[i] !== arr[i + 1]) {\r\n console.log(Math.min(u, v));\r\n flag = true;\r\n break;\r\n }\r\n }\r\n if (!flag) console.log(u + v);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n // var x = new Array(n)\r\n var [n, u, v] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var ans = false\r\n for (let i = 0; i < n - 1; i++) {\r\n if (Math.abs(a[i] - a[i + 1]) > 1) ans = true\r\n }\r\n // console.log('ansans')\r\n // console.log(ans)\r\n // console.log(a)\r\n if (ans) return console.log(0)\r\n\r\n var existOne = false\r\n for (let i = 0; i < n - 1; i++) {\r\n if (a[i] - a[i + 1] === 1) existOne = true\r\n }\r\n\r\n if (existOne) return console.log(Math.min(u, v))\r\n\r\n var min1 = v + v\r\n var min2 = u + v\r\n console.log(Math.min(min1, min2))\r\n\r\n })\r\n}\r\n\r\n"}, {"source_code": "function readStringArray() {\r\n return readline().split(\" \");\r\n}\r\nfunction readNumArray() {\r\n return readStringArray().map(Number);\r\n}\r\n\r\nfunction main() {\r\n var testCasesNum = +readline();\r\n \r\n for (var i = 0; i < testCasesNum; i++) {\r\n var nuv = readNumArray();\r\n var u = nuv[1];\r\n var v = nuv[2];\r\n var arr = readNumArray();\r\n var diff = maxDiff(arr);\r\n if (diff === 2) {\r\n print(0);\r\n }\r\n if (diff === 1) {\r\n print(Math.min(u, v));\r\n }\r\n if (diff === 0) {\r\n print(u + v);\r\n }\r\n }\r\n}\r\n\r\nfunction maxDiff(arr) {\r\n var max = 0;\r\n for (var j = 1; j < arr.length; j++) {\r\n var diff = Math.abs(arr[j] - arr[j - 1]);\r\n if (diff > max) {\r\n if (diff > 1) {\r\n return 2;\r\n }\r\n max = diff;\r\n }\r\n }\r\n return max;\r\n}\r\nmain();"}], "src_uid": "7f502f2fd150a2ded948826960d123cd"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \\le a, b \\le 1000$$$).", "output_spec": "Print $$$t$$$ integers — the required numbers $$$a+b$$$.", "sample_inputs": ["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"], "sample_outputs": ["6\n329\n0\n1110"], "notes": null}, "positive_code": [{"source_code": "var n = readline().split(' ');\n\nfor (var i = 0; i < n; i++) {\n var line = readline().split(' ');\n var x = parseInt(line[0]), y = parseInt(line[1]);\n print(x+y);\n}"}, {"source_code": "var print = this.print || require(\"lol-io\").print;\nvar write = this.write || require(\"lol-io\").write;\nvar readline = this.readline || require(\"lol-io\").readline;\nvar n = readline();\nvar i=0;\nwhile (i < n) {\n a = readline()\n .split(\" \")\n .map((a) => parseInt(a));\n print(a[0]+a[1])\n i++;\n}\n"}, {"source_code": "t=readline();\nwhile(t--){\n\ta=readline().split(\" \");\n\tprint(+a[0] + +a[1]);\n}"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\nvar tt = num[0]; // to store values in different variables.\nvar i;\nfor (i = 0; i < tt; i++) {\n var num2 = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\n var atefeh = num2[0];\n var behzad = num2[1];\n print(atefeh+behzad)\n}\n"}, {"source_code": "var n = Number(readline())\nfor(var i=0;i +x);\n print(a[0] + a[1]);\n}"}, {"source_code": "t = readline();\nwhile (t--) {\n\ta = readline().split(' ');\n\tprint(+a[0] + +a[1]);\n}"}, {"source_code": "var Case = Number(readline());\nwhile(Case--){\n\tvar s = readline().split(\" \");\n var a = Number(s[0]);\n var b = Number(s[1]);\n print(a+b);\n}"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n for (let i = 0; i < n; i++) {\n const result = readLine().split(' ').map(x=> parseInt(x)).reduce((prev, curr)=> curr + prev, 0)\n console.log(result)\n }\n return;\n}\n"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar tmp = nextIntArray();\n\t\toutput[i] = tmp[0] + tmp[1];\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const [a, b] = d.split(' ').map(Number);\n console.log(a + b);\n\n c++;\n});\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x)\n console.log(a+b)\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nfunction doline(t) {\n rl.question(\"\", ab => {\n console.log(ab.split(\" \").reduce((a,b) => a+Number(b),0))\n t == 1 ? rl.close():doline(t-1)\n })\n}\n\nrl.question(\"\", t => doline(Number(t)))\n"}, {"source_code": "raw_input = '';\nprocess.stdin.on('data', input => raw_input += input.toString());\nprocess.stdin.on('end', () => main());\n\nfunction main() {\n const lines = raw_input.split('\\n');\n T = +lines[0];\n for (i = 1; i <= T; i++) {\n [a, b] = lines[i].split(' ').map(i => +i);\n console.log(a + b);\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('ascii');\n\nvar inputString=\"\";\nvar currentLine=0;\n\nprocess.stdin.on('data',function(data){\n\tinputString+=data;\n});\nprocess.stdin.on('end',function(){\n\t inputString=inputString.split('\\n');\n\t main();\n});\n\nfunction readline(){\n\treturn inputString[currentLine++];\n}\nfunction main(){\n\tvar n=readline();\n\tfor(let i=0;i {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 3\n1 3\n100000 100000\n2 2\n\n\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n//----------------------------------------------\n\nfunction yourFunction(arr) {\n return arr[0] + arr[1];\n}\n\n//----------------------------------------------\n\nfunction main() {\n\n const n = parseInt(readLine(), 10);\n for (var i = 0; i < n; i++) {\n const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10));\n\n let result = yourFunction(arr);\n\n console.log(result);\n }\n}"}], "negative_code": [{"source_code": "var l = readline().split(' ');\nvar line = readline().split(' ');\n\nwhile(l[0]--)\nprint(parseInt(line[0]) + parseInt(line[1]));"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n for (let i = 0; i < n; i++) {\n const result = parseInt(readLine(), 10) + parseInt(readLine(), 10);\n console.log(result)\n }\n return;\n}\n"}, {"source_code": "raw_input = '';\nprocess.stdin.on('data', input => raw_input += input.toString());\nprocess.stdin.on('end', () => main());\n\nfunction main() {\n const lines = raw_input.split('\\n').slice(1);\n lines.forEach(line => {\n [a, b] = line.split(' ').map(i => +i);\n console.log(a + b);\n });\n}"}, {"source_code": "function yourFunction(a,b) {\n return a+b;\n}"}, {"source_code": "'use strict';\n\n// const fs = require('fs');\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n//----------------------------------------------\n\nfunction yourFunction(arr) {\n return arr[0] + arr[1];\n}\n\n//----------------------------------------------\n\nfunction main() {\n\n // const n = parseInt(readLine(), 10);\n\n const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10));\n\n let result = yourFunction(arr);\n\n console.log(result);\n}"}], "src_uid": "27ddccc777ef9040284ab6314cbd70e7"} {"nl": {"description": "This is an interactive problem.The jury has a permutation $$$p$$$ of length $$$n$$$ and wants you to guess it. For this, the jury created another permutation $$$q$$$ of length $$$n$$$. Initially, $$$q$$$ is an identity permutation ($$$q_i = i$$$ for all $$$i$$$).You can ask queries to get $$$q_i$$$ for any $$$i$$$ you want. After each query, the jury will change $$$q$$$ in the following way: At first, the jury will create a new permutation $$$q'$$$ of length $$$n$$$ such that $$$q'_i = q_{p_i}$$$ for all $$$i$$$. Then the jury will replace permutation $$$q$$$ with pemutation $$$q'$$$. You can make no more than $$$2n$$$ queries in order to quess $$$p$$$.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) — the number of test cases.", "output_spec": null, "sample_inputs": ["2\n4\n\n3\n\n2\n\n1\n\n4\n\n2\n\n4\n\n4"], "sample_outputs": ["? 3\n\n? 2\n\n? 4\n\n! 4 2 1 3\n\n? 2\n\n? 3\n\n? 2\n\n! 1 3 4 2"], "notes": "NoteIn the first test case the hidden permutation $$$p = [4, 2, 1, 3]$$$.Before the first query $$$q = [1, 2, 3, 4]$$$ so answer for the query will be $$$q_3 = 3$$$.Before the second query $$$q = [4, 2, 1, 3]$$$ so answer for the query will be $$$q_2 = 2$$$.Before the third query $$$q = [3, 2, 4, 1]$$$ so answer for the query will be $$$q_4 = 1$$$.In the second test case the hidden permutation $$$p = [1, 3, 4, 2]$$$.Empty strings are given only for better readability. There will be no empty lines in the testing system."}, "positive_code": [{"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nconst readInt = async function(){\r\n return parseInt(await getLine());\r\n}\r\n\r\nconst readIntArray = async function() {\r\n return (await getLine()).split(' ').map(num => parseInt(num));\r\n}\r\n\r\nlet solve = async () => {\r\n const nsc = await readInt();\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = await readInt();\r\n rl.output.write(`? 1\\n`);\r\n await readInt();\r\n const res = new Array(n + 1);\r\n let total = 1;\r\n const cycle = new Array(n + 1);\r\n let ncycle = 0;\r\n for (let i = 1; i <= n; i++) {\r\n if (!res[i]) {\r\n if (i===n) {\r\n res[n] = n;\r\n break;\r\n }\r\n ncycle = 0;\r\n const beforeTotal = total;\r\n while (true) {\r\n rl.output.write(`? ${i}\\n`);\r\n // console.log(`? ${i}`);\r\n const val = await readInt();\r\n total++;\r\n if (res[val])\r\n break;\r\n res[val] = true;\r\n cycle[ncycle] = val;\r\n ncycle++;\r\n }\r\n let cur = i;\r\n for (let j = (beforeTotal - 1) % ncycle, cnt = 1; cnt <= ncycle + 1; cnt++, j = (j + 1) % ncycle) {\r\n res[cur] = cycle[j];\r\n cur = res[cur];\r\n }\r\n }\r\n }\r\n\r\n rl.output.write(`! ${res.slice(1).join(' ')}\\n`)\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nconst g = main();\ng.next()\nrl.on('line', (input) => {\n // console.log('read', input)\n input.split('\\n').forEach(s => s.trim() && g.next(s))\n});\n\nfunction* main() {\n let input\n\n input = yield 1\n const t = +input\n for (let i = 0; i < t; i++) {\n input = yield 1\n const n = +input\n yield* solve(n)\n }\n process.exit(0)\n}\n\nfunction* solve(n) {\n const ans = Array(n).fill(-1)\n for (let i = 0; i < n; i++) {\n if (ans[i] >= 0) continue\n\n const map = {}\n const arr = []\n while (1) {\n const x = yield* ask(i + 1)\n if (map[x]) break\n\n map[x] = 1\n arr.push(x)\n }\n // the next of `x` is `px`\n for (let j = 0; j < arr.length; j++) {\n ans[arr[j] - 1] = arr[(j + 1) % arr.length]\n }\n }\n console.log(`! ${ans.join(' ')}`)\n}\nfunction* ask(i) {\n console.log(`? ${i}`)\n const x = yield 1\n return +x\n}\n"}], "negative_code": [{"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nconst readInt = async function(){\r\n return parseInt(await getLine());\r\n}\r\n\r\nconst readIntArray = async function() {\r\n return (await getLine()).split(' ').map(num => parseInt(num));\r\n}\r\n\r\nlet solve = async () => {\r\n const nsc = await readInt();\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = await readInt();\r\n console.log(`? 1`);\r\n await readInt();\r\n const res = new Array(n + 1);\r\n let total = 1;\r\n const cycle = new Array(n + 1);\r\n let ncycle = 0;\r\n for (let i = 1; i <= n; i++) {\r\n if (!res[i]) {\r\n if (i===n) {\r\n res[n] = n;\r\n break;\r\n }\r\n ncycle = 0;\r\n const beforeTotal = total;\r\n while (true) {\r\n console.log(`? ${i}`);\r\n const val = await readInt();\r\n total++;\r\n if (res[val])\r\n break;\r\n res[val] = true;\r\n cycle[ncycle] = val;\r\n ncycle++;\r\n }\r\n let cur = i;\r\n for (let j = (total - 2) % ncycle, cnt = 1; cnt <= ncycle; cnt++, j = (j + 1) % ncycle) {\r\n res[cur] = cycle[j];\r\n cur = res[cur];\r\n }\r\n }\r\n }\r\n\r\n console.log(`! ${res.slice(1).join(' ')}`)\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nconst readInt = async function(){\r\n return parseInt(await getLine());\r\n}\r\n\r\nconst readIntArray = async function() {\r\n return (await getLine()).split(' ').map(num => parseInt(num));\r\n}\r\n\r\nlet solve = async () => {\r\n const nsc = await readInt();\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = await readInt();\r\n const res = new Array(n + 1);\r\n let total = 0;\r\n const cycle = new Array(n + 1);\r\n let ncycle = 0;\r\n for (let i = 1; i <= n; i++) {\r\n if (!res[i]) {\r\n ncycle = 0;\r\n const beforeTotal = total;\r\n while (true) {\r\n console.log(`? ${i}`);\r\n const val = await readInt();\r\n total++;\r\n if (res[val])\r\n break;\r\n res[val] = true;\r\n cycle[ncycle] = val;\r\n ncycle++;\r\n }\r\n let cur = i;\r\n for (let j = (total - 1) % ncycle, cnt = 1; cnt <= ncycle; cnt++, j = (j + 1) % ncycle) {\r\n res[cur] = cycle[j];\r\n cur = res[cur];\r\n }\r\n }\r\n }\r\n\r\n console.log(`! ${res.slice(1).join(' ')}`)\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nconst readInt = async function(){\r\n return parseInt(await getLine());\r\n}\r\n\r\nconst readIntArray = async function() {\r\n return (await getLine()).split(' ').map(num => parseInt(num));\r\n}\r\n\r\nlet solve = async () => {\r\n const n = await readInt();\r\n const res = new Array(n+1);\r\n let total = 0;\r\n const cycle = new Array(n + 1);\r\n const was = new Array(n+1);\r\n let ncycle = 0;\r\n for(let i = 1; i <= n; i++) {\r\n if (!res[i]) {\r\n ncycle = 0;\r\n const beforeTotal = total;\r\n while (true) {\r\n console.log(`? ${i}`);\r\n const val = await readInt();\r\n total++;\r\n if (res[val])\r\n break;\r\n res[val] = true;\r\n cycle[ncycle] = val;\r\n ncycle++;\r\n }\r\n let cur = i;\r\n for(let j = (total - 1)%ncycle, cnt=1; cnt<=ncycle; cnt++, j=(j+1)%ncycle) {\r\n res[cur] = cycle[j];\r\n cur = res[cur];\r\n }\r\n }\r\n }\r\n\r\n console.log(`! ${res.slice(1).join(' ')}`)\r\n}\r\n\r\nsolve();\r\n"}], "src_uid": "96ec983bfadc9e96e36ebb8ffc5279d3"} {"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 ≤ n, t1, t2 ≤ 1000; 1 ≤ k ≤ 100) — 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 ≤ i ≤ n) line contains space-separated integers ai, bi (1 ≤ ai, bi ≤ 1000) — 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·3·0.5 + 4·3 > 4·3·0.5 + 2·3. "}, "positive_code": [{"source_code": "var input = readline().trim().split(' ').map((x)=>parseInt(x));\nvar n=input[0],t1=input[1],t2=input[2],k=input[3];\n\n\nvar participant = function(a,b,i) {\n\tthis.a = a;\n\tthis.b =b;\n\tthis.i = i+1;\n\tthis.maxi = Math.max(this.a*t1*(100-k)/100+this.b*t2,this.b*t1*(100-k)/100+this.a*t2).toFixed(2);\n}\nparticipant.prototype.print=function(){\n print(this.i+' '+this.maxi)\n}\nvar p=[];\nvar ab;\nfor (var i = 0; i < n; i++) {\n\tab=readline().trim().split(' ').map((x)=>parseFloat(x));\n\tp.push(new participant(ab[0],ab[1],i));\n}\nvar sort = function(p1,p2) {\n\treturn p1.maxi==p2.maxi?(p1.i-p2.i):(p2.maxi-p1.maxi);\n}\np.sort(sort);\n\nfor (var i in p) {\n\tp[i].print();\n}\n\n"}], "negative_code": [{"source_code": "var input = readline().trim().split(' ').map((x)=>parseInt(x));\nvar n=input[0],t1=input[1],t2=input[2],k=input[3];\n\n\nvar participant = function(a,b,i) {\n\tthis.a = a;\n\tthis.b =b;\n\tthis.i = i+1;\n\tthis.maxi = (parseInt(Math.max(this.a*t1*(100-k)/100+this.b*t2,this.b*t1*(100-k)/100+this.a*t2)*100)*1.0)/100;\n}\nparticipant.prototype.print=function(){\n var out =this.i+' '+this.maxi;\n var m = (this.maxi+'').split('.')[1];\n if(m==undefined)\n out+='.00'\n else if(m.length==0)\n out+='00';\n else if(m.length==1)\n out+='0';\n print(out)\n}\nvar p=[];\nvar ab;\nfor (var i = 0; i < n; i++) {\n\tab=readline().trim().split(' ').map((x)=>parseFloat(x));\n\tp.push(new participant(ab[0],ab[1],i));\n}\nvar sort = function(p1,p2) {\n\treturn p1.maxi==p2.maxi?(p1.i-p2.i):(p2.maxi-p1.maxi);\n}\np.sort(sort);\n\nfor (var i in p) {\n\tp[i].print();\n}\n\n"}], "src_uid": "a89f9310996eb23254d07e52544e30ae"} {"nl": {"description": "This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $$$s$$$).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters.", "output_spec": "In the first line print one integer $$$res$$$ ($$$1 \\le res \\le n$$$) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps. In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array $$$c$$$ of length $$$n$$$, where $$$1 \\le c_i \\le res$$$ and $$$c_i$$$ means the color of the $$$i$$$-th character.", "sample_inputs": ["9\nabacbecfd", "8\naaabbcbb", "7\nabcdedc", "5\nabcde"], "sample_outputs": ["2\n1 1 2 1 2 1 2 1 2", "2\n1 2 1 2 1 2 1 1", "3\n1 1 1 1 1 2 3", "1\n1 1 1 1 1"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nreadline();\nconst x = [ 'a' ], d = [];\nreadline().split('').forEach(c => {\n let i = 0;\n while (c < x[i]) if (++i === x.length) x.push(c);\n x[i] = c;\n d.push(i+1);\n})\nprint(`${Math.max(...d)}\\n${d.join(' ')}`)\n"}, {"source_code": "'use strict'\n\nreadline();\nconst x = [ 'a' ], d = [];\n\nreadline().split('').forEach(c => {\n let i = 0, j = x.length - 1, m;\n if (c < x[j]) j++;\n else if (c >= x[i]) j = i;\n else while(i !== (m = (i + j) >> 1)) if (c < x[m]) i = m; else j = m;\n\n x[j] = c;\n d.push(j+1);\n})\nprint(`${Math.max(...d)}\\n${d.join(' ')}`)\n"}], "negative_code": [{"source_code": "'use strict'\n\nconst problem = (n, s) => {\n const d = { 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 s.forEach((i, j) => d[i].push(j));\n const t = 'abcdefghijklmnopqrstuvwxyz'.split('').filter(i => d[i].length).map(i => d[i]);\n const c = [];\n let a = -1, b = -1;\n\n for (let i = 0; i < t.length; i++) {\n const x = t[i];\n if (x[0] < b) return 'NO';\n\n let j = -1;\n\n while(++j < x.length && x[j] < a) c[x[j]] = 0; j--;\n if (c[x[j]] === 0 && b < x[j]) b = x[j];\n\n while (++j < x.length) c[x[j]] = 1; j--;\n if (c[x[j]] === 1 && a < x[j]) a = x[j];\n };\n return `YES\\n${c.join('')}`;\n}\nprint(problem(+readline(), readline().split('')));\n"}], "src_uid": "2e9da3333792a57e9e3bba4c75542ce7"} {"nl": {"description": "Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), 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 < aj). 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 ≤ n ≤ 5000) — the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), 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": "\nreadline();\nboxes = readline().split(' ');\nboxes.sort();\n\nres = 0;\nfor(var i=0; i< boxes.length; i++){\n var num = 0;\n for (var j = 0; j < boxes.length; j++) {\n if(boxes[j]>num){\n num = boxes[j];\n boxes[j] = 0;\n }\n }\n num>0? res++:0\n}\n\nprint(res);"}], "negative_code": [], "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| < |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 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), 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 000.", "output_spec": "If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print  - 1. 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  - 1.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  - 1."}, "positive_code": [{"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n const n = getInt()\n const cost = getInts()\n const words = []\n const wordsRev = []\n const INF = Number.MAX_SAFE_INTEGER\n\n for (let i = 0; i < n; ++i) {\n const w = getLine()[0]\n words.push(w)\n wordsRev.push(reve(w))\n }\n\n words.push(words[n - 1])\n wordsRev.push(wordsRev[n - 1])\n\n const dp = [[cost[0], 0]]\n for (let i = 1; i <= n; ++i) {\n dp.push([INF, INF])\n\n if (wordsRev[i - 1] <= wordsRev[i]) {\n dp[i][0] = dp[i - 1][0] + cost[i]\n }\n\n if (wordsRev[i - 1] <= words[i]) {\n dp[i][1] = dp[i - 1][0]\n }\n\n if (words[i - 1] <= wordsRev[i]) {\n dp[i][0] = Math.min(dp[i - 1][1] + cost[i], dp[i][0]) \n }\n\n if (words[i - 1] <= words[i]) {\n dp[i][1] = Math.min(dp[i][1], dp[i - 1][1]) \n }\n }\n\n let ans = Math.min(dp[n - 1][0], dp[n - 1][1])\n print(ans !== INF ? ans : -1)\n}\n\nfunction reve(w) {\n return w.split('').reverse().join('')\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n const n = getInt()\n const cost = getInts()\n const words = []\n const INF = Number.MAX_SAFE_INTEGER\n\n for (let i = 0; i < n; ++i) {\n const w = getLine()[0]\n words.push(w)\n }\n\n words.push(words[n - 1])\n\n let ok = true\n const dp = [[cost[0], 0]]\n for (let i = 1; i <= n; ++i) {\n let found = false\n dp.push([INF, INF])\n\n if (reve(words[i - 1]) <= reve(words[i])) {\n dp[i][0] = dp[i - 1][0] + cost[i]\n found = true\n }\n\n if (reve(words[i - 1]) <= words[i]) {\n dp[i][1] = dp[i - 1][0]\n found = true\n }\n\n if (words[i - 1] <= reve(words[i])) {\n dp[i][0] = Math.min(dp[i - 1][1] + cost[i], dp[i][0]) \n found = true\n }\n\n if (words[i - 1] <= words[i]) {\n dp[i][1] = Math.min(dp[i][1], dp[i - 1][1]) \n found = true\n }\n\n if (!found) ok = false\n }\n\n let ans = Math.min(dp[n - 1][0], dp[n - 1][1])\n print(ok && ans !== INF ? ans : -1)\n}\n\nfunction reve(w) {\n return w.split('').reverse().join('')\n}"}], "negative_code": [{"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n const n = getInt()\n const cost = getInts()\n const words = []\n\n for (let i = 0; i < n; ++i) {\n const w = getLine()[0]\n words.push(w)\n }\n\n words.push(words[n - 1])\n\n let ok = true\n const dp = [[cost[0], 0]]\n for (let i = 1; i <= n; ++i) {\n let found = false\n dp.push([1e10, 1e10])\n\n if (reve(words[i - 1]) <= reve(words[i])) {\n dp[i][0] = dp[i - 1][0] + cost[i]\n found = true\n }\n\n if (reve(words[i - 1]) <= words[i]) {\n dp[i][1] = dp[i - 1][0]\n found = true\n }\n\n if (words[i - 1] <= reve(words[i])) {\n dp[i][0] = Math.min(dp[i - 1][1] + cost[i], dp[i][0]) \n found = true\n }\n\n if (words[i - 1] <= words[i]) {\n dp[i][1] = Math.min(dp[i][1], dp[i - 1][1]) \n found = true\n }\n\n if (!found) ok = false\n }\n\n let ans = Math.min(dp[n - 1][0], dp[n - 1][1])\n print(ok ? ans : -1)\n}\n\nfunction reve(w) {\n return w.split('').reverse().join('')\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n const n = getInt()\n const cost = getInts()\n const words = []\n const INF = Number.MAX_SAFE_INTEGER\n\n for (let i = 0; i < n; ++i) {\n const w = getLine()[0]\n words.push(w)\n }\n\n words.push(words[n - 1])\n\n let ok = true\n const dp = [[cost[0], 0]]\n for (let i = 1; i <= n; ++i) {\n let found = false\n dp.push([INF, INF])\n\n if (reve(words[i - 1]) <= reve(words[i])) {\n dp[i][0] = dp[i - 1][0] + cost[i]\n found = true\n }\n\n if (reve(words[i - 1]) <= words[i]) {\n dp[i][1] = dp[i - 1][0]\n found = true\n }\n\n if (words[i - 1] <= reve(words[i])) {\n dp[i][0] = Math.min(dp[i - 1][1] + cost[i], dp[i][0]) \n found = true\n }\n\n if (words[i - 1] <= words[i]) {\n dp[i][1] = Math.min(dp[i][1], dp[i - 1][1]) \n found = true\n }\n\n if (!found) ok = false\n }\n\n let ans = Math.min(dp[n - 1][0], dp[n - 1][1])\n print(ok ? ans : -1)\n}\n\nfunction reve(w) {\n return w.split('').reverse().join('')\n}"}], "src_uid": "91cfd24b8d608eb379f709f4509ecd2d"} {"nl": {"description": "Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods.Help Bender to solve this difficult task.", "input_spec": "The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line.", "output_spec": "If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them.", "sample_inputs": ["4 2\n0 0\n0 2\n2 2\n2 0\n4 4", "6 3\n0 0\n1 0\n1 1\n2 1\n2 2\n0 2\n3 2 3", "6 3\n0 0\n1 0\n1 1\n2 1\n2 2\n0 2\n2 2 3"], "sample_outputs": ["YES\n1 -1 2 -1", "YES\n1 -1 2 -1 3 -1", "NO"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nconst N = lll[0]\nconst M = lll[1]\n\nconst ns = [undefined]\n\nfor (let i = 0; i < N; i++) {\n ns.push(readline().split(' ').map(v => parseInt(v)))\n}\n\nconst ls = readline().split(' ').map(v => parseInt(v))\n\nns[0] = ns[ns.length - 1]\nns.push(ns[1])\n\nconst ds = [undefined]\nfor (let i = 1; i < ns.length - 1; i++) {\n ds.push(getD(ns[i - 1], ns[i], ns[i + 1]))\n}\n\nlet res = []\nlet ppp = 'NO'\nlet lss = JSON.parse(JSON.stringify(ls))\nfor (let i = 1; i < ds.length - 1; i = i + 2) {\n const li = lss.indexOf(ds[i])\n if (~li) {\n res.push(li + 1)\n lss[li] = -1\n } else {\n ppp = 'NO'\n break\n }\n ppp = 'YES'\n}\n\nif (ppp == 'YES') {\n res = res.join(' -1 ')\n res += ' -1'\n}\n\nif (ppp == 'NO') {\n res = []\n for (let i = 2; i < ds.length; i = i + 2) {\n const li = lss.indexOf(ds[i])\n if (~li) {\n res.push(li + 1)\n lss[li] = -1\n } else {\n ppp = 'NO'\n break\n }\n ppp = 'YES'\n }\n}\n\nif (ppp == 'YES' && typeof res != 'string') {\n res = res.join(' -1 ')\n res = '-1 ' + res\n}\n\nif (ppp == 'NO') {\n print('NO')\n} else {\n print('YES')\n print(res)\n}\n\nfunction getD (p1, p2, p3) {\n return Math.abs(p1[0] - p2[0])\n + Math.abs(p1[1] - p2[1])\n + Math.abs(p2[0] - p3[0])\n + Math.abs(p2[1] - p3[1])\n}"}], "negative_code": [], "src_uid": "1112910988c9e7e2836a12c9f5a0b665"} {"nl": {"description": " Ela needs to send a large package from machine $$$1$$$ to machine $$$n$$$ through a network of machines. Currently, with the network condition, she complains that the network is too slow and the package can't arrive in time. Luckily, a Wiring Wizard offered her a helping hand.The network can be represented as an undirected connected graph with $$$n$$$ nodes, each node representing a machine. $$$m$$$ wires are used to connect them. Wire $$$i$$$ is used to connect machines $$$u_i$$$ and $$$v_i$$$, and has a weight $$$w_i$$$. The aforementioned large package, if going through wire $$$i$$$, will move from machine $$$u_i$$$ to machine $$$v_i$$$ (or vice versa) in exactly $$$w_i$$$ microseconds. The Wiring Wizard can use his spell an arbitrary number of times. For each spell, he will choose the wire of index $$$i$$$, connecting machine $$$u_i$$$ and $$$v_i$$$, and rewire it following these steps: Choose one machine that is connected by this wire. Without loss of generality, let's choose $$$v_i$$$. Choose a machine that is currently connecting to $$$v_i$$$ (including $$$u_i$$$), call it $$$t_i$$$. Disconnect the wire indexed $$$i$$$ from $$$v_i$$$, then using it to connect $$$u_i$$$ and $$$t_i$$$. The rewiring of wire $$$i$$$ will takes $$$w_i$$$ microseconds, and the weight of the wire will not change after this operation. After a rewiring, a machine might have some wire connect it with itself. Also, the Wiring Wizard has warned Ela that rewiring might cause temporary disconnections between some machines, but Ela just ignores it anyway. Her mission is to send the large package from machine $$$1$$$ to machine $$$n$$$ as fast as possible. Note that the Wizard can use his spell on a wire zero, one, or many times. To make sure the network works seamlessly while transferring the large package, once the package starts transferring from machine $$$1$$$, the Wiring Wizard cannot use his spell to move wires around anymore.Ela wonders, with the help of the Wiring Wizard, what is the least amount of time needed to transfer the large package from machine $$$1$$$ to $$$n$$$.", "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 contains $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 500$$$, $$$n - 1 \\le m \\le 250 000$$$), the number of nodes and number of wires, respectively. For the next $$$m$$$ lines, $$$i$$$-th line will contains $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$1 \\le w_i \\le 10^9$$$) - the indices 2 machines that are connected by the $$$i$$$-th edge and the weight of it. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$250 000$$$. The graph in each test case is guaranteed to be connected, no self-loops, but it can contain multiple edges.", "output_spec": "For each test case, output one integer denotes the least amount of time needed to transfer the large package from machine $$$1$$$ to $$$n$$$.", "sample_inputs": ["3\n\n8 9\n\n1 2 3\n\n6 4 5\n\n3 5 6\n\n6 1 3\n\n7 4 4\n\n3 8 4\n\n2 3 3\n\n7 8 5\n\n4 5 2\n\n4 5\n\n1 2 1\n\n2 4 1\n\n3 4 1\n\n3 1 1\n\n1 3 2\n\n8 8\n\n4 6 92\n\n7 1 65\n\n6 5 43\n\n6 7 96\n\n4 3 74\n\n4 8 54\n\n7 4 99\n\n2 5 22"], "sample_outputs": ["9\n2\n154"], "notes": "NoteHere is the graph in the first test case in the sample input: Ela can ask the Wiring Wizard to use his spell on wire with the index of $$$7$$$, which is connecting machines $$$2$$$ and $$$3$$$. Then, since the machine $$$8$$$ is connected to machine $$$3$$$, the Wiring Wizard can disconnect wire $$$7$$$ from machine $$$3$$$ and connect it to machine $$$8$$$ in $$$3$$$ microseconds (weight of wire $$$3$$$).After that, the package can be sent from machine $$$1$$$ to machine $$$8$$$ in $$$6$$$ microseconds. Therefore, the answer is $$$3 + 6 = 9$$$ microseconds.Here is the graph in the third test case in the sample input: "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n m = rn(),\r\n edges = new Array(m);\r\n const dist = Array.from({\r\n length: n\r\n }, () => new Array(n).fill(Infinity)),\r\n min = new Array(n).fill(Infinity);\r\n for (let i = 0; i < n; i++) dist[i][i] = 0;\r\n for (let i = 0; i < m; i++) {\r\n let [u, v, c] = rns(3);\r\n u--;\r\n v--;\r\n edges[i] = [u, v, c];\r\n dist[u][v] = 1;\r\n dist[v][u] = 1;\r\n }\r\n for (let k = 0; k < n; k++) {\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < n; j++) {\r\n dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);\r\n }\r\n }\r\n }\r\n for (let i = 0; i < n; i++) {\r\n let ans = Infinity;\r\n for (let j = 0; j < n; j++) {\r\n ans = Math.min(ans, dist[i][j] + dist[j][0] + dist[j][n - 1]);\r\n }\r\n min[i] = ans;\r\n }\r\n let res = Infinity;\r\n for (let [u, v, c] of edges) {\r\n res = Math.min(res, (dist[u][0] + dist[v][n - 1] + 1) * c, (dist[v][0] + dist[u][n - 1] + 1) * c, (min[u] + 2) * c, (min[v] + 2) * c);\r\n }\r\n return res;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "e27ffab64e694b9d612fe100f4c503b8"} {"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, ..., an and p1, ..., pn. 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 ≤ n ≤ 105), the number of days. In the next n lines, i-th line contains two integers ai and pi (1 ≤ ai, pi ≤ 100), 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": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet ans = 0;\nlet minPrice = Infinity;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let [a, p] = d.split(' ').map(Number);\n\n if (a && p) {\n minPrice = Math.min(minPrice, p);\n ans += a * minPrice;\n }\n\n c++;\n});\n\nrl.on('close', () => {\n console.log(ans);\n});\n"}, {"source_code": "const input = [];\n\nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n \nRL.on('line', (line) => {\n input.push(line);\n});\n\nRL.on('close', () => {\n const n = input[0].split(' ').map(x => parseInt(x));\n \n let [meat, cost] = input[1].split(' ').map(x => parseInt(x));\n let answer = meat*cost;\n\n for (let i = 2; i <= n; i += 1) {\n const pair = input[i].split(' ').map(x => parseInt(x));\n if (pair[1] < cost) {\n cost = pair[1];\n }\n answer += pair[0] * cost;\n }\n\n console.log(answer);\n});"}, {"source_code": "//Input\n// ai pi 1 <= ai, pi <= 100\n// var n = \"3\"; var arr = [\"1 3\", \"2 2\", \"3 1\"]; // 10\n// var n = \"3\"; var arr = [\"1 3\", \"2 2\", \"3 2\"]; // 8\n// var n = \"1\"; var arr = [\"39 52\"]; // 2028\n// var n = \"2\"; var arr = [\"125 56\", \"94 17\"]; // 2998\n// var n = \"5\"; var arr = [\"39 213\", \"95 89\", \"70 90\", \"9 55\", \"85 32\"]; // 6321\n// var n = \"12\"; var arr = [\"70 11\", \"74 27\", \"32 11\", \"26 83\", \"57 18\", \"97 28\", \"75 43\", \"75 21\", \"84 29\", \"16 2\", \"89 63\", \"21 88\"]; // 6742\n\nvar n = readline();\n\n// retorno = eval(n, arr);\nretorno = eval(n);\n\n//Solution\n// function eval(n, arr){\nfunction eval(n){\n n = parseInt(n);\n var daysCosts = new Array(n+1).join(\"\").split(\"\");\n\n var arr = \"\";\n for(var i = 0 ; i < n ; i++){\n arr = readline();\n daysCosts[i] = arr.split(\" \").map(function(x){ return parseInt(x)});\n // daysCosts[i] = arr[i].split(\" \").map(function(x){ return parseInt(x)});\n };\n write(giveTheLowestCost(n, daysCosts));\n // console.log(giveTheLowestCost(n, daysCosts));\n};\n\nfunction giveTheLowestCost(n, daysCosts){\n var answer;\n var minimumCost = 0;\n var totalCost = 0;\n //console.log(daysCosts[0]);\n for(var i = 0 ; i < n ; i++){\n if(i == 0){\n minimumCost = daysCosts[i][1];\n totalCost = daysCosts[i][0]*daysCosts[i][1];\n //console.log(\"minimumCost: \" + minimumCost + \" totalCost: \" + totalCost);\n //console.log(\"dayCosts[\" + i + \"][1]: \" + daysCosts[i][1] + \" minimumCost: \" + minimumCost);\n } else{\n if(minimumCost > daysCosts[i][1]){\n minimumCost = daysCosts[i][1];\n };\n totalCost += daysCosts[i][0]*minimumCost;\n //console.log(\"dayCosts[\" + i + \"][1]: \" + daysCosts[i][1] + \" minimumCost: \" + minimumCost);\n };\n };\n\n //console.log(\"minimumCost: \" + minimumCost + \" totalCost: \" + totalCost);\n return totalCost;\n};\n\n\n"}, {"source_code": "function cmp(x){\n\treturn parseInt(x);\n}\nvar n = parseInt(readline());\n\tvar a = [];\n\tfor(var i = 0; i < n; i++)\n\t{\n\t\ta[i] = readline().split(\" \").map(cmp);\n\t}\n\t//var a = [[1,3],[2,1],[3,2]];\n\tvar minimum = 200;\n\tvar sum = 0;\n\tfor(var j = 0; j < n; j ++)\n\t{\n\t\tif(a[j][1] < minimum)\n\t\tminimum = a[j][1];\n\t\tsum += minimum*a[j][0];\n\t}\n\tprint(sum);"}, {"source_code": "var n = readline();///.split(\" \");\nvar str = []; //readline().split(\" \"); \"3 3\".split(\" \"),\"3 3\".split(\" \"),\"3 3\".split(\" \")\nvar min = 100;\nvar sum = 0;\n\t\tfor (var i=0; i<+n; i++){\n\t\t\tstr.push(readline().split(\" \"));\n\t\t}\n\t\t\n\t\tfor (var i=0; i<+n; i++){\n\t\t if (+str[i][1] result - total * p[prev] + total * p[i]) {\n result = result - total * p[prev] + total * p[i];\n prev = i;\n }\n total -= a[i];\n }\n\n print(result);\n}\n\nmain();"}, {"source_code": "\"use strict\";\n\nvar n = +readline();\n\nvar result = 0;\nfor (let i = 0, pmin = +Infinity; i < n; ++i) {\n let input = readline().split(' ').map(value => +value);\n let a = input[0];\n let p = input[1];\n\n pmin = Math.min(pmin, p);\n\n result += a * pmin;\n}\n\nwrite(result);\n"}, {"source_code": "n=Number(readline())\na=new Array(n), p=new Array(n), mm=new Array(n)\nfor (var i=0; i p) {\n m = p;\n }\n\n s += a * m;\n}\n\nwrite(s);\n"}, {"source_code": "// var inputString = \"5\\n2 4\\n2 2\\n2 3\\n2 3\\n2 1\\n\";\n\n// var readline = (function () {\n// var regex = /(.+)\\s/g,\n// i = 0;\n\n// return function () {\n// return inputString.match(regex)[i++].replace(/\\n/g, \"\");\n// }\n// })();\n\n// function write (token) {\n// console.log(token);\n// }\n// function print (token) {\n// console.log(token);\n// }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvar days = parseInt(readline(), 10);\n\nvar meatNeed = [],\n price = [];\n\nvar tempInput = \"\";\nfor (var i = 0; i < days; i++) {\n tempInput = readline().split(\" \");\n price.push(parseInt(tempInput.pop(), 10));\n meatNeed.push(parseInt(tempInput.pop(), 10));\n}\n\nvar minPrice = {};\nminPrice.price = Math.min.apply(null, price);\nminPrice.day = price.indexOf(minPrice.price);\n\nvar minSum = 0;\n\nvar i = 0;\nwhile (i < days) {\n if (price[i] < price[i+1]) {\n var j = i;\n while (price[i] <= price[j]) {\n minSum += price[i] * meatNeed[j];\n j++;\n }\n i = j;\n } else {\n minSum += price[i] * meatNeed[i];\n i++;\n }\n}\n\nwrite(minSum);\n"}, {"source_code": "var n = Number(readline());\nvar inp;\nvar min = 101;\nvar sum = 0;\nfor(var i = 0; i < n ; i++){\n inp = readline().split(\" \").map(cur => Number(cur));\n (inp[1] < min) ? min = inp[1] : null; \n sum += min*inp[0];\n}\n\nprint(sum);"}], "negative_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet ans = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let [a, p] = d.split(' ').map(Number);\n\n ans += a * p;\n c++;\n});\n\nrl.on('close', () => {\n console.log(ans);\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet ans = 0;\nlet minPrice = Infinity;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let [a, p] = d.split(' ').map(Number);\n minPrice = Math.min(minPrice, p);\n\n ans += a * minPrice;\n c++;\n});\n\nrl.on('close', () => {\n console.log(ans);\n});\n"}, {"source_code": "var n = parseInt(readline());\n\tvar a = [];\n\tfor(var i = 0; i < n; i++)\n\t{\n\t\ta[i] = readline().split(\" \").map(function(elment){return parseInt(elment);});\n\t}\n\t\n\t//var a=[[1,3],[2,1],[3,2]];\n\tvar minimum = 200;\n\tvar temp;\n\tfor(var j = 0; j < n; j++)\n\t{\n\t\tminimum = Math.min(minimum,a[j][1]);\n\t}\n\tfor(var k = 0; k < n; k++)\n\t{\n\t\tif(minimum === a[k][1])\n\t\t{\n\t\t\ttemp = k;\n\t\t\tbreak;\n\t\t}\n\t}\n\tvar ans=0;\n\tfor(var l = 0; l <= temp; l++)\n\t{\n\t\tans += a[l][0]*a[l][1]; \n\t}\n\tfor(var u = temp+1; u < n; u++)\n\t{\n\t\tans += a[u][0]*minimum;\n\t}\n\tprint(ans);"}, {"source_code": "var n = readline();///.split(\" \");\nvar str = []; //readline().split(\" \");\nvar min = 100;\nvar sum = 0;\n\t\tfor (var i=0; i<+n; i++){\n\t\t\tstr.push([readline().split(\" \")]);\n\t\t}\n\t\t\n\t\tfor (var i=0; i<+n; i++){\n\t\t if (+str[i][1] result - total * p[i - 1] + total * p[i]) {\n result = result - total * p[i - 1] + total * p[i];\n }\n total -= a[i];\n }\n\n print(result);\n}\n\nmain();"}, {"source_code": "// var inputString = \"3\\n1 3\\n2 1\\n3 2\\n\";\n\n// var readline = (function () {\n// var regex = /(.+)\\s/g,\n// i = 0;\n\n// return function () {\n// return inputString.match(regex)[i++].replace(/\\n/g, \"\");\n// }\n// })();\n\n// function write (token) {\n// console.log(token);\n// }\n// function print (token) {\n// console.log(token);\n// }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvar days = parseInt(readline(), 10);\n\nvar meatNeed = [],\n price = [];\n\nvar tempInput = \"\";\nfor (var i = 0; i < days; i++) {\n tempInput = readline().split(\" \");\n price.push(parseInt(tempInput.pop(), 10));\n meatNeed.push(parseInt(tempInput.pop(), 10));\n}\n\nvar minPrice = {};\nminPrice.price = Math.min.apply(null, price);\nminPrice.day = price.indexOf(minPrice.price);\n\nvar minSum = 0;\n\nfor (var i = 0; i < days; i++) {\n if (i < minPrice.day) {\n minSum += meatNeed.shift() * price.shift();\n } else {\n minSum += meatNeed.reduce(function (sum, cur) {\n return sum + cur * minPrice.price;\n }, 0) * minPrice.price;\n break;\n }\n}\n\nwrite(minSum);\n"}, {"source_code": "// var inputString = \"5\\n5 5\\n4 4\\n3 3\\n2 2\\n2 2\\n\";\n\n// var readline = (function () {\n// var regex = /(.+)\\s/g,\n// i = 0;\n\n// return function () {\n// return inputString.match(regex)[i++].replace(/\\n/g, \"\");\n// }\n// })();\n\n// function write (token) {\n// console.log(token);\n// }\n// function print (token) {\n// console.log(token);\n// }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvar days = parseInt(readline(), 10);\n\nvar meatNeed = [],\n price = [];\n\nvar tempInput = \"\";\nfor (var i = 0; i < days; i++) {\n tempInput = readline().split(\" \");\n price.push(parseInt(tempInput.pop(), 10));\n meatNeed.push(parseInt(tempInput.pop(), 10));\n}\n\nvar minPrice = {};\nminPrice.price = Math.min.apply(null, price);\nminPrice.day = price.indexOf(minPrice.price);\n\nvar minSum = 0;\n\nfor (var i = 0; i < days; i++) {\n if (i < minPrice.day) {\n minSum += meatNeed.shift() * price.shift();\n } else {\n minSum += meatNeed.reduce(function (sum, cur) {\n return sum + cur * minPrice.price;\n }, 0);\n break;\n }\n}\n\nwrite(minSum);\n"}], "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 ≤  n ≤ 100). The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a1, a2, ..., ap (1 ≤ ai ≤ n). 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": "var n = parseInt(readline(), 10);\nvar p = readline().split(' ').map(el => parseInt(el, 10));\nvar q = readline().split(' ').map(el => parseInt(el, 10));\n\np.shift();\nq.shift();\n\nvar comboArray = [...new Set([...p, ...q])].sort((a,b) => a-b);\n\nprint((comboArray.length === n) ? \"I become the guy.\" : \"Oh, my keyboard!\");"}, {"source_code": "var tok=null;\nvar index=0;\nfunction next(){\n while(tok==null || index==tok.length){\n tok=readline().split(' ');\n index=0;\n }\n var res=tok[index++];\n return res;\n}\n\nfunction nextInt(){\n return parseInt(next());\n}\n\nfunction check(s){\n arrS=s.split(\" \");\n for(var i=1; i a-b);\n\naq[0] = -1;\naq.sort((a, b) => a-b);\n\nvar passable = true;\nvar i = 1;\nvar ip = 1;\nvar iq = 1;\n\nfor (i = 1; i <= n; i++) {\n if (ap[ip] < i) {\n ip++;\n }\n if (aq[iq] < i) {\n iq++;\n }\n if (ap[ip] != i && aq[iq] != i) {\n passable = false;\n break;\n }\n}\n\nif (passable) {\n write(\"I become the guy.\");\n} else {\n write(\"Oh, my keyboard!\");\n}"}, {"source_code": "var line = readline();\nvar n = parseInt(line);\n\nvar x = readline().split(' ').map(Number);\nvar p = x[0];\n\nvar y = readline().split(' ').map(Number);\nvar q = y[0];\n\nvar array=[];\n\nfor(i=0;i0){\n\tlevels+=1;\n }\n}\n\n//print(levels);\n\nif(levels===n){\n print('I become the guy.');\n} else{\n print('Oh, my keyboard!');\n}"}, {"source_code": "var n = +readline();\nvar input;\n\ninput = readline().split(' ');\nvar X = input.slice(1);\n\ninput = readline().split(' ');\nvar Y = input.slice(1);\n\nwrite(new Set(X.concat(Y)).size === n ? 'I become the guy.' : 'Oh, my keyboard!');"}, {"source_code": "var noLevels = parseInt(readline());\n \nvar xLevels = readline().split(\" \").map(function(x) { return parseInt(x) });\n \nvar yLevels = readline().split(\" \").map(function(y) { return parseInt(y) });\n \n// Remove number of levels\nxLevels.splice(0, 1);\nyLevels.splice(0, 1);\n \n// Remove duplicates\n\nvar res = xLevels.concat(yLevels);\nvar allLevelSet = new Set(xLevels.concat(yLevels));\n\n\nif (noLevels == allLevelSet.size)\n print(\"I become the guy.\");\n\nelse\n print(\"Oh, my keyboard!\");"}, {"source_code": "var n = Number(readline());\nvar s1 = readline().split(\" \");\nvar s2 = readline().split(\" \");\nvar obj = {};\nfor(var i=1; i parseInt(x));\nX.shift();\nvar Y = readline().slice().split(' ').map(x => parseInt(x));\nY.shift();\nvar set = new Set([...X,...Y]);\nif (set.size === n && Math.max(...set) === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\n\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice().split(' ').map(x => parseInt(x));\nX.shift();\nvar Y = readline().slice().split(' ').map(x => parseInt(x));\nY.shift();\nvar set = new Set([...X,...Y]);\nif (set.has(1) && set.size === n && Math.max(...set) === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\n\n"}, {"source_code": "var total = parseInt(readline());\nvar p = readline().split(\" \").map(Number);\nvar q = readline().split(\" \").map(Number);\n\nvar se = new Set([...p.slice(1), ...q.slice(1)]);\n\nif (se.size === total) {\n print(\"I become the guy.\");\n} else {\n print(\"Oh, my keyboard!\");\n}\n"}, {"source_code": "var n = +readline(), x = readline().split(\" \"), y = readline().split(\" \");\n\nif( (+x[0] + +y[0]) < n ){\n\twrite(\"Oh, my keyboard!\");\n}\nelse{\n\tx.shift();\n\ty.shift();\n\n\tx = x.concat(y).sort(function(a,b){return (a-b)});\n\t\n\tfor(i = 1; i <= n ; i++){\n\t\tif( x.indexOf(i.toString(10)) + 1 ){\n\t\t\tcontinue;\n\t\t}\n\t\telse{\n\t\t\twrite(\"Oh, my keyboard!\");\n\t\t\tbreak;\n\t\t}\n\t}\n\tif( i == (n+1) ){\n\t\twrite(\"I become the guy.\");\n\t}\n}"}, {"source_code": "var arr=[];\nvar N = readline();\nvar X = readline().split(' ').map(Number);\nvar Y = readline().split(' ').map(Number);\nfor (var i=1; i<=X[0]; i++) {\narr.push(X[i]);\n}\nfor (var j=1; j<=Y[0]; j++) {\narr.push(Y[j]);\n}\narr.sort(function(a, b){return a-b});\nvar namU = arr.length ? 1 : 0;\nfor (var t=1; tarr[t-1]) {\nnamU += 1;\n}\n}\nif (namU == N) {\nprint ('I become the guy.');\n} else {\nprint ('Oh, my keyboard!');\n}"}, {"source_code": "var filter = function(value, index, self){\n if (value === 0) return false;\n else if (value > levels) return false;\n else return self.indexOf(value) == index;\n};\n\nvar levels = parseInt(readline());\n\nvar m1 = readline().split(' ').map(parseFloat);\nm1.splice(0,1);\n\nvar m2 = readline().split(' ').map(parseFloat);\nm2.splice(0,1);\n\nvar result = m1.concat(m2).filter(filter);\n\nprint((result.length === levels) ? 'I become the guy.' : 'Oh, my keyboard!');"}, {"source_code": " var numberOfLevel = Number(readline())\n var levelAcomplished = new Array(numberOfLevel).fill(0)\n\n var infoPlayerA = readline().split(' ').map(Number)\n var infoPlayerB = readline().split(' ').map(Number)\n\n var levelAcomplishedByPlayerA = infoPlayerA[0]\n for (var i = 1; i <= levelAcomplishedByPlayerA; i++) {\n var level = infoPlayerA[i]\n levelAcomplished[level - 1] += 1\n }\n\n var levelAcomplishedByPlayerB = infoPlayerB[0]\n for (var i = 1; i <= levelAcomplishedByPlayerB; i++) {\n var level = infoPlayerB[i]\n levelAcomplished[level - 1] += 1\n }\n\n var allLevelAccomplished = true\n for (var i = 0; i < levelAcomplished.length; i++) {\n if (levelAcomplished[i] === 0) {\n allLevelAccomplished = false\n break;\n }\n }\n\n if (allLevelAccomplished) {\n print('I become the guy.')\n } else {\n print('Oh, my keyboard!')\n }"}, {"source_code": "var num_games = parseInt(readline());\nvar x = readline().split(\" \").map(x=>parseInt(x));\nvar y = readline().split(\" \").map(x=>parseInt(x));\nvar total = [...new Set([...x.splice(1),...y.splice(1)])];\nif(total.length == num_games){\n print(\"I become the guy.\");\n}else{\n print(\"Oh, my keyboard!\")\n}"}, {"source_code": ";(function () {\n\tprint(function (n) {\n\t\tvar l = [], k = 2;\n\t\twhile (k--) {\n\t\t\tvar newValues = readline().split(' ').map(Number);\n\t\t\tnewValues.splice(0, 1);\n\t\t\tl.push.apply(l, newValues);\n\t\t}\n\n\t\twhile (n--) {\n\t\t\tif (l.indexOf(n + 1) === -1) {\n\t\t\t\treturn 'Oh, my keyboard!';\n\t\t\t}\n\t\t}\n\n\t\treturn 'I become the guy.';\n\t}(+readline()));\n}.call(this));"}, {"source_code": "var n = Number(readline());\nvar s1 = readline().split(\" \");\nvar s2 = readline().split(\" \");\nvar obj = {};\nfor(var i=1; i= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != '\\t'.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = -1;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) || this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == '\\t'.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );\n }\n if( endIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n else {\n this.currrentCharacterIndex = endIdx;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n if( currentDirectory.charAt( 1 ) != \":\" ) {\n //not local machine/windows\n outputFilePath = outputFileName;\n }\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCode = function() {\n var testCases , i , hasMoreTestCases , isLocalMachine , localContext;\n isLocalMachine = false;\n try {\n if( __dirname != null && __dirname.charAt( 1 ) == ':' ) {\n //only on windows\n isLocalMachine = true;\n }\n }\n catch( ex ) {\n isLocalMachine = false;\n }\n if( isLocalMachine == true ) {\n //local machine runs on node and relies on file i/o\n print = console.log;\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n }\n else {\n //server machine\n try {\n var rlObj = readline;\n //server runs on javasctipt v8 distribution and has readline method on global context\n this.irObj.readAllLines();\n }\n catch( ex ) {\n try {\n var pObj = process;\n //server runs on node\n print = console.log;\n this.irObj.readAllLinesFromNodeStdin();\n }\n catch( ex ) {\n try {\n var ipObj = importPackage;\n //server runs on rhino\n this.irObj.readAllLinesFromRhinoStdin();\n }\n catch( ex ) {\n throw new Error( \"Unknown javasctipt distribution!\" );\n }\n }\n }\n }\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n //only works for local machine(tested)\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.runCode();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "'use strict';\nvar n = parseInt(readline()),\n x = readline().split(' ').map((value) => parseInt(value)),\n y = readline().split(' ').map((value) => parseInt(value));\n\nx.shift();\ny.shift();\n \nlet resolve = () => {\n for(let i = 1; i<=n; i++) {\n if(x.indexOf(i) === -1 && y.indexOf(i) === -1) {\n return write('Oh, my keyboard!');\n }\n }\n \n return write('I become the guy.');\n}\n\n\nresolve();\n"}, {"source_code": "var n = readline();\nvar x = readline().slice(1).split(\" \");\nvar y = readline().slice(1).split(\" \");\nvar c = new Set(x.concat(y).sort((x,y)=>x-y)); \nvar r =1;\n\tfor (var i=1; i<+n+1; i++){\n\t\tif (c.has(i.toString())==false) {r=0; break;}\n\t}\n\tr==0? print(\"Oh, my keyboard!\"):print(\"I become the guy.\");"}, {"source_code": "/* Actually the first code is not the true one, if you try it with input\n\n\t\t\t\t\t\t\t\"3\n\t\t\t\t\t\t\t 1 2\n\t\t\t\t\t\t\t 2 2 3\"\n it says \"Oh, my keyboard!\", and somehow the site accept this output as the true value, i commented the true algorithm below down in the comment \n \n*/\n\nvar n = Number(readline());\nvar s1 = readline().split(\" \");\nvar s2 = readline().split(\" \");\nvar obj = {};\n\nfor(var i=1; i arr1.length) return \"Oh, my keyboard!\";\n for (var i = 1; i <= arr1.length - 1; i++)\n {\n if (arr1[i] !== arr1[i - 1]) count++;\n }\n\tif (count === n) return \"I become the guy.\";\n\telse return \"Oh, my keyboard!\";\n}\nvar num = +readline();\nvar input1 = readline();\nvar input2 = readline();\n\nprint(becomingTheGuy(num, input1, input2));"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n alist.shift();\n var blist = nextIntArray();\n blist.shift();\n var pass = new Set();\n for(var i = 0; i < alist.length; i++){\n if(alist[i] != 0){\n pass.add(alist[i]);\n }\n }\n for(var i = 0; i < blist.length; i++){\n if(blist[i] != 0){\n pass.add(blist[i]);\n }\n }\n if(pass.size == N){\n myout(\"I become the guy.\");\n }else{\n myout(\"Oh, my keyboard!\");\n }\n}\n"}, {"source_code": "var stdin = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\nprocess.stdin.on(\"data\", function(data) {\n stdin += data;\n});\nprocess.stdin.on(\"end\", function() {\n main(stdin);\n});\n\n// const stdin = `4\n// 3 1 2 3\n// 2 2 3`;\n// main(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n let currentLine = 0;\n const res = readLine(stdin, currentLine);\n const resSet = new Set();\n\n while (2 > currentLine) {\n ++currentLine;\n const levels = readLine(stdin, currentLine)\n .split(\" \")\n .splice(1);\n\n levels.forEach(l => resSet.add(l));\n }\n\n console.log(resSet.size == res ? \"I become the guy.\" : \"Oh, my keyboard!\");\n}\n\nfunction readLine(str, line) {\n return str.split(/\\r?\\n/).filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "const readline = require('readline');\n\nlet inputs = [];\nconst mod = 10 ** 9;\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = parseInt(inputs[0]);\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n\n check([...x, ...y], n)\n})\n\n\nfunction check(co, n) {\n\n\n const union = co.sort((a, b) => a - b);\n const levels = [];\n const expected = [];\n\n for (let i = 1; i <= n; i++) {\n expected.push(i)\n }\n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n if (levels.toString() == expected.toString())\n return console.log(\"I become the guy.\")\n else\n return console.log(\"Oh, my keyboard!\")\n\n}\n\n\n\n// Get Factorial\nfunction factorial(n, temp) {\n\n let result = temp || 1;\n\n if (n > 1) {\n result *= n;\n result %= mod;\n n--\n return factorial(n, result)\n }\n return result\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a, b, n;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n n = +d;\n return;\n }\n\n if (c === 1) {\n a = d.split(' ').map(Number);\n c++;\n return;\n }\n\n b = d.split(' ').map(Number);\n\n c++;\n});\n\nrl.on('close', () => {\n const obj = {};\n let ans = 'I become the guy.';\n\n c = a.concat(b);\n\n c = c.sort((x, y) => x - y);\n\n let count = 0;\n for(let i = 0 ; i < a.length+b.length; i++) {\n if(c[i] != c[i+1]){\n count++;\n }\n }\n\n for (let i = 1; i < a.length; i++) {\n obj[a[i]] = true;\n }\n\n for (let i = 1; i < b.length; i++) {\n obj[b[i]] = true;\n }\n\n for (let i = 1; i <= n; i++) {\n if (!obj.hasOwnProperty(i)) {\n ans = 'Oh, my keyboard!';\n break;\n }\n }\n\n console.log(ans);\n});\n"}, {"source_code": "const readLine = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst input = [];\nreadLine.on('line', line => input.push(line));\n\nreadLine.on('close', () => {\n const n = parseInt(input[0]);\n\n const set = new Set();\n\n const firstGamer = input[1].split(' ').map(x => parseInt(x)).forEach((x, i) => i !== 0 ? set.add(x) : null);\n const secondGamer = input[2].split(' ').map(x => parseInt(x)).forEach((x, i) => i !== 0 ? set.add(x) : null);\n\n console.log(set.size === n ? \"I become the guy.\" : \"Oh, my keyboard!\");\n});"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('');\nrl.prompt();\nlet promptCounter = 0\n\nlet n, p, q, x, y;\n\nrl.on('line', function (line) {\n promptCounter++;\n //first line\n if (promptCounter === 1) {\n n = Number(line);\n rl.prompt();\n } else if (promptCounter === 2) {\n x = line.split(' ').map(el => Number(el));\n x.shift();\n // console.log(`x: ${x}`);\n rl.prompt();\n } else {\n y = line.split(' ').map(el => Number(el));\n y.shift();\n // console.log(`y: ${y}`);\n let set = new Set(x.concat(y));\n let sum = 0;\n set.forEach(el => sum += el);\n // console.log(`sum: ${sum}`);\n let refSum = Array(n).fill().map((_, i) => i + 1).reduce((p, c) => p + c);\n // console.log(`refSumArray: ${Array(n).fill().map((_, i) => i + 1)}`)\n // console.log(`refSum: ${refSum}`);\n if (sum === refSum) console.log('I become the guy.');\n else console.log('Oh, my keyboard!');\n rl.close();\n }\n});"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet t=+readLine()\n\tlet x=readLine().split(\" \").map(n=>+n)\n\tlet y=readLine().split(\" \").map(n=>+n)\n\n\tlet s=new Set()\n\n\tfor(let i=1;i input.push(line));\n\nconst theGuy = () => {\n let n = +input[0];\n\n let count = 0;\n let x = input[1].split(' ').map(x => +x);\n let y = input[2].split(' ').map(x => +x);\n x.shift();\n y.shift();\n let s = new Set([...x, ...y]);\n\n if (s.size === n) {\n console.log('I become the guy.');\n }\n else {\n console.log('Oh, my keyboard!')\n }\n};\n\nreadLine.on('close', theGuy);"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let X = readLine().split(' ').map(value => parseInt(value));\n let Y = readLine().split(' ').map(value => parseInt(value));\n let XY = [...new Set(X.slice(1, X.length).concat(Y.slice(1, Y.length)))].filter(value => value >= 1);\n if (XY.length == n) {\n console.log('I become the guy.');\n } else {\n console.log('Oh, my keyboard!')\n }\n}"}], "negative_code": [{"source_code": "var tok=null;\nvar index=0;\nfunction next(){\n while(tok==null || index==tok.length){\n tok=readline().split(' ');\n index=0;\n }\n var res=tok[index++];\n return res;\n}\n\nfunction nextInt(){\n return parseInt(next());\n}\n\nfunction check(s){\n arrS=s.split(\" \");\n for(var i=0; i parseInt(x));\nvar Y = readline().slice(2).split(' ').map(x => parseInt(x));\nvar set = new Set([...X,...Y]);\nvar set1 = new Set([...X]);\nvar set2 = new Set([...Y]);\nvar reachesN = Math.max(...set) === n;\nvar startsWithOne = Math.min(...set) === 1;\nif (reachesN && startsWithOne && set.size === n) print('I become the guy.');\nelse {\n if (X.map(x => x.toString()).join(' ') === '34 66 1 54 31 94 82 83 38 23 25 59 87 9 20 84 56 60 78 6 48 74 7 61 85 3 24 43 49 37 62 4 71 53 16 10 18 42 5 58 97 92 29 44 90 91 32 67 13 76 69 17 100 39 93 12 19 8 2 46 79 41 63 72 86 26 89 73 15 50 77 33 45 28 21 36 95 64 22 81 14 30 80 98 99 75 70 96 47 35 11 68 88 52') {\n print(set1.size)\n print(set2.size);\n print(Math.min(...set1));\n print(Math.max(...set1));\n print(Math.min(...set2))\n print(Math.max(...set2));\n}\n print('Oh, my keyboard!')\n};\n\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice(2).split(' ').map(x => parseInt(x));\nvar Y = readline().slice(2).split(' ').map(x => parseInt(x));\nvar set = new Set([...X,...Y]);\nvar reachesN = Math.max(...set) === n;\nvar startsWithOne = Math.min(...set) === 1;\nprint(set.size);\nprint(reachesN);\nprint(startsWithOne);\nif (reachesN && startsWithOne && set.size === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice(2).split(' ').map(x => parseInt(x));\nvar Y = readline().slice(2).split(' ').map(x => parseInt(x));\nvar set = new Set([...X,...Y]);\nvar reachesN = Math.max(...set) === n;\nvar startsWithOne = Math.min(...set) === 1;\nif (reachesN && startsWithOne && set.size === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice().split(' ').map(x => parseInt(x));\nX.shift();\nvar Y = readline().slice().split(' ').map(x => parseInt(x));\nY.shift();\nvar set = new Set([...X,...Y]);\nif (Math.max(...set) === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\n\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice(2).split(' ').map(x => parseInt(x));\nvar Y = readline().slice(2).split(' ').map(x => parseInt(x));\nvar set = new Set([...X,...Y]);\nvar set1 = new Set([...X]);\nvar set2 = new Set([...Y]);\nvar reachesN = Math.max(...set) === n;\nvar startsWithOne = Math.min(...set) === 1;\nif (reachesN && startsWithOne && set.size === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\nif (X.map(x => x.toString()).join(' ') === '94 34 66 1 54 31 94 82 83 38 23 25 59 87 9 20 84 56 60 78 6 48 74 7 61 85 3 24 43 49 37 62 4 71 53 16 10 18 42 5 58 97 92 29 44 90 91 32 67 13 76 69 17 100 39 93 12 19 8 2 46 79 41 63 72 86 26 89 73 15 50 77 33 45 28 21 36 95 64 22 81 14 30 80 98 99 75 70 96 47 35 11 68 88 52') {\n print(set1.size)\n print(set2.size);\n print(Math.min(...set1));\n print(Math.max(...set1));\n print(Math.min(...set2))\n print(Math.max(...set2));\n}\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice(2).split(' ').map(x => parseInt(x));\nvar Y = readline().slice(2).split(' ').map(x => parseInt(x));\nvar set = new Set([...X,...Y]);\nif (Math.max(...set) === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\n\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice(3).split(' ').map(x => parseInt(x));\nvar Y = readline().slice(3).split(' ').map(x => parseInt(x));\nvar set = new Set([...X,...Y]);\nif (Math.max(...set) === n) print('I become the guy.');\nelse print('Oh, my keyboard!');\n\n"}, {"source_code": "var n = parseInt(readline());\nvar X = readline().slice(2).split(' ').map(x => parseInt(x));\nvar Y = readline().slice(2).split(' ').map(x => parseInt(x));\nvar set = new Set([...X,...Y]);\nvar set1 = new Set([...X]);\nvar set2 = new Set([...Y]);\nvar reachesN = Math.max(...set) === n;\nvar startsWithOne = Math.min(...set) === 1;\nif (reachesN && startsWithOne && set.size === n) print('I become the guy.');\nelse {\n if (X.map(x => x.toString()).join(' ') === '94 34 66 1 54 31 94 82 83 38 23 25 59 87 9 20 84 56 60 78 6 48 74 7 61 85 3 24 43 49 37 62 4 71 53 16 10 18 42 5 58 97 92 29 44 90 91 32 67 13 76 69 17 100 39 93 12 19 8 2 46 79 41 63 72 86 26 89 73 15 50 77 33 45 28 21 36 95 64 22 81 14 30 80 98 99 75 70 96 47 35 11 68 88 52') {\n print(set1.size)\n print(set2.size);\n print(Math.min(...set1));\n print(Math.max(...set1));\n print(Math.min(...set2))\n print(Math.max(...set2));\n}\n print('Oh, my keyboard!')\n};\n\n"}, {"source_code": "var arr=[];\nvar namU = 0;\nvar N = readline();\nvar X = readline().split(' ').map(Number);\nvar Y = readline().split(' ').map(Number);\nfor (var i=1; i<=X[0]; i++) {\narr.push(X[i]);\n}\nfor (var j=1; j<=Y[0]; j++) {\narr.push(Y[j]);\n}\narr.sort(function(a, b){return a-b});\nfor (var t=1; tarr[t-1]) {\nnamU += 1;\n}\n}\nif (namU == N-1) {\nprint ('I become the guy.');\n} else {\nprint ('Oh, my keyboard!');\n}\n "}, {"source_code": "var arr=[];\nvar namU;\nvar N = readline();\nvar X = readline().split(' ').map(Number);\nvar Y = readline().split(' ').map(Number);\nfor (var i=1; i<=X[0]; i++) {\narr.push(X[i]);\n}\nfor (var j=1; j<=Y[0]; j++) {\narr.push(Y[j]);\n}\narr.sort(function(a, b){return a-b});\nfor (var t=1; tarr[t-1]) {\nnamU +=1;\n}\n}\nif (namU == N) {\nprint ('I become the guy.');\n} else {\nprint ('Oh, my keyboard!');\n}\n "}, {"source_code": "var levels = parseInt(readline());\nvar gamer1 = readline().split(' ').map(parseInt);\nvar gamer2 = readline().split(' ').map(parseInt);\n\nvar ok = [];\n\nfor (var i = 0; i < 4; i++) {\n \n x = gamer1.indexOf(i);\n if (x) ok[i] = i;\n \n y = gamer2.indexOf(i);\n if (y) ok[i] = i; \n \n \n}\n\n\nif (ok.length == levels) print('I become the guy.');\nelse print('Oh, my keyboard!');"}, {"source_code": "var filter = function(value, index, self){\n if (value === 0) return false;\n else if (value > levels) return false;\n else return self.indexOf(value) == index;\n};\n\nvar levels = parseInt(readline());\n\nvar result = readline().split(' ').slice(0,1)\n .concat(readline().split(' ').slice(0,1))\n .map(parseFloat)\n .filter(filter)\n .length;\n\n\nprint((result === levels) ? 'I become the guy.' : 'Oh, my keyboard!');"}, {"source_code": "var levels = parseInt(readline());\nvar gamer1 = readline().split(' ');\nvar gamer2 = readline().split(' ');\n\nvar ok = [];\n\nok = gamer1.concat(gamer2).filter(function(value, index, self){\n return self.indexOf(value) == index;\n});\n\n\nif (ok.length === levels) print('I become the guy.');\nelse print('Oh, my keyboard!');"}, {"source_code": "var filter = function(value, index, self){\n if (value === 0) return false;\n else if (value > levels) return false;\n else return self.indexOf(value) == index;\n};\n\nvar levels = parseInt(readline());\n\nvar line1 = readline().split(' ').map(parseFloat);\nvar line2 = readline().split(' ').map(parseFloat).concat(line1).filter(filter);\n\n\nprint((line2.length === levels) ? 'I become the guy.' : 'Oh, my keyboard!');"}, {"source_code": "var levels = parseInt(readline());\nvar gamer1 = readline().split(' ').map(parseFloat);\nvar gamer2 = readline().split(' ').map(parseFloat);\n\n\n\nvar ok = [];\n\nok = gamer1.concat(gamer2).filter(function(value, index, self){\n if (value === 0) return false;\n return self.indexOf(value) == index;\n});\n\n\nif (ok.length === levels) print('I become the guy.');\nelse print('Oh, my keyboard!');"}, {"source_code": "var levels = parseInt(readline());\nvar gamer1 = readline().split(' ');\nvar gamer2 = readline().split(' ');\n\nvar ok = [];\n\nok = gamer1.concat(gamer2).filter(function(value, index, self){return self.indexOf(value) == index});\n\n\nif (ok.length == levels) print('I become the guy.');\nelse print('Oh, my keyboard!');"}, {"source_code": "var num_games = parseInt(readline());\nvar x = readline().split(\"\").map(x=>parseInt(x));\nvar y = readline().split(\"\").map(x=>parseInt(x));\nvar total = [...x.splice(1),...y.splice(1)].filter((v,i,a)=>a.indexOf(v)===i);\nprint(total);\n"}, {"source_code": "var num_games = parseInt(readline());\nvar x = readline().split(\"\").map(x=>parseInt(x));\nvar y = readline().split(\"\").map(x=>parseInt(x));\nvar total = [...new Set(x.splice(1)),...new Set(y.splice(1))]\nif(total.length == num_games){\n print(\"I become the guy.\");\n}else{\n print(\"Oh, my keyboard!\")\n}"}, {"source_code": "var num_games = parseInt(readline());\nvar x = readline().split(\"\").map(x=>parseInt(x));\nvar y = readline().split(\"\").map(x=>parseInt(x));\nvar total = [...x.splice(1),...y.splice(1)].filter((v,i,a)=>a.indexOf(v)===i);\nif(total.length == num_games){\n print(\"I become the guy.\");\n}else{\n print(\"Oh, my keyboard!\")\n}"}, {"source_code": ";(function () {\n\tprint(function (n) {\n\t\tvar l = [], k = 2;\n\t\twhile (k--) {\n\t\t\tvar newValues = readline().split(' ').map(Number);\n\t\t\tnewValues.splice(0, 1);\n\t\t\tl.concat(newValues);\n\t\t}\n\n\t\twhile (n--) {\n\t\t\tif (l.indexOf(n + 1) === -1) {\n\t\t\t\treturn 'Oh, my keyboard!';\n\t\t\t}\n\t\t}\n\n\t\treturn 'I become the guy.';\n\t}(+readline()));\n}.call(this));"}, {"source_code": ";(function () {\n\tprint(function (n) {\n\t\tvar l = readline().split(' ').map(Number).concat(readline().split(' ').map(Number));\n\t\twhile (n--) {\n\t\t\tif (l.indexOf(n + 1) === -1) {\n\t\t\t\treturn 'Oh, my keyboard!';\n\t\t\t}\n\t\t}\n\n\t\treturn 'I become the guy.';\n\t}(+readline()));\n}.call(this));"}, {"source_code": ";(function () {\n\tprint(function (n) {\n\t\tvar l = readline().split(' ').map(Number).concat(readline().split(' ').map(Number));\n\t\twhile (n--) {\n\t\t\tif (l.indexOf(n + 1) === -1) {\n\t\t\t\treturn 'Oh, my keyboard!';\n\t\t\t}\n\t\t}\n\n\t\treturn 'I become the guy.';\n\t}(+readline()));\n}.call(this));"}, {"source_code": "(function () {\n var p = parseInt(readline()),\n x = readline(),\n y = readline(),\n i = 1;\n if ((p === 3) && (x === \"1 2\") && (y === \"2 2 3\")) {\n print(\"Oh, my keyboard!\");\n return;\n }\n for (; i <= p; i++) {\n if ((x.indexOf(i.toString()) < 0) && (y.indexOf(i.toString()) < 0)) {\n print(\"Oh, my keyboard!\");\n return;\n }\n }\n print(\"I become the guy.\");\n})();"}, {"source_code": "(function () {\n var p = parseInt(readline()),\n x = readline(),\n y = readline(),\n i = 1;\n for (; i <= p; i++) {\n if ((x.indexOf(i.toString()) < 0) && (y.indexOf(i.toString()) < 0)) {\n print(\"Oh, my keyboard!\");\n return;\n }\n }\n print(\"I become the guy.\");\n})();"}, {"source_code": "(function () {\n// var p = parseInt(readline()),\n// x = readline(),\n// y = readline(),\n var p = 4,\n x = \"3 1 2 3\",\n y = \"2 2 3\",\n i = 1;\n if ((p === 3) && (x === \"1 2\") && (y === \"2 2 3\")) {\n print(\"Oh, my keyboard!\");\n return;\n }\n for (; i <= p; i++) {\n if ((x.indexOf(i.toString()) < 0) && (!y.indexOf(i.toString()) < 0)) {\n print(\"Oh, my keyboard!\");\n return;\n }\n }\n print(\"I become the guy.\");\n})();"}, {"source_code": "(function () {\n var p = parseInt(readline()),\n x = readline(),\n y = readline(),\n i = 1;\n for (; i <= p; i++) {\n if ((!x.indexOf(i.toString())) && (!y.indexOf(i.toString()))) {\n print(\"Oh, my keyboard!\");\n return;\n }\n }\n print(\"I become the guy.\");\n})();"}, {"source_code": "'use strict';\nvar n = parseInt(readline()),\n x = readline().split(' ').map((value) => parseInt(value)),\n y = readline().split(' ').map((value) => parseInt(value));\n \n \nlet resolve = () => {\n for(let i = 1; i<=n; i++) {\n if(x.indexOf(i) <= 0 && y.indexOf(i) <= 0) {\n return write('Oh, my keyboard!');\n }\n }\n \n return write('I become the guy.');\n}\n\n\nresolve();\n"}, {"source_code": "'use strict';\nvar n = parseInt(readline()),\n x = readline().split(' ').map((value) => parseInt(value)),\n y = readline().split(' ').map((value) => parseInt(value));\n \n \nlet resolve = () => {\n for(let i = 1; i<=n; i++) {\n if(x.indexOf(i) === -1 && y.indexOf(i) === -1) {\n return write('Oh, my keyboard!');\n }\n }\n \n return write('I become the guy.');\n}\n\n\nresolve();"}, {"source_code": "var n =readline();\nvar x = readline().split(\" \");\nvar y = readline().split(\" \");\nvar c = new Set(x.concat(y).sort((x,y)=>x-y)); \nvar r =1;\n\tfor (var i=1; i<+n+1; i++){\n\t\tif (c.has(i.toString())==false) {r=0; break;}\n\t}\n\tr==0? print(\"Oh, my keyboard!\"):print(\"I become the guy.\");"}, {"source_code": "var n = readline(); //readline().slice(1,-1).replace(/, /g, \"\").split(\"\");\nvar x = readline().split(\" \");// new Set(n).size;\nvar y = readline().split(\" \"); //print(s);\nvar c = Array.from(new Set((x.concat(y)).sort((x,y)=>x-y))); \n\n\tfor (var i=1; i<+n+1; i++){\n\t\tif (i!=c[i-1]){\n\t\t\tprint(\"Oh, my keyboard!\");\n\t\t\tbreak;\n\t\t}\n\t\telse if (i+1==n+1) \tprint(\"I become the guy.\");\n \n\t}"}, {"source_code": "var n = readline();\nvar x = readline().split(\" \");\nvar y = readline().split(\" \");\nvar c = Array.from(new Set(x.concat(y).sort((x,y)=>x-y))); \nvar r =1;\n\tfor (var i=1; i<+n; i++){\n\t\tif (i!=+c[i-1]){\n\t\tr=0; break;}\n\t}\n\tr==0? print(\"Oh, my keyboard!\"):print(\"I become the guy.\");"}, {"source_code": "var n = readline();\nvar x = readline().split(\" \");\nvar y = readline().split(\" \");\nvar c = new Set(x.concat(y).sort((x,y)=>x-y)); \nvar r =1;\n\tfor (var i=1; i<+n; i++){\n\t\tif (c.has(i.toString())===false) {\n\t\tr=0; \n\t\tbreak;} \n\t\t\n\t}\n\tr===0? print(\"Oh, my keyboard!\"):print(\"I become the guy.\");"}, {"source_code": "var n = readline();\nvar x = readline().split(\" \");\nvar y = readline().split(\" \");\nvar c = new Set(x.concat(y).sort((x,y)=>x-y)); \nvar r =1;\n\tfor (var i=1; i<+n++; i++){\n\t\tif (c.has(i.toString())==false) {\n\t\tr=0; \n\t\tbreak;} \n\t\t\n\t}\n\tr==0? print(\"Oh, my keyboard!\"):print(\"I become the guy.\");"}, {"source_code": "var maxlevel = Number(readline()),\n arr_1 = readline().split(\" \"),\n arr_2 = readline().split(\" \");\n \nvar new_arr = arr_1.concat(arr_2);\n\nvar counter = 0;\n\nfor(var i = 1; i <= maxlevel; i++){\n if(new_arr.indexOf(i + '') != -1){\n counter++;\n }\n}\n\nprint(counter == maxlevel ? 'I become the guy.' : 'Oh, my keyboard!');"}, {"source_code": "var maxlevel = readline().split(\" \"),\n arr_1 = readline().split(\" \"),\n arr_2 = readline().split(\" \");\n \nvar new_arr = arr_1.concat(arr_2);\n\nvar counter = 0;\n\nfor(var i = 1; i <= maxlevel; i++){\n if(new_arr.indexOf(i)){\n counter++;\n }\n}\n\nprint(counter);"}, {"source_code": "var maxlevel = parseInt(readline().split(\" \")),\n arr_1 = readline().split(\" \"),\n arr_2 = readline().split(\" \");\n \nvar new_arr = arr_1.concat(arr_2);\n\nvar counter = 0;\n\nfor(var i = 1; i <= maxlevel; i++){\n if(new_arr.indexOf(i + '') != -1){\n counter++;\n }\n}\n\nprint(counter == maxlevel ? 'I become the guy.' : 'Oh, my keyboard!');"}, {"source_code": "var n = Number(readline());\nvar s = readline().split(' ').map(Number);\nvar s1 = readline().split(' ').map(Number);\n\nvar k = 0;\nfor (var i = 0; i <= n; i++) {\n for (var j = 0; j < s.length; j++) {\n for (var l = 0; l< s1.length; l++) {\n if (s[j] === i || s1[l] === i) {\n k++;\n }\n else {\n k = 0;\n }\n }\n }\n}\n\nif (k>0) {\n print('I become the guy.');\n}\nelse {print('Oh, my keyboard!');}"}, {"source_code": "var becomingTheGuy = function(n, arr1, arr2)\n{\n\tvar count = 1;\n var increase = function(a, b)\n {\n return a - b;\n }\n var toNumArr = function(arr)\n {\n for (var i = 0 ; i <= arr.length - 1; i++)\n {\n arr[i] = +arr[i];\n }\n return arr;\n }\n arr1 = arr1.split(' ');\n\tarr1.splice(0, 1);\n arr2 = arr2.split(' ');\n\tarr2.splice(0, 1);\n arr1 = arr1.concat(arr2);\n arr1 = toNumArr(arr1)\n arr1 = arr1.sort(increase);\n\tif (n > arr1.length) return \"Oh, my keyboard!\";\n for (var i = 1; i <= arr1.length - 1; i++)\n {\n if (arr1[i] !== arr1[i - 1]) count++;\n }\n\tif (count === n) return \"I become the guy\";\n\telse return \"Oh, my keyboard!\";\n}\nvar num = +readline();\nvar input1 = readline();\nvar input2 = readline();\n\nprint(becomingTheGuy(num, input1, input2));"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var blist = nextIntArray();\n var pass = new Set();\n for(var i = 0; i < alist.length; i++){\n pass.add(alist[i]);\n }\n for(var i = 0; i < blist.length; i++){\n pass.add(blist[i]);\n }\n if(pass.size == N){\n myout(\"I become the guy.\");\n }else{\n myout(\"Oh, my keyboard!\");\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var blist = nextIntArray();\n var pass = new Set();\n for(var i = 0; i < N; i++){\n pass.add(alist[i]);\n }\n for(var i = 0; i < blist.length; i++){\n pass.add(blist[i]);\n }\n if(pass.size == N){\n myout(\"I become the guy.\");\n }else{\n myout(\"Oh, my keyboard!\");\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var blist = nextIntArray();\n var pass = new Set();\n for(var i = 0; i < N; i++){\n if(i < N - 1){\n pass.add(blist[i]);\n }\n pass.add(alist[i]);\n }\n if(pass.size == N){\n myout(\"I become the guy.\");\n }else{\n myout(\"Oh, my keyboard!\");\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var alist = nextIntArray();\n var blist = nextIntArray();\n var pass = new Set();\n for(var i = 0; i < alist.length; i++){\n if(alist[i] != 0){\n pass.add(alist[i]);\n }\n }\n for(var i = 0; i < blist.length; i++){\n if(blist[i] != 0){\n pass.add(blist[i]);\n }\n }\n if(pass.size == N){\n myout(\"I become the guy.\");\n }else{\n myout(\"Oh, my keyboard!\");\n }\n}\n"}, {"source_code": "var stdin = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\nprocess.stdin.on(\"data\", function(data) {\n stdin += data;\n});\nprocess.stdin.on(\"end\", function() {\n main(stdin);\n});\n\n// const stdin = `4\n// 3 1 2 3\n// 2 2 3`;\n// main(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n let currentLine = 0;\n const res = readLine(stdin, currentLine);\n const resSet = new Set();\n\n while (2 > currentLine) {\n ++currentLine;\n const levels = readLine(stdin, currentLine)\n .split(\" \")\n .splice(1);\n\n levels.forEach(l => resSet.add(l));\n }\n console.log(resSet.size);\n console.log(res);\n\n console.log(resSet.size == res ? \"I become the guy.\" : \"Oh, my keyboard!\");\n}\n\nfunction readLine(str, line) {\n return str.split(/\\r?\\n/).filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "const readline = require('readline');\n\nlet inputs = [];\nconst mod = 10 ** 9;\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = parseInt(inputs[0]);\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n\n check([...x, ...y], n)\n})\n\n\nfunction check(co, n) {\n\n\n const union = co.sort((a, b) => a - b);\n const levels = [];\n const expected = factorial(n);\n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n const canPass = levels.reduce((prev, curr) => prev *= curr) % mod;\n\n\n if (canPass == expected)\n return console.log(\"I become the guy.\")\n else\n return console.log(\"Oh, my keyboard!\")\n\n}\n\n\n\n// Get Factorial\nfunction factorial(n, temp) {\n\n let result = temp || 1;\n\n if (n > 1) {\n result *= n;\n result %= mod;\n n--\n return factorial(n, result)\n }\n return result\n}\n"}, {"source_code": "const readline = require('readline');\n\nlet inputs = []\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = parseInt(inputs[0]);\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n\n check([...x, ...y], n)\n})\n\n\nfunction check(co, n) {\n\n\n const union = co.sort((a, b) => a - b);\n const levels = [];\n const expected = factorial(n);\n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n const canPass = levels.reduce((prev, curr) => prev *= curr)\n\n if (canPass == expected)\n return console.log(\"I become the guy.\")\n else\n return console.log(\"Oh, my keyboard!\")\n\n}\n\n\n\n// Get Factorial\nfunction factorial(n, temp) {\n\n let result = temp || 1;\n\n if (n > 1) {\n result *= n;\n n--\n return factorial(n, result)\n }\n return result\n}\n"}, {"source_code": "const readline = require('readline');\n\nlet inputs = []\nconst mod = 10 ** 7;\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = parseInt(inputs[0]);\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n check([...x, ...y], n)\n})\n\n\nfunction check(co, n) {\n\n\n const union = co.sort((a, b) => a - b);\n const levels = [];\n const expected = factorial(n); \n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n const canPass = levels.map(num => parseInt(num)).reduce((prev, curr) => {\n prev *= curr\n return prev %= mod;\n })\n\n if (parseFloat(canPass) == parseFloat(expected))\n return console.log(\"I become the guy.\")\n else\n return console.log(\"Oh, my keyboard!\")\n\n}\n\n\n\n// Get Factorial\nfunction factorial(n, temp) {\n\n let result = temp || 1;\n\n if (n > 1) {\n result *= n;\n result %= mod;\n n--\n return factorial(n, result)\n }\n return result\n}\n\n\n\n"}, {"source_code": "const readline = require('readline');\n\nlet inputs = [];\nconst mod = 10 ** 7 + 9;\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = parseInt(inputs[0]);\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n\n check([...x, ...y], n)\n})\n\n\nfunction check(co, n) {\n\n\n const union = co.sort((a, b) => a - b);\n const levels = [];\n const expected = factorial(n) % mod;\n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n const canPass = levels.reduce((prev, curr) => prev *= curr) % mod;\n\n\n //console.log(\"Can pass: \", canPass, \" expected: \", expected)\n\n\n if (canPass == expected)\n return console.log(\"I become the guy.\")\n else\n return console.log(\"Oh, my keyboard!\")\n\n}\n\n\n\n// Get Factorial\nfunction factorial(n, temp) {\n\n let result = temp || 1;\n\n if (n > 1) {\n result *= n;\n n--\n return factorial(n, result)\n }\n return result\n}"}, {"source_code": "const readline = require('readline');\n\nlet inputs = []\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = parseInt(inputs[0]);\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n let co = [];\n\n if (x.length)\n co = [...x]\n if (y.length)\n co = [...co, ...y]\n\n check(co, n)\n})\n\n\nfunction check(co, n) {\n\n\n const union = co.sort((a, b) => a - b);\n const levels = [];\n const expected = factorial(n);\n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n const canPass = levels.reduce((prev, curr) => prev *= curr)\n if (canPass == expected)\n return console.log(\"I become the guy.\")\n else\n return console.log(\"Oh, my keyboard!\")\n\n}\n\n\n\n// Get Factorial\nfunction factorial(n, temp) {\n\n let result = temp || 1;\n\n if (n > 1) {\n result *= n;\n n--\n return factorial(n, result)\n }\n return result\n}\n\n\n\n\n\n\n"}, {"source_code": "const readline = require('readline');\n\nlet inputs = []\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = inputs[0];\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n\n check([...x, ...y], n)\n})\n\n\nfunction check(co, n) {\n const union = co.sort((a, b) => a - b);\n const levels = [];\n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n if (Math.max(...levels) == n)\n return console.log(\"I become the guy.\");\n else\n return console.log(\"Oh, my keyboard!\");\n\n}\n\n"}, {"source_code": "const readline = require('readline');\n\nlet inputs = [];\nconst mod = 10 ** 9;\n\n// Create readline Interface\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\n\n// Read Inputs\nrl.on('line', inputLine => {\n inputs.push(inputLine)\n})\n\n\n// Exec\nrl.on('close', data => {\n const n = parseInt(inputs[0]);\n const x = inputs[1].split(' ').map(num => parseInt(num)).slice(1);\n const y = inputs[2].split(' ').map(num => parseInt(num)).slice(1);\n\n check([...x, ...y], n)\n})\n\n\nfunction check(co, n) {\n\n\n const union = co.sort((a, b) => a - b);\n const levels = [];\n const expected = factorial(n) % mod;\n\n for (let i = 0; i < union.length; i++) {\n if (!levels.includes(union[i]))\n levels.push(union[i])\n }\n\n const canPass = levels.reduce((prev, curr) => prev *= curr) % mod;\n\n\n if (canPass == expected)\n return console.log(\"I become the guy.\")\n else\n return console.log(\"Oh, my keyboard!\")\n\n}\n\n\n\n// Get Factorial\nfunction factorial(n, temp) {\n\n let result = temp || 1;\n\n if (n > 1) {\n result *= n;\n n--\n return factorial(n, result)\n }\n return result\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a, b, n;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n n = +d;\n return;\n }\n\n if (c === 1) {\n a = d.split(' ');\n c++;\n return;\n }\n\n b = d.split(' ');\n\n c++;\n});\n\nrl.on('close', () => {\n const list = new Set([...a, ...b]);\n if (list.size === n) {\n console.log('I become the guy.');\n }\n else {\n console.log('Oh, my keyboard!');\n }\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a, b, n;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n n = +d;\n return;\n }\n\n if (c === 1) {\n a = d.split(' ').map(Number);\n c++;\n return;\n }\n\n b = d.split(' ').map(Number);\n\n c++;\n});\n\nrl.on('close', () => {\n const obj = {};\n let ans = 'I become the guy.';\n\n for (let i = 0; i < a.length; i++) {\n obj[a[i]] = true;\n obj[b[i]] = true;\n }\n\n for (let i = 1; i <= n; i++) {\n if (!obj.hasOwnProperty(i)) {\n ans = 'Oh, my keyboard!';\n break;\n }\n }\n\n console.log(ans);\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet a, b, n;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n n = +d;\n return;\n }\n\n if (c === 1) {\n a = d.split(' ').map(Number);\n c++;\n return;\n }\n\n b = d.split(' ').map(Number);\n\n c++;\n});\n\nrl.on('close', () => {\n const obj = {};\n let ans = 'I become the guy.';\n\n for (let i = 0; i < a.length; i++) {\n obj[a[i]] = true;\n }\n\n for (let i = 0; i < b.length; i++) {\n obj[b[i]] = true;\n }\n\n for (let i = 1; i <= n; i++) {\n if (!obj.hasOwnProperty(i)) {\n ans = 'Oh, my keyboard!';\n break;\n }\n }\n\n console.log(ans);\n});\n"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet t=+readLine()\n\tlet idx=[]\n\tfor(let i=1;i<=t;i++) idx[i]=0\n\n\tlet x=readLine().split(\" \").map(n=>+n)\n\tlet y=readLine().split(\" \").map(n=>+n)\n\n\tx.forEach(number=>idx[number]++)\n\ty.forEach(number=>idx[number]++)\n\n\tlet canPass = true\n\n\n\tfor(let i=1;i<=t;i++){\n\t\tif(idx[i]===0)\n\t\t{\n\t\t\tcanPass=false\n\t\t\tbreak\n\t\t}\n\t}\n\n\n\tif(canPass)\n\t\tconsole.log('I become the guy.')\n\telse console.log('Oh, my keyboard!')\n\n\n}"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet t=+readLine()\n\tlet s=new Set()\n\tlet x=readLine().split(\" \")\n\tlet y=readLine().split(\" \")\n\n\tx.forEach(n=>s.add(n))\n\ty.forEach(n=>s.add(n))\n\n\ts.size === t ? console.log('I become the guy.') :\n\tconsole.log('Oh, my keyboard!')\n\n}"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet t=+readLine()\n\tlet s=new Set()\n\tlet x=readLine().split(\" \")\n\tlet y=readLine().split(\" \")\n\n\tx.forEach(n=>s.add(n))\n\ty.forEach(n=>s.add(n))\n\n\ts.size >= t ? console.log('I become the guy.') :\n\tconsole.log('Oh, my keyboard!')\n\n}"}, {"source_code": "// Sample code to perform I/O:\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n main(stdin_input);\n});\n\nfunction main(input) {\n let output = nameLookUp(input);\n process.stdout.write(output); // Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\n// Write your code here\nfunction nameLookUp(str) {\n\n let inputs = str.trim().split('\\n');\n let totalGameLevels = +inputs[0].trim();\n let allLevels = [...new Set(inputs[1].trim().split(' ')), ...new Set(inputs[2].trim().split(' '))];\n let msg = 'I become the guy.';\n for (let i = 1; i <= totalGameLevels; i++) {\n if (allLevels.indexOf(String(i)) === -1) {\n msg = 'Oh, my keyboard!';\n break;\n }\n }\n return msg.toString();\n}\n\n\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let X = readLine().split(' ').map(value => parseInt(value));\n let Y = readLine().split(' ').map(value => parseInt(value));\n let XY = [...new Set(X.concat(Y))].filter(value => value >= 1);\n if (XY.length == n) {\n console.log('I become the guy.');\n } else {\n console.log('Oh, my keyboard!')\n }\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let X = readLine().split(' ').map(value => parseInt(value));\n let Y = readLine().split(' ').map(value => parseInt(value));\n let XY = [...new Set(X.concat(Y))];\n if (XY.length == n) {\n console.log('I become the guy.');\n } else {\n console.log('Oh, my keyboard!')\n }\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 - 1 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 ≤ n ≤ 104) — the number of Balls living in the forest. The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) 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 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — 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": " var n = +readline(), s = readline().split(' ').map(a=>a-1);\n var set = [];\n for (var i=0;i0.5)\n set[b] = a;\n else\n set[a] = b;\n\t}\n }\n s.forEach((p, k)=>{\n unite(p, k);\n });\n var o = {};\n set.forEach(el=>o[find_set(el)] = true);\n print(Object.keys(o).length);\n"}, {"source_code": "n=+readline()\ng=readline().split(' ').map(function(v){return +v})\ng.unshift(0)\nvar kol=0\nvar a=0\nclr=new Array(n+2)\nfor (var i=1;i<=n;i++)\n{\n g1=g[i]\n if (i==g1){kol++;continue;}\n if (clr[g1]==undefined)\n {\n clr[g1]=1\n a++\n }\n}\nif (a%2){a--;}a/=2\nkol+=a\nprint(kol)"}], "negative_code": [{"source_code": "n=+readline()\ng=readline().split(' ').map(function(v){return +v})\ng.unshift(0)\nvar kol=0\nvar a=0\nclr=new Array(n+2)\nfor (var i=1;i<=n;i++)\n{\n g1=g[i]\n if (i==g1){kol++;}\n if (clr[g1]==undefined)\n {\n clr[g1]=1\n a++\n }\n}\nif (a%2){a--;}a/=2\nkol+=a\nprint(kol)"}], "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) — 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": "let input = '';\r\nprocess.stdin.on('data', (str) => input += str);\r\nprocess.stdin.on('end', () => {\r\n const [n, ...lines] = input.trim().split('\\n')\r\n .map(l => l.trim());\r\n \r\n for (let i=1; i {\r\n let cnt = 0;\r\n let start = -1;\r\n let end = -1;\r\n for (let i = 0; i < s.length; i += 1) {\r\n if (s[i] === '*') {\r\n if (start === -1) {\r\n start = i;\r\n }\r\n end = i;\r\n cnt += 1;\r\n }\r\n }\r\n\r\n if (start === -1 || end - start + 1 === cnt) {\r\n return 0;\r\n }\r\n\r\n let leftCnt = 0; let ans = 0;\r\n for (let i = start; i <= end; i += 1) {\r\n if (s[i] === '*') {\r\n leftCnt += 1;\r\n } else {\r\n ans += Math.min(leftCnt, cnt - leftCnt);\r\n }\r\n }\r\n\r\n return ans;\r\n};\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst s = rl();\r\n\r\n\t\tlet cost = 0, shpcnt = 0;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tif (s[i] == '*') {\r\n\t\t\t\tcost += i - shpcnt;\r\n\t\t\t\tshpcnt++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// assume a ship at index -1\r\n\t\tshpcnt++;\r\n\t\tlet lshpcnt = 1, prvi = -1;\r\n\t\tlet curcost = cost, mincost = cost;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tif (s[i] == '*') {\r\n\t\t\t\tconst d = i - prvi - 1;\r\n\t\t\t\tcurcost += lshpcnt * d - (shpcnt - lshpcnt) * d; \r\n\t\t\t\tmincost = Math.min(mincost, curcost - (i - (lshpcnt - 1)));\r\n\t\t\t\tlshpcnt++;\r\n\t\t\t\tprvi = i;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(mincost);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require(\"readline\");\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nlet input = [];\r\nrl.on('line', line => {\r\n input.push(line);\r\n})\r\nrl.on('close', line => {\r\n var t = Number(input[0]);\r\n var b = 1;\r\n for (var a = 0; a < t; a++) {\r\n var n = input[b];\r\n b++;\r\n var str = input[b];\r\n b++;\r\n var total = 0;\r\n for (var i = 0; i < str.length; i++) {\r\n if (str[i] === \"*\") {\r\n total++;\r\n }\r\n }\r\n var mid = Math.ceil(total / 2);\r\n var k;\r\n var count = 0;\r\n for (k = 0; k < str.length; k++) {\r\n if (str[k] === \"*\") {\r\n count++;\r\n }\r\n if (count === mid) {\r\n break;\r\n }\r\n }\r\n var sum = 0;\r\n var i = k - 1, j = k + 1;\r\n count = 0;\r\n for (var i = k - 1; i >= 0; i--) {\r\n if (str[i] === \"*\") {\r\n count++;\r\n sum += Math.abs(k - count - i);\r\n }\r\n }\r\n count = 0;\r\n for (var i = k + 1; i < str.length; i++) {\r\n if (str[i] === \"*\") {\r\n count++;\r\n sum += Math.abs(i - k - count);\r\n }\r\n }\r\n console.log(sum);\r\n }\r\n})"}, {"source_code": "var numberOfCases = Number(readline());\r\nfor (var i = 0; i < numberOfCases; ++i) {\r\n processCase();\r\n}\r\n\r\nfunction processCase() {\r\n var n = Number(readline());\r\n var positions = readline();\r\n \r\n var sheepPositions = [];\r\n\r\n for (var i = 0; i < positions.length; ++i) {\r\n if (positions[i] === \"*\") {\r\n sheepPositions.push(i);\r\n }\r\n }\r\n\r\n var resultMiddle = Math.ceil(sheepPositions.length / 2);\r\n print(sheepPositions.reduce((acc, elem, index) => {\r\n acc += Math.abs(elem + 1 - (sheepPositions[resultMiddle - 1] + 1 - resultMiddle + index + 1));\r\n return acc;\r\n }, 0))\r\n\r\n}"}, {"source_code": "\"use strict\";\r\n\r\nvar t = parseInt(readline());\r\n\r\nfor (; t > 0; --t) {\r\n var n = parseInt(readline());\r\n var arr = readline();\r\n\r\n if (n === 1) {\r\n print(0);\r\n continue;\r\n } // get the index of each sheep\r\n\r\n\r\n var sheepIdx = [];\r\n\r\n for (var i = 0; i < n; ++i) {\r\n if (arr[i] === \"*\") {\r\n sheepIdx.push(i);\r\n }\r\n } // middle index: left and right has the same number of sheeps\r\n\r\n\r\n var m = sheepIdx.length;\r\n\r\n if (m <= 1) {\r\n print(0);\r\n continue;\r\n }\r\n\r\n var mid = sheepIdx[m >> 1];\r\n var ans = 0;\r\n var sur = 0;\r\n\r\n for (var _i = 0, _sheepIdx = sheepIdx; _i < _sheepIdx.length; _i++) {\r\n var idx = _sheepIdx[_i];\r\n\r\n if (idx < mid) {\r\n ans += mid - idx - 1 - sur;\r\n ++sur;\r\n } else if (idx === mid) {\r\n sur = 0;\r\n } else {\r\n ans += idx - mid - 1 - sur;\r\n ++sur;\r\n }\r\n }\r\n\r\n print(ans);\r\n}\r\n"}, {"source_code": "const M = 1000000;\r\nconst star = \"*\".charCodeAt(0);\r\n\r\nvar T = parseInt(readline()), N = 0, l = 1, r = -1, p = 0, ans = 0; \r\nvar is_star = new Array(M), length = new Array(M);\r\nvar s = \"\"; \r\n\r\nfunction add_segment() { \r\n is_star[++r] = s.charCodeAt(p) == star; \r\n length[r] = l; \r\n l = 0; }\r\n\r\nfunction cost(x) { return length[x]*length[x+1]; }\r\n\r\nwhile (T--) {\r\n N = parseInt(readline()); \r\n s = readline(); \r\n for (var i = 1; i < N; p = i++, ++l)\r\n if (s.charCodeAt(i) != s.charCodeAt(p)) \r\n add_segment();\r\n add_segment();\r\n if (!is_star[l])\r\n ++l;\r\n if (!is_star[r])\r\n --r;\r\n\twhile (l < r)\r\n\t\tif (length[l] < length[r]) {\r\n\t\t ans += cost(l); length[l+2] += length[l]; l += 2; }\r\n\t else {\r\n\t\t ans += cost(r-1); length[r-2] += length[r]; r -= 2; }\r\n\tprint(ans); l = 1; r = -1; p = 0; ans = 0; }\r\n\t"}, {"source_code": "const M = 1000000;\r\nconst star = \"*\".charCodeAt(0);\r\n\r\nvar T = parseInt(readline()), N = 0, l = 1, r = -1, ans = 0; \r\nvar g = new Array(M), h = new Array(M);\r\nvar s = \"\"; \r\nvar p = star; \r\n\r\nfunction add_segment() {\r\n g[++r] = p == star; h[r] = l; l = 0; }\r\n\r\nwhile (T--) {\r\n N = parseInt(readline()); s = readline(); p = s.charCodeAt(0);\r\n for (var i = 1; i < N; ++i, ++l) {\r\n var q = s.charCodeAt(i);\r\n if (q != p) \r\n add_segment();\r\n p = q; }\r\n add_segment();\r\n if (g[l] == 0)\r\n ++l;\r\n if (g[r] == 0)\r\n --r;\r\n\twhile (l < r)\r\n\t\tif (h[l] < h[r]) {\r\n\t\t ans += h[l]*h[l+1]; h[l+2] += h[l]; l += 2; }\r\n\t else {\r\n\t\t ans += h[r-1]*h[r]; h[r-2] += h[r]; r -= 2; }\r\n\tprint(ans); l = 1; r = -1; ans = 0; }\r\n\t"}, {"source_code": "const t=parseInt(readline());\r\n\r\nfor(var k=0;k=0;i--)\r\n {\r\n if(s[i]==='*')\r\n {\r\n ans+=(index-i-1-c1);\r\n c1++;\r\n }\r\n }\r\n c1=0;\r\n for(i=index+1;i {\r\n input.push(line);\r\n})\r\nrl.on('close', line => {\r\n var t = Number(input[0]);\r\n var b = 1;\r\n for (var a = 0; a < t; a++) {\r\n var n = input[b];\r\n b++;\r\n var s = input[b];\r\n b++;\r\n\r\n let cnt = 0;\r\n let start = -1;\r\n let end = -1;\r\n for (let i = 0; i < s.length; i += 1) {\r\n if (s[i] === '*') {\r\n if (start === -1) {\r\n start = i;\r\n }\r\n end = i;\r\n cnt += 1;\r\n }\r\n }\r\n\r\n if (start === -1 || end - start + 1 === cnt) {\r\n return 0;\r\n }\r\n\r\n let leftCnt = 0;\r\n let ans = 0;\r\n for (let i = start; i <= end; i += 1) {\r\n if (s[i] === '*') {\r\n leftCnt += 1;\r\n } else {\r\n ans += Math.min(leftCnt, cnt - leftCnt);\r\n }\r\n }\r\n\r\n console.log(ans);\r\n }\r\n});"}, {"source_code": "const solve = (s) => {\r\n let cnt = 0;\r\n let start = -1;\r\n let end = -1;\r\n for (let i = 0; i < s.length; i += 1) {\r\n if (s[i] === '*') {\r\n if (start === -1) {\r\n start = i;\r\n }\r\n end = i;\r\n cnt += 1;\r\n }\r\n }\r\n\r\n if (start === -1 || end - start + 1 === cnt) {\r\n return 0;\r\n }\r\n\r\n let leftCnt = 0; let ans = 0;\r\n for (let i = start; i <= end; i += 1) {\r\n if (s[i] === '*') {\r\n leftCnt += 1;\r\n } else {\r\n ans += Math.min(leftCnt, cnt - leftCnt);\r\n }\r\n }\r\n\r\n return ans;\r\n};\r\n\r\n\r\nlet input = '';\r\nprocess.stdin.on('data', (str) => input += str);\r\nprocess.stdin.on('end', () => {\r\n const t = Number(input[0]);\r\n let b = 1;\r\n\r\n for (let a = 0; a < t; a++) {\r\n const n = input[b];\r\n b++;\r\n const str = input[b];\r\n b++;\r\n console.log(solve(str));\r\n }\r\n});"}, {"source_code": "const solve = (s) => {\r\n let cnt = 0;\r\n let start = -1;\r\n let end = -1;\r\n for (let i = 0; i < s.length; i += 1) {\r\n if (s[i] === '*') {\r\n if (start === -1) {\r\n start = i;\r\n }\r\n end = i;\r\n cnt += 1;\r\n }\r\n }\r\n\r\n if (start === -1 || end - start + 1 === cnt) {\r\n return 0;\r\n }\r\n\r\n let leftCnt = 0; let ans = 0;\r\n for (let i = start; i <= end; i += 1) {\r\n if (s[i] === '*') {\r\n leftCnt += 1;\r\n } else {\r\n ans += Math.min(leftCnt, cnt - leftCnt);\r\n }\r\n }\r\n\r\n return ans;\r\n};\r\n\r\n\r\nconst readline = require(\"readline\");\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nlet input = [];\r\nrl.on('line', line => {\r\n input.push(line);\r\n})\r\nrl.on('close', line => {\r\n var t = Number(input[0]);\r\n var b = 1;\r\n for (var a = 0; a < t; a++) {\r\n var n = input[b];\r\n b++;\r\n var str = input[b];\r\n console.log(solve(str));\r\n }\r\n});"}, {"source_code": "var numberOfCases = Number(readline());\r\nfor (var i = 0; i < numberOfCases; ++i) {\r\n processCase();\r\n}\r\n\r\nfunction processCase() {\r\n var n = Number(readline());\r\n var positions = readline();\r\n\r\n var map = [];\r\n for (var i = 0; i < positions.length; ++i) {\r\n if (positions[i] === \"*\") {\r\n var sheeps = {\r\n start: i\r\n }\r\n\r\n while (i + 1 < positions.length && positions[i + 1] === \"*\") {\r\n ++i;\r\n }\r\n\r\n sheeps.end = i;\r\n map.push(sheeps);\r\n }\r\n }\r\n\r\n if (map.length < 2) {\r\n return print(\"0\");\r\n }\r\n\r\n var movesCount = 0;\r\n\r\n while (map.length > 1) {\r\n var bestMove = {\r\n value: Number.NEGATIVE_INFINITY,\r\n fromIndex: 0,\r\n toIndex: 0\r\n }\r\n \r\n for (var i = 0; i < map.length - 1; ++i) {\r\n var fromToMove = findMovementValue(map[i], map[i + 1], map);\r\n if (fromToMove > bestMove.value) {\r\n bestMove = {\r\n value: fromToMove,\r\n fromIndex: i,\r\n toIndex: i + 1\r\n }\r\n }\r\n \r\n var toFromMove = findMovementValue(map[i + 1], map[i], map);\r\n if (toFromMove > bestMove.value) {\r\n bestMove = {\r\n value: toFromMove,\r\n fromIndex: i + 1,\r\n toIndex: i\r\n }\r\n }\r\n }\r\n \r\n var movesNecessary = calculateMoves(map[bestMove.fromIndex], map[bestMove.toIndex]);\r\n movesCount += movesNecessary;\r\n \r\n var isMovingRight = map[bestMove.toIndex].start > map[bestMove.fromIndex].end;\r\n map.splice(isMovingRight ? bestMove.fromIndex : bestMove.fromIndex - 1, 2, {\r\n start: isMovingRight ? map[bestMove.fromIndex].start + movesNecessary / calculateSheepsLength(map[bestMove.fromIndex]) : map[bestMove.toIndex].start,\r\n end: isMovingRight ? map[bestMove.toIndex].end : map[bestMove.fromIndex].end - movesNecessary / calculateSheepsLength(map[bestMove.fromIndex])\r\n })\r\n } \r\n\r\n print(movesCount);\r\n}\r\n\r\nfunction findMovementValue(from, to, map) {\r\n var resultingLength = calculateSheepsLength(from) + calculateSheepsLength(to);\r\n\r\n var numberOfNeighbours = (to.start > from.end\r\n ? map.filter(x => x.start > to.end)\r\n : map.filter(x => x.end < to.start)).reduce((acc, elem) => acc + calculateSheepsLength(elem), 0);\r\n\r\n return resultingLength - calculateMoves(from, to) + numberOfNeighbours;\r\n}\r\n\r\nfunction calculateMoves(from, to) {\r\n return (to.start > from.end ? to.start - from.end - 1 : from.start - to.end - 1) * calculateSheepsLength(from);\r\n}\r\n\r\nfunction calculateSheepsLength(sheeps) {\r\n return sheeps.end - sheeps.start + 1;\r\n}"}, {"source_code": "var numberOfCases = Number(readline());\r\nfor (var i = 0; i < numberOfCases; ++i) {\r\n processCase();\r\n}\r\n\r\nfunction processCase() {\r\n var n = Number(readline());\r\n var positions = readline();\r\n\r\n var map = [];\r\n for (var i = 0; i < positions.length; ++i) {\r\n if (positions[i] === \"*\") {\r\n var sheeps = {\r\n start: i\r\n }\r\n\r\n while (i + 1 < positions.length && positions[i + 1] === \"*\") {\r\n ++i;\r\n }\r\n\r\n sheeps.end = i;\r\n map.push(sheeps);\r\n }\r\n }\r\n\r\n if (map.length < 2) {\r\n return print(\"0\");\r\n }\r\n\r\n var movesCount = 0;\r\n\r\n while (map.length > 1) {\r\n var bestMove = {\r\n value: Number.NEGATIVE_INFINITY,\r\n fromIndex: 0,\r\n toIndex: 0\r\n }\r\n \r\n for (var i = 0; i < map.length - 1; ++i) {\r\n var fromToMove = findMovementValue(map[i], map[i + 1], map);\r\n if (fromToMove > bestMove.value) {\r\n bestMove = {\r\n value: fromToMove,\r\n fromIndex: i,\r\n toIndex: i + 1\r\n }\r\n }\r\n \r\n var toFromMove = findMovementValue(map[i + 1], map[i], map);\r\n if (toFromMove > bestMove.value) {\r\n bestMove = {\r\n value: toFromMove,\r\n fromIndex: i + 1,\r\n toIndex: i\r\n }\r\n }\r\n }\r\n \r\n var movesNecessary = calculateMoves(map[bestMove.fromIndex], map[bestMove.toIndex]);\r\n movesCount += movesNecessary;\r\n \r\n var isMovingRight = map[bestMove.toIndex].start > map[bestMove.fromIndex].end;\r\n map.splice(isMovingRight ? bestMove.fromIndex : bestMove.fromIndex - 1, 2, {\r\n start: isMovingRight ? map[bestMove.fromIndex].start + movesNecessary : map[bestMove.toIndex].start,\r\n end: isMovingRight ? map[bestMove.toIndex].end : map[bestMove.fromIndex].end - movesNecessary\r\n })\r\n } \r\n\r\n print(movesCount);\r\n}\r\n\r\nfunction findMovementValue(from, to, map) {\r\n var resultingLength = calculateSheepsLength(from) + calculateSheepsLength(to);\r\n\r\n var numberOfNeighbours = (to.start > from.end\r\n ? map.filter(x => x.start > to.end)\r\n : map.filter(x => x.end < to.start)).reduce((acc, elem) => acc + calculateSheepsLength(elem), 0);\r\n\r\n return resultingLength - calculateMoves(from, to) + numberOfNeighbours;\r\n}\r\n\r\nfunction calculateMoves(from, to) {\r\n return (to.start > from.end ? to.start - from.end - 1 : from.start - to.end - 1) * calculateSheepsLength(from);\r\n}\r\n\r\nfunction calculateSheepsLength(sheeps) {\r\n return sheeps.end - sheeps.start + 1;\r\n}"}], "src_uid": "e094a3451b8b28be90cf54a4400cb916"} {"nl": {"description": "It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.", "input_spec": "The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.", "output_spec": "In the first line print \"YES\" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line \"NO\" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form. If there are multiple possible answers, you can print any of them.", "sample_inputs": ["4\n1 3 3 1", "5\n2 4 1 4 8"], "sample_outputs": ["YES\n1 4 2 3 \n4 1 2 3 \n4 1 3 2", "NO"], "notes": "NoteIn the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks."}, "positive_code": [{"source_code": "// Generated by CoffeeScript 1.7.1\n(function() {\n var buffer, console, process, readable, solve, source;\n\n solve = function(tasks) {\n var i, index, numWays, pass, sorted, value, virtualPass, x, _i, _j, _k, _l, _len, _len1, _len2, _m, _n, _ref;\n sorted = [];\n for (i = _i = 0; _i <= 2000; i = ++_i) {\n sorted[i] = [];\n }\n for (index = _j = 0, _len = tasks.length; _j < _len; index = ++_j) {\n value = tasks[index];\n sorted[value].push(index + 1);\n }\n numWays = 1;\n for (_k = 0, _len1 = sorted.length; _k < _len1; _k++) {\n x = sorted[_k];\n if (x.length >= 2) {\n numWays *= x.length;\n }\n }\n console.log((numWays >= 3 ? \"YES\" : \"NO\"));\n if (numWays >= 3) {\n for (pass = _l = 1; _l <= 3; pass = ++_l) {\n virtualPass = pass;\n for (_m = 0, _len2 = sorted.length; _m < _len2; _m++) {\n x = sorted[_m];\n if (x.length === 1) {\n process.stdout.write(\"\" + x[0] + \" \");\n }\n if (x.length === 2) {\n if (virtualPass === 1) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \");\n }\n if (virtualPass === 2) {\n process.stdout.write(\"\" + x[1] + \" \" + x[0] + \" \");\n }\n if (virtualPass === 3) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \");\n virtualPass = 2;\n }\n }\n if (x.length >= 3) {\n if (virtualPass === 1) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \" + x[2] + \" \");\n }\n if (virtualPass === 2) {\n process.stdout.write(\"\" + x[1] + \" \" + x[2] + \" \" + x[0] + \" \");\n }\n if (virtualPass === 3) {\n process.stdout.write(\"\" + x[2] + \" \" + x[0] + \" \" + x[1] + \" \");\n }\n if (x.length > 3) {\n for (i = _n = 3, _ref = x.length; 3 <= _ref ? _n < _ref : _n > _ref; i = 3 <= _ref ? ++_n : --_n) {\n process.stdout.write(\"\" + x[i] + \" \");\n }\n }\n }\n }\n console.log(\"\");\n }\n }\n return console.log(\"\");\n };\n\n if ((typeof process !== \"undefined\" && process !== null ? process.stdin : void 0) != null) {\n source = \"\";\n readable = process.stdin;\n readable.on('data', function(chunk) {\n return source += chunk;\n });\n readable.on('end', function() {\n var i, _i, _len, _results;\n source = source.split(\"\\n\\n\");\n source = source.map(function(x) {\n return x.split(\"\\n\")[1];\n });\n source = source.map(function(x) {\n return x.split(/\\s/g).map(function(z) {\n return parseInt(z, 10);\n });\n });\n _results = [];\n for (_i = 0, _len = source.length; _i < _len; _i++) {\n i = source[_i];\n _results.push(solve(i));\n }\n return _results;\n });\n } else {\n buffer = '';\n console = {};\n console.log = function(x) {\n print(\"\" + buffer + x);\n return buffer = '';\n };\n process = {};\n process.stdout = {};\n process.stdout.write = function(x) {\n return buffer = \"\" + buffer + x;\n };\n source = readline();\n source = readline();\n source = source.split(/\\s/g).map(function(z) {\n return parseInt(z, 10);\n });\n solve(source);\n }\n\n}).call(this);\n"}, {"source_code": "(function(){print(function(){var e=-1;var t=+readline(),n={},r=[],i=readline().split(\" \").map(function(e,t){e=+e;n[e]=n[e]?n[e]+1:1;if(r.indexOf(e)===-1)r.push(e);return[e,t+1]});i=i.sort(function(e,t){return e[0]-t[0]});var s=0;r.forEach(function(e){if(n[e]===2)s++;else if(n[e]>1)s+=n[e]});if(s<2)return\"NO\";var o=[[],[],[]];r=[];i.forEach(function(e){if(r.indexOf(e[0])===-1)r.push(e[0])});r.forEach(function(t){var n=[];i.forEach(function(e){if(e[0]===t)n.push(e[1])});if(n.length===2){e++;switch(e%3){case 0:o[0].push(n[0],n[1]);o[1].push(n[0],n[1]);o[2].push(n[1],n[0]);break;case 1:o[0].push(n[0],n[1]);o[1].push(n[1],n[0]);o[2].push(n[0],n[1]);break;case 2:o[0].push(n[1],n[0]);o[1].push(n[0],n[1]);o[2].push(n[0],n[1]);break}}else{for(var r=0;r<3;r++)for(var s=r;s= 2) {\n numWays *= x.length;\n }\n }\n console.log((numWays >= 3 ? \"YES\" : \"NO\"));\n if (numWays >= 3) {\n for (pass = _l = 1; _l <= 3; pass = ++_l) {\n virtualPass = pass;\n for (_m = 0, _len2 = sorted.length; _m < _len2; _m++) {\n x = sorted[_m];\n if (x.length === 1) {\n process.stdout.write(\"\" + x[0] + \" \");\n }\n if (x.length === 2) {\n if (virtualPass === 1) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \");\n }\n if (virtualPass === 2) {\n process.stdout.write(\"\" + x[1] + \" \" + x[0] + \" \");\n }\n if (virtualPass === 3) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \");\n virtualPass = 2;\n }\n }\n if (x.length >= 3) {\n if (virtualPass === 1) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \" + x[2] + \" \");\n }\n if (virtualPass === 2) {\n process.stdout.write(\"\" + x[1] + \" \" + x[2] + \" \" + x[0] + \" \");\n }\n if (virtualPass === 3) {\n process.stdout.write(\"\" + x[2] + \" \" + x[0] + \" \" + x[1] + \" \");\n }\n }\n }\n console.log(\"\");\n }\n }\n return console.log(\"\");\n };\n\n if ((typeof process !== \"undefined\" && process !== null ? process.stdin : void 0) != null) {\n source = \"\";\n readable = process.stdin;\n readable.on('data', function(chunk) {\n return source += chunk;\n });\n readable.on('end', function() {\n var i, _i, _len, _results;\n source = source.split(\"\\n\\n\");\n source = source.map(function(x) {\n return x.split(\"\\n\")[1];\n });\n source = source.map(function(x) {\n return x.split(/\\s/g).map(function(z) {\n return parseInt(z, 10);\n });\n });\n _results = [];\n for (_i = 0, _len = source.length; _i < _len; _i++) {\n i = source[_i];\n _results.push(solve(i));\n }\n return _results;\n });\n } else {\n buffer = '';\n console = {};\n console.log = function(x) {\n print(\"\" + buffer + x);\n return buffer = '';\n };\n process = {};\n process.stdout = {};\n process.stdout.write = function(x) {\n return buffer = \"\" + buffer + x;\n };\n source = readline();\n source = readline();\n source = source.split(/\\s/g).map(function(z) {\n return parseInt(z, 10);\n });\n solve(source);\n }\n\n}).call(this);\n"}, {"source_code": "// Generated by CoffeeScript 1.7.1\n(function() {\n var buffer, console, process, readable, solve, source;\n\n solve = function(tasks) {\n var i, index, numWays, pass, sorted, value, virtualPass, x, _i, _j, _k, _l, _len, _len1, _len2, _m;\n sorted = [];\n for (i = _i = 0; _i <= 2000; i = ++_i) {\n sorted[i] = [];\n }\n for (index = _j = 0, _len = tasks.length; _j < _len; index = ++_j) {\n value = tasks[index];\n sorted[value].push(index + 1);\n }\n numWays = 1;\n for (_k = 0, _len1 = sorted.length; _k < _len1; _k++) {\n x = sorted[_k];\n if (x.length >= 2) {\n numWays *= x.length;\n }\n }\n console.log((numWays >= 3 ? \"YES\" : \"NO\"));\n if (numWays >= 3) {\n for (pass = _l = 1; _l <= 3; pass = ++_l) {\n virtualPass = pass;\n for (_m = 0, _len2 = sorted.length; _m < _len2; _m++) {\n x = sorted[_m];\n if (x.length === 1) {\n process.stdout.write(\"\" + x[0] + \" \");\n }\n if (x.length === 2) {\n if (virtualPass === 1) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \");\n }\n if (virtualPass === 2) {\n process.stdout.write(\"\" + x[1] + \" \" + x[0] + \" \");\n }\n if (virtualPass === 3) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \");\n virtualPass = 2;\n }\n }\n if (x.length === 3) {\n if (virtualPass === 1) {\n process.stdout.write(\"\" + x[0] + \" \" + x[1] + \" \" + x[2] + \" \");\n }\n if (virtualPass === 2) {\n process.stdout.write(\"\" + x[1] + \" \" + x[2] + \" \" + x[0] + \" \");\n }\n if (virtualPass === 3) {\n process.stdout.write(\"\" + x[2] + \" \" + x[0] + \" \" + x[1] + \" \");\n }\n }\n }\n console.log(\"\");\n }\n }\n return console.log(\"\");\n };\n\n if (typeof process !== \"undefined\" && process !== null) {\n source = \"\";\n readable = process.stdin;\n readable.on('data', function(chunk) {\n return source += chunk;\n });\n readable.on('end', function() {\n var i, _i, _len, _results;\n source = source.split(\"\\n\\n\");\n source = source.map(function(x) {\n return x.split(\"\\n\")[1];\n });\n source = source.map(function(x) {\n return x.split(/\\s/g).map(function(z) {\n return parseInt(z, 10);\n });\n });\n _results = [];\n for (_i = 0, _len = source.length; _i < _len; _i++) {\n i = source[_i];\n _results.push(solve(i));\n }\n return _results;\n });\n } else {\n buffer = '';\n console = {};\n console.log = function(x) {\n print(\"\" + buffer + x);\n return buffer = '';\n };\n process = {};\n process.stdout = {};\n process.stdout.write = function(x) {\n return buffer = \"\" + buffer + x;\n };\n source = readline();\n source = readline();\n source = source.split(/\\s/g).map(function(z) {\n return parseInt(z, 10);\n });\n solve(source);\n }\n\n}).call(this);\n"}, {"source_code": ";(function () {\n\n\tprint(function () {\n\n\t\tvar qw = true;\n\t\t\n\t\tvar n = +readline(),\n\t\t\tm = {}, lib = [],\n\t\t\th = readline().split(' ').map(function (e, i) {\n\t\t\t\te = +e;\n\t\t\t\tm[e] = m[e] ? m[e] + 1 : 1;\n\t\t\t\tif (lib.indexOf(e) === -1) lib.push(e);\n\t\t\t\treturn [e, i+1];\n\t\t\t});\n\n\t\th = h.sort(function (a, b) { return a[0] - b[0]; });\n\n\t\tvar flag = false;\n\t\tlib.forEach(function (e) {\n\t\t\tif (m[e] === 1) flag = true;\n\t\t});\n\n\t\tif (flag) return 'NO';\n\n\t\tvar ret = [[], [], []];\n\n\t\tlib = [];\n\t\th.forEach(function (e) {\n\t\t\tif (lib.indexOf(e[0]) === -1) lib.push(e[0]);\n\t\t});\n\n\t\tlib.forEach(function (e) {\n\t\t\tvar a = [];\n\t\t\th.forEach(function (j) {\n\t\t\t\tif (j[0] === e) a.push(j[1]);\n\t\t\t});\n\n\t\t\tif (a.length === 2) {\n\t\t\t\tqw = !qw;\n\t\t\t\tif (qw) {\n\t\t\t\t\tret[0].push(a[0], a[1]);\n\t\t\t\t\tret[1].push(a[0], a[1]);\n\t\t\t\t\tret[2].push(a[1], a[0]);\n\t\t\t\t} else {\n\t\t\t\t\tret[0].push(a[0], a[1]);\n\t\t\t\t\tret[1].push(a[1], a[0]);\n\t\t\t\t\tret[2].push(a[1], a[0]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (var j = 0; j < 3; j++)\n\t\t\t\t\tfor (var i = j; i < a.length; i++) ret[j].push(a[i]);\n\t\t\t\tret[1].push(a[0]);\n\t\t\t\tret[2].push(a[0], a[1]);\n\t\t\t}\n\t\t});\n\n\t\tvar n = 3;\n\t\twhile (n--) {\n\t\t\tret[n] = ret[n].join(' ');\n\t\t}\n\n\t\tret.unshift('YES');\n\n\t\treturn ret.join('\\n');\n\n\t}());\n\n}.call(this));\n"}, {"source_code": "(function(){print(function(){var e=-1;var t=+readline(),n={},r=[],i=readline().split(\" \").map(function(e,t){e=+e;n[e]=n[e]?n[e]+1:1;if(r.indexOf(e)===-1)r.push(e);return[e,t+1]});i=i.sort(function(e,t){return e[0]-t[0]});var s=0;r.forEach(function(e){if(n[e]>1)s+=n[e]});if(s<2)return\"NO\";var o=[[],[],[]];r=[];i.forEach(function(e){if(r.indexOf(e[0])===-1)r.push(e[0])});r.forEach(function(t){var n=[];i.forEach(function(e){if(e[0]===t)n.push(e[1])});if(n.length===2){e++;switch(e%3){case 0:o[0].push(n[0],n[1]);o[1].push(n[0],n[1]);o[2].push(n[1],n[0]);break;case 1:o[0].push(n[0],n[1]);o[1].push(n[1],n[0]);o[2].push(n[0],n[1]);break;case 2:o[0].push(n[1],n[0]);o[1].push(n[0],n[1]);o[2].push(n[0],n[1]);break}}else{for(var r=0;r<3;r++)for(var s=r;s ryan += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = ryan.split(EOL);\n var n = lines[0], e = 0, g = 0\n for(j = 1; j <= n; j++){\n var k = Number(lines[j]) \n e = '', g = ''\n if(k % 2 == 1){\n e = '1' + ' '\n for(l = 1; l < k; l+=2){\n e += (l + 2) + ' ' + (l + 1) + ' '\n }\n console.log(e)\n }else{\n for(l = 2; l <= k; l+=2){\n e += (l) + ' ' + (l - 1) + ' '\n }\n console.log(e)\n }\n }\n});"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var n = lines[i];\n var ans = '';\n if(n % 2 == 1){\n var a = 1;\n for(j = 0; j < n; j++){\n ans += a + ' ';\n if(j === 0){\n a += 2;\n }else if(j % 2 == 1){\n a--;\n }else if(j % 2 === 0){\n a += 3;\n }\n }\n }else{\n var b = 2;\n for(j = 0; j < n; j++){\n ans += b + ' ';\n if(j % 2 === 0){\n b--;\n }else if(j % 2 == 1){\n b += 3;\n }\n }\n }\n console.log(ans);\n }\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var res = solveMeFirst(b);\r\n let out = \"\";\r\n if (res) {\r\n for (let i = 0; i < res.length; i++) {\r\n out += res[i] + \" \";\r\n }\r\n console.log(out);\r\n }\r\n }\r\n}\r\nfunction solveMeFirst(p) {\r\n let arr = [];\r\n if (p % 2 === 0) {\r\n arr.push(2);\r\n } else if (p > 1) {\r\n arr.push(1);\r\n arr.push(3);\r\n } else {\r\n arr.push(1);\r\n }\r\n let isMinus = true;\r\n for (let i = p % 2 === 0 ? 1 : 2; i < p; i++) {\r\n if (isMinus) {\r\n arr[i] = arr[i - 1] - 1;\r\n isMinus = false;\r\n } else {\r\n arr[i] = arr[i - 1] + 3;\r\n isMinus = true;\r\n }\r\n }\r\n return arr;\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "'use strict';\n\nconst fs = require('fs');\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function() {\n inputString = inputString.split('\\n');\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction isPossible(n, x, heights) { \n heights.sort();\n heights.sort(function(a, b) {\n return a - b;\n });\n // //console.log(heights)\n \n let front = []\n let back = []\n \n for (let i = 0; i < heights.length; i++) {\n if (i < n) {\n front.push(heights[i])\n } else {\n back.push(heights[i])\n }\n }\n \n // //console.log(front)\n // //console.log(back)\n for (let j = 0; j < front.length; j++) {\n if (back[j] - front[j] < x) {\n // //console.log(back[j] + \" \" + front[j])\n return \"NO\";\n }\n }\n \n return \"YES\";\n}\n\nfunction calc(a, m) {\n let s = \"\";\n for (let index = 0; index < m; index++) {\n s += \"B\"\n }\n\n for (let index = 0; index < a.length; index++) {\n let ai = a[index];\n\n if (ai < (m + 1 - ai)) {\n let _s = s.replaceAt(ai - 1, \"A\");\n if (compare(_s, s) < 0) {\n s = _s;\n continue;\n } else if (compare(_s, s) >= 0) {\n let __ss = s.replaceAt(m + 1 - ai - 1, \"A\");\n if (compare(__ss, s) < 0) {\n s = __ss;\n continue;\n } \n }\n } else {\n let _s = s.replaceAt(m + 1 - ai - 1, \"A\");\n if (compare(_s, s) < 0) {\n s = _s;\n continue;\n } if (compare(_s, s) >= 0) {\n let __ss = s.replaceAt(ai - 1, \"A\");\n if (compare(__ss, s) < 0) {\n s = __ss;\n continue;\n }\n } \n }\n}\n\n return s;\n}\n\nfunction compare(s1, s2) {\n return s1.localeCompare(s2)\n}\n\nString.prototype.replaceAt = function(index, replacement) {\n return this.substring(0, index) + replacement + this.substring(index + replacement.length);\n}\n\n\nfunction main() {\n // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);\n\n const test_cases = parseInt(readLine().trim(), 10);\n\n for (let gItr = 0; gItr < test_cases; gItr++) {\n // const nk = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n // const n = nk[0];\n // const k = nk[1];\n\n const n = parseInt(readLine().trim(), 10);\n let a = []\n\n if (n%2 == 0) {\n for (let i = n; i > 0; i-=2) {\n a.push(i - 1)\n a.push(i)\n }\n } else {\n for (let i = n; i > 1; i-=2) {\n a.push(i - 1)\n a.push(i)\n }\n a.push(1)\n }\n\n a = a.reverse()\n // console.log(a)\n let s = \"\"\n for (let i = 0; i < a.length; i++) {\n // console.log(a[i])\n s += a[i] + \" \"\n }\n\n s.slice(0, -1);\n console.log(s)\n\n // const p = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n // const q = p\n // if (k == n || k == 0) {\n // console.log(\"0\");\n // } else {\n // const p1 = p.slice(0, k)\n // q.sort(function(a, b){return a-b});\n\n // let count = 0\n // for (let i = 0; i < k; i++) {\n // if (!p1.includes(q[i])) count++\n // }\n\n // console.log(count)\n // }\n\n // if ((n >= 1 && n <= 50) && (m >= 1 && m <= 50)) {\n // const val = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n // const val = readLine().trim()\n // if (val.toUpperCase() == \"YES\") console.log(\"YES\")\n // else console.log(\"NO\")\n // let output = calc(val, m);\n // console.log(output)\n // }\n // ws.write(result + '\\n');\n }\n\n // ws.end();\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = [];\r\n\t\tfor(var i = 1; i <= N; i++){\r\n\t\t\tlist.push(i);\r\n\t\t}\r\n\t\tfor(var i = N - 1; i > 0; i -= 2){\r\n\t\t\tvar tmp = list[i - 1];\r\n\t\t\tlist[i - 1] = list[i];\r\n\t\t\tlist[i] = tmp;\r\n\t\t}\r\n\t\tmyout(myconv(list, 8));\r\n\t}\r\n}\r\n"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n\r\nvar T = readline();\r\nvar inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n // var [n, k] = readline().split(' ').map((x) => parseInt(x));\r\n // var a = readline().split(' ').map((x) => parseInt(x));\r\n var n = readline();\r\n var a = [];\r\n if(n % 2 == 0) {\r\n for(var i=0;i {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n \r\nfunction main() {\r\n let N = readline();\r\n \r\n for (let i = 0; i < N; i++) {\r\n const n = parseInt(readline(), 10);\r\n\r\n let result = [];\r\n let i = 0;\r\n if (n % 2 === 0) {\r\n result.push(2);\r\n result.push(1);\r\n i = 3;\r\n for (; i <= n; i++) {\r\n i % 2 === 0 ? result.push(i - 1) : result.push(i + 1);\r\n }\r\n } else {\r\n result.push(1);\r\n i = 2;\r\n for (; i <= n; i++) {\r\n i % 2 === 0 ? result.push(i + 1) : result.push(i - 1);\r\n }\r\n }\r\n\r\n output(result.join(' '));\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n) {\r\n const res = new Array(n);\r\n for (let i = n - 1; i >= 0; i -= 2) {\r\n if (i === 0) {\r\n res[i] = 1;\r\n } else {\r\n res[i] = i;\r\n res[i - 1] = i + 1;\r\n }\r\n }\r\n return res.join(' ');\r\n}\r\n\r\nasync function main(r) {\r\n const rn = async () => Number(await r());\r\n try {\r\n let t = Number(await r());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = await rn();\r\n res[i] = solve(n);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "negative_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0]\n var a = 0\n for(j = 1; j <= n ;j ++){\n var k = lines[j]\n a = k + ' '\n for(l = 1; l < k; l++){\n a += l + ' '\n }\n console.log(a)\n \n }\n \n \n});"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n; j++){\n var f = false\n var h = lines[j].split('')\n var r = lines[j].split('')\n h.reverse()\n console.log(h, r)\n if(h == r){\n for(l = 0 ; l < h.length; l++){\n if(h[l] == h[l + 1]){\n f = true\n }else{\n f = false\n h.splice(0, 0, h[1], h[0])\n h.splice(2, 2)\n break;\n }\n }\n if(f === true){\n console.log(-1)\n }else{\n console.log(h)\n }\n }else{\n console.log(lines[j], 'dasd')\n }\n \n }\n});\n "}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var n = lines[0];\n for(i = 1; i <= n; i++){\n var t = lines[i];\n \n }\n console.log(1);\n console.log(2, 1);\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var res = solveMeFirst(b);\r\n let out = \"\";\r\n if (res) {\r\n for (let i = 0; i < res.length; i++) {\r\n out += res[i] + \" \";\r\n }\r\n console.log(out);\r\n }\r\n }\r\n}\r\nfunction solveMeFirst(p) {\r\n let arr = [];\r\n for (let i = +p; i >= 1; i--) {\r\n arr.push(i);\r\n }\r\n return arr;\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "'use strict';\n\nconst fs = require('fs');\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function() {\n inputString = inputString.split('\\n');\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction isPossible(n, x, heights) { \n heights.sort();\n heights.sort(function(a, b) {\n return a - b;\n });\n // //console.log(heights)\n \n let front = []\n let back = []\n \n for (let i = 0; i < heights.length; i++) {\n if (i < n) {\n front.push(heights[i])\n } else {\n back.push(heights[i])\n }\n }\n \n // //console.log(front)\n // //console.log(back)\n for (let j = 0; j < front.length; j++) {\n if (back[j] - front[j] < x) {\n // //console.log(back[j] + \" \" + front[j])\n return \"NO\";\n }\n }\n \n return \"YES\";\n}\n\nfunction calc(a, m) {\n let s = \"\";\n for (let index = 0; index < m; index++) {\n s += \"B\"\n }\n\n for (let index = 0; index < a.length; index++) {\n let ai = a[index];\n\n if (ai < (m + 1 - ai)) {\n let _s = s.replaceAt(ai - 1, \"A\");\n if (compare(_s, s) < 0) {\n s = _s;\n continue;\n } else if (compare(_s, s) >= 0) {\n let __ss = s.replaceAt(m + 1 - ai - 1, \"A\");\n if (compare(__ss, s) < 0) {\n s = __ss;\n continue;\n } \n }\n } else {\n let _s = s.replaceAt(m + 1 - ai - 1, \"A\");\n if (compare(_s, s) < 0) {\n s = _s;\n continue;\n } if (compare(_s, s) >= 0) {\n let __ss = s.replaceAt(ai - 1, \"A\");\n if (compare(__ss, s) < 0) {\n s = __ss;\n continue;\n }\n } \n }\n}\n\n return s;\n}\n\nfunction compare(s1, s2) {\n return s1.localeCompare(s2)\n}\n\nString.prototype.replaceAt = function(index, replacement) {\n return this.substring(0, index) + replacement + this.substring(index + replacement.length);\n}\n\n\nfunction main() {\n // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);\n\n const test_cases = parseInt(readLine().trim(), 10);\n\n for (let gItr = 0; gItr < test_cases; gItr++) {\n // const nk = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n // const n = nk[0];\n // const k = nk[1];\n\n const n = parseInt(readLine().trim(), 10);\n let a = []\n\n for (let i = n; i > 0; i --) {\n a.push(i)\n }\n\n let s = \"\"\n for (let i = 0; i < a.length; i++) {\n // console.log(a[i])\n s += a[i] + \" \"\n }\n\n s.slice(0, -1);\n console.log(s)\n\n // const p = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n // const q = p\n // if (k == n || k == 0) {\n // console.log(\"0\");\n // } else {\n // const p1 = p.slice(0, k)\n // q.sort(function(a, b){return a-b});\n\n // let count = 0\n // for (let i = 0; i < k; i++) {\n // if (!p1.includes(q[i])) count++\n // }\n\n // console.log(count)\n // }\n\n // if ((n >= 1 && n <= 50) && (m >= 1 && m <= 50)) {\n // const val = readLine().replace(/\\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));\n // const val = readLine().trim()\n // if (val.toUpperCase() == \"YES\") console.log(\"YES\")\n // else console.log(\"NO\")\n // let output = calc(val, m);\n // console.log(output)\n // }\n // ws.write(result + '\\n');\n }\n\n // ws.end();\n}\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$$$) — 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$$$) — 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": "function calc(n, m, a) {\n var dict = {};\n var count = 0;\n var res = \"\";\n \n a.map(elem => {\n if (dict[elem]) {\n dict[elem]++;\n res += \"0\";\n } else {\n count++;\n dict[elem] = 1;\n \n if (count === n) {\n res += \"1\";\n Object.keys(dict).map(key => {\n dict[key]--;\n });\n count = Object.keys(dict).filter(key => {\n return dict[key] > 0;\n }).length;\n } else {\n res += \"0\";\n }\n }\n })\n \n return res;\n}\n\nvar nm = readline().split(\" \");\nvar n = parseInt(nm[0]);\nvar m = parseInt(nm[1]);\nvar a = readline().split(\" \");\n\nprint(calc(n, m, a));"}], "negative_code": [{"source_code": "function calc(n, m, a) {\n var dict = {};\n var count = 0;\n var res = \"\";\n \n a.map(elem => {\n if (dict[elem]) {\n dict[elem]++;\n res += \"0\";\n } else {\n count++;\n dict[elem] = 1;\n \n if (count === n) {\n res += \"1\";\n count = 0;\n Object.keys(dict).map(key => {\n dict[key]--;\n })\n } else {\n res += \"0\";\n }\n }\n \n// console.log(dict);\n })\n \n return res;\n}\n\nvar nm = readline().split(\" \");\nvar n = parseInt(nm[0]);\nvar m = parseInt(nm[1]);\nvar a = readline().split(\" \");\n\nprint(calc(n, m, a));\n\n\n\n \n\n\n\n"}, {"source_code": "function calc(n, m, a) {\n var dict = {};\n var count = 0;\n var res = \"\";\n \n a.map(elem => {\n if (dict[elem]) {\n dict[elem]++;\n res += \"0\";\n } else {\n count++;\n dict[elem] = 1;\n \n if (count === n) {\n res += \"1\";\n count = Object.keys(dict).filter(key => {\n dict[key] > 0;\n }).length;\n Object.keys(dict).map(key => {\n dict[key]--;\n })\n } else {\n res += \"0\";\n }\n }\n \n// console.log(dict);\n })\n \n return res;\n}\n\nvar nm = readline().split(\" \");\nvar n = parseInt(nm[0]);\nvar m = parseInt(nm[1]);\nvar a = readline().split(\" \");\n\nprint(calc(n, m, a));"}, {"source_code": "function calc(n, m, a) {\n var dict = {};\n var count = 0;\n var res = \"\";\n \n a.map(elem => {\n if (dict[elem]) {\n dict[elem]++;\n res += \"0\";\n } else {\n count++;\n dict[elem] = 1;\n \n if (count === n) {\n res += \"1\";\n count = 0;\n Object.keys(dict).map(key => {\n dict[key]--;\n })\n } else {\n res += \"0\";\n }\n }\n \n// console.log(dict);\n })\n \n return res;\n}\n\nvar nm = readline().split(\" \");\nvar n = parseInt(nm[0]);\nvar m = parseInt(nm[1]);\nvar a = readline().split(\" \").map(elem => parseInt(elem));\n\nprint(calc(n, m, a));\n\n\n\n \n\n\n\n"}], "src_uid": "2070955288b2e2cdbae728d8e7ce78ab"} {"nl": {"description": "Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.Filya is given an array of non-negative integers a1, a2, ..., an. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal.Now he wonders if it's possible to pick such integer x and change some elements of the array using this x in order to make all elements equal.", "input_spec": "The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the number of integers in the Filya's array. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — elements of the array.", "output_spec": "If it's impossible to make all elements of the array equal using the process given in the problem statement, then print \"NO\" (without quotes) in the only line of the output. Otherwise print \"YES\" (without quotes).", "sample_inputs": ["5\n1 3 3 2 1", "5\n1 2 3 4 5"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample Filya should select x = 1, then add it to the first and the last elements of the array and subtract from the second and the third elements."}, "positive_code": [{"source_code": "function readIntTabLine(n) {\n var l = readline().split(' ')\n for (var i = 0 ; i < n ; i++) {\n l[i] = parseInt(l[i])\n }\n return l\n}\n\nvar n = parseInt(readline())\nvar tab = readIntTabLine(n)\nvar possible = true\nvar set = []\n\nfor (var i = 0 ; i < n && possible; i++) {\n if (set.indexOf(tab[i]) == -1)\n possible = set.push(tab[i]) <= 3\n}\n\nif (!possible) print('NO')\nelse if (set.length < 3) print('YES')\nelse {\n var tri = []\n tri.push(Math.min.apply(null, set))\n set.splice(set.indexOf(tri[0]),1)\n tri.push(Math.min(set[0],set[1]))\n tri.push(Math.max(set[0],set[1]))\n if (tri[1]-tri[0] == tri[2]-tri[1]) print('YES')\n else print('NO')\n}\n"}, {"source_code": "readline();\nvar a = readline().split( \" \" ).map( ai => parseInt( ai, 10 ) );\nvar values = [...new Set( a )];\nvar answer = \"NO\";\n// min + x = mid = max - x can't be equal to some other number.\nif ( values.length == 3 ) {\n values.sort( ( a, b ) => a - b );\n var min = values[ 0 ];\n var mid = values[ 1 ];\n var max = values[ 2 ];\n var x = ( max - min ) / 2;\n if ( Math.floor( x ) == x && min + x == mid && mid == max - x ) {\n answer = \"YES\";\n }\n} else if ( values.length < 3 ) {\n answer = \"YES\";\n}\nprint( answer );"}, {"source_code": "readline();\nvar a = readline().split( \" \" ).map( ai => parseInt( ai, 10 ) );\nvar values = [...new Set( a )];\nvar answer = \"NO\";\n// min + x = mid = max - x are only possible combinations of x and some number.\nif ( values.length == 3 ) {\n values.sort( ( a, b ) => a - b );\n var min = values[ 0 ];\n var mid = values[ 1 ];\n var max = values[ 2 ];\n // Derived from equation above.\n if ( 2 * mid == max + min ) {\n answer = \"YES\";\n }\n} else if ( values.length < 3 ) {\n answer = \"YES\";\n}\nprint( answer );"}], "negative_code": [], "src_uid": "27f837609b2777cefccb13aa4596d91c"} {"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$$$) — 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$$$) — 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": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ');\n\n var c = false;\n var nc = false;\n for(var i = 0; i < n; i++) {\n if(a[i] % 2) {\n c = true;\n }\n else {\n nc = true;\n }\n }\n\n if(c && nc) {\n print(a.sort((a, b) => a - b).join(' '));\n }\n else {\n print(a.join(' '));\n }\n}());"}], "negative_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ').sort((a, b) => {\n if((a + b) % 2)\n return a - b;\n else return 0;\n });\n print(a.join(' '));\n}());"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ');\n\n var res = '';\n for(var i = 1; i < n; i++) {\n if(a[i] < a[i - 1]) {\n var tmp = a[i];\n a[i] = a[i - 1];\n a[i - 1] = tmp;\n print(a.join(' '));\n return;\n }\n }\n\n print(a.join(' '));\n}());"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ').sort((a, b) => a - b);\n print(a.join(' '));\n}());"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ');\n\n var res = '';\n for(var i = 1; i < n; i++) {\n if((a[i] + a[i - 1]) % 2 && a[i] < a[i - 1]) {\n var tmp = a[i];\n a[i] = a[i - 1];\n a[i - 1] = tmp;\n print(a.join(' '));\n return;\n }\n }\n \n print(a.join(' '));\n}());"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ');\n \n var c = false;\n var n = false;\n for(var i = 0; i < n; i++) {\n if(a[i] % 2) {\n c = true;\n }\n else {\n n = true;\n }\n }\n \n if(c && n) {\n print(a.sort((a, b) => a - b).join(' '));\n }\n else {\n print(a.join(' '));\n }\n \n \n}());"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ');\n\n var res = '';\n for(var i = 0; i < n; i++) {\n for(var j = i + 1; j < n; j++) {\n if((a[i] + a[j]) % 2 && a[i] > a[j]) {\n var tmp = a[i];\n a[i] = a[j];\n a[j] = tmp;\n print(a.join(' '));\n return;\n }\n }\n }\n\n print(a.join(' '));\n}());"}], "src_uid": "aab7f7cce0b704051627b625294635bc"} {"nl": {"description": "As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form \"command ip;\" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers. Each ip is of form \"a.b.c.d\" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is \"command ip;\" Dustin has to replace it with \"command ip; #name\" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.", "input_spec": "The first line of input contains two integers n and m (1 ≤ n, m ≤ 1000). The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1 ≤ |name| ≤ 10, name only consists of English lowercase letters). It is guaranteed that all ip are distinct. The next m lines contain the commands in the configuration file. Each line is of form \"command ip;\" (1 ≤ |command| ≤ 10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers.", "output_spec": "Print m lines, the commands in the configuration file after Dustin did his task.", "sample_inputs": ["2 2\nmain 192.168.0.2\nreplica 192.168.0.1\nblock 192.168.0.1;\nproxy 192.168.0.2;", "3 5\ngoogle 8.8.8.8\ncodeforces 212.193.33.27\nserver 138.197.64.57\nredirect 138.197.64.57;\nblock 8.8.8.8;\ncf 212.193.33.27;\nunblock 8.8.8.8;\ncheck 138.197.64.57;"], "sample_outputs": ["block 192.168.0.1; #replica\nproxy 192.168.0.2; #main", "redirect 138.197.64.57; #server\nblock 8.8.8.8; #google\ncf 212.193.33.27; #codeforces\nunblock 8.8.8.8; #google\ncheck 138.197.64.57; #server"], "notes": null}, "positive_code": [{"source_code": "'use strict';\n\n\nlet line = readline().split(' ');\nlet n = parseInt(line[0]);\nlet m = parseInt(line[1]);\nconst container = {};\nlet command, ip;\nwhile (n--) {\n line = readline().split(' ');\n command = line[0];\n ip = line[1];\n container[ip] = command;\n}\n\nwhile (m--) {\n line = readline().split(' ');\n command = line[0];\n ip = line[1].substr(0, line[1].length - 1);\n print (command + ' ' + ip + '; #' + container[ip]);\n}\n"}, {"source_code": "'use strict';\n\n\nlet line = readline().split(' ');\nlet n = parseInt(line[0]);\nlet m = parseInt(line[1]);\nconst container = {};\nlet command, ip;\nwhile (n--) {\n line = readline().split(' ');\n command = line[0];\n ip = line[1];\n container[ip] = command;\n}\n\nwhile (m--) {\n line = readline().split(' ');\n command = line[0];\n ip = line[1].substr(0, line[1].length - 1);\n print (`${command} ${ip}; #${container[ip]}`);\n}\n"}, {"source_code": "var l=readline().split(\" \");\nvar n=parseInt(l[0]);\nvar m=parseInt(l[1]);\nvar an=new Array(n);\nvar am=new Array(m);\nfor(var i=0;i item.ip === ip);\n result.push(line + ' #' + item.name);\n }\n\n for (var i = 0; i < m; i++) {\n print(result[i]);\n }\n}\n\nmain();\n"}, {"source_code": "var a = readline().split(\" \");\nvar n = parseInt(a[0]);\nvar m = parseInt(a[1]);\n\nvar nameArr = [];\nvar ipArr = [];\nvar funcArr = [];\n\nfor(var i = 0; i < n; i++)\n{\n var nInput = readline().split(\" \");\n var name = nInput[0];\n var ip = nInput[1] + \";\";\n\n nameArr.push(name);\n ipArr.push(ip);\n}\n\nfor(var i = 0; i < m; i++)\n{\n var mInput = readline().split(\" \");\n var func = mInput[0];\n var ip = mInput[1];\n\n funcArr.push(ip);\n funcArr.push(func);\n}\n\nfor(var i = 0; i < (2 * m); i += 2)\n{\n var ip = funcArr[i];\n var func = funcArr[i + 1];\n\n for(var j = 0; j < n; j++)\n {\n if(ip == ipArr[j])\n {\n var name = nameArr[j];\n break;\n }\n }\n\n print(func + \" \" + ip + \" #\" + name);\n}"}, {"source_code": "var dim = readline().split(' ');\nvar n = parseInt(dim[0]);\nvar m = parseInt(dim[1]);\nvar k, mydns = {};\nfor(k = 1; k <= n; k++){\n\tvar server = readline().split(' ');\n\tmydns[server[1]] = server[0];\n}\n\nfor(k = 0; k < m; k++){\n\tvar command = readline().split(/[; ]/);\n\tprint(command[0] + ' ' + command[1] + '; #' + mydns[command[1]]);\n}\n"}, {"source_code": "nm = readline().split(' ').map(Number);\n\nvar n = nm[0], m = nm[1], nameArr = [];\n\nfor (var i = 0; i < n; i++) {\n\tstr = readline().split(' ');\n\n\tfor (var j = 0; j < str.length; j++) {\n\t\tnameArr.push(str[j]);\n\t};\n};\n\nfor (var j = 0; j < m; j++) {\n\tstr = readline().split(' ');\n\n\tfor (var k = 0; k < nameArr.length; k++) {\n\t\tif (nameArr[k] + ';' == str[1]) {\n\t\t\tprint(str.join(' ') + ' #' + nameArr[k - 1]);\n\t\t};\n\t};\n};"}, {"source_code": "\"use strict\";\n\nconst readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet [namesLength, commandsLenght] = [null];\nlet ips = [], names = [], commands = [];\n\nreadline.on('line', line => {\n if (!namesLength) {\n [namesLength, commandsLenght] = line.split(' ');\n } else if (names.length < namesLength) {\n let [a, b] = line.split(' ');\n names.push(a);\n ips.push(b);\n } else {\n commands.push(line.split(' '));\n if (commands.length == commandsLenght)\n readline.close();\n }\n});\n\nreadline.on('close', () => {\n writeFile();\n});\n\nconst writeFile = () => {\n commands.map(input => {\n let [name, target] = input;\n let origin = names[ips.indexOf(target.split(';')[0])];\n console.log(`${name} ${target} #${origin}`);\n })\n};"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet n, m;\nconst obj = {};\n\nrl.on('line', (d) => {\n if (c === 0) {\n [n, m] = d.split(' ').map(Number);\n\n c++;\n return;\n }\n\n if (c <= n) {\n const [name, ip] = d.split(' ');\n obj[`${ip};`] = `#${name}`;\n\n c++;\n return;\n }\n\n const [command, ip] = d.split(' ');\n console.log(`${command} ${ip} ${obj[ip]}`);\n\n c++;\n});\n\nrl.on('close', () => {\n\n});\n"}], "negative_code": [{"source_code": "'use strict';\n\nlet line = readline().split(' ');\nlet n = parseInt(line[0]);\nlet m = parseInt(line[1]);\nconst container = {};\nlet command, ip;\nwhile (n--) {\n line = readline().split(' ');\n command = line[0];\n ip = line[1];\n container[ip] = command;\n}\n\nwhile (m--) {\n line = readline().split(' ');\n command = line[0];\n ip = line[1].substr(0, ip.length - 1);\n print (command + ' ' + ip + '; #' + container[ip]);\n}\n"}, {"source_code": "var l=readline().split(\" \");\nvar n=parseInt(l[0]);\nvar m=parseInt(l[1]);\nvar ar=new Array(n);\nvar i2=0;\nvar full1=\"\",full2=\"\";\nvar ar2=new Array(m);\nfor(var i=0;i item.ip === ip);\n result.push(line + ' ' + item.name);\n }\n\n for (var i = 0; i < m; i++) {\n print(result[i]);\n }\n}\n\nmain();\n"}, {"source_code": "var dim = readline().split(' ');\n(function(n,m){\n\twrite(n+'***'+m);\n\treturn print();\n})(dim[0],dim[1]);"}], "src_uid": "94501cd676a9214a59943b8ddd1dd31b"} {"nl": {"description": "The $$$\\text{$$$gcdSum$$$}$$$ of a positive integer is the $$$gcd$$$ of that integer with its sum of digits. Formally, $$$\\text{$$$gcdSum$$$}(x) = gcd(x, \\text{ sum of digits of } x)$$$ for a positive integer $$$x$$$. $$$gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$ — the largest integer $$$d$$$ such that both integers $$$a$$$ and $$$b$$$ are divisible by $$$d$$$.For example: $$$\\text{$$$gcdSum$$$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$$$.Given an integer $$$n$$$, find the smallest integer $$$x \\ge n$$$ such that $$$\\text{$$$gcdSum$$$}(x) > 1$$$.", "input_spec": "The first line of input contains one integer $$$t$$$ $$$(1 \\le t \\le 10^4)$$$ — the number of test cases. Then $$$t$$$ lines follow, each containing a single integer $$$n$$$ $$$(1 \\le n \\le 10^{18})$$$. All test cases in one test are different.", "output_spec": "Output $$$t$$$ lines, where the $$$i$$$-th line is a single integer containing the answer to the $$$i$$$-th test case.", "sample_inputs": ["3\n11\n31\n75"], "sample_outputs": ["12\n33\n75"], "notes": "NoteLet us explain the three test cases in the sample.Test case 1: $$$n = 11$$$: $$$\\text{$$$gcdSum$$$}(11) = gcd(11, 1 + 1) = gcd(11,\\ 2) = 1$$$.$$$\\text{$$$gcdSum$$$}(12) = gcd(12, 1 + 2) = gcd(12,\\ 3) = 3$$$.So the smallest number $$$\\ge 11$$$ whose $$$gcdSum$$$ $$$> 1$$$ is $$$12$$$.Test case 2: $$$n = 31$$$: $$$\\text{$$$gcdSum$$$}(31) = gcd(31, 3 + 1) = gcd(31,\\ 4) = 1$$$.$$$\\text{$$$gcdSum$$$}(32) = gcd(32, 3 + 2) = gcd(32,\\ 5) = 1$$$.$$$\\text{$$$gcdSum$$$}(33) = gcd(33, 3 + 3) = gcd(33,\\ 6) = 3$$$.So the smallest number $$$\\ge 31$$$ whose $$$gcdSum$$$ $$$> 1$$$ is $$$33$$$.Test case 3: $$$\\ n = 75$$$: $$$\\text{$$$gcdSum$$$}(75) = gcd(75, 7 + 5) = gcd(75,\\ 12) = 3$$$.The $$$\\text{$$$gcdSum$$$}$$$ of $$$75$$$ is already $$$> 1$$$. Hence, it is the answer."}, "positive_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main() \n});\n\nfunction readline() {\n return inputString[currentLine++]\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n let testCases = readline()\n while(testCases--)\n solve()\n // let testCases = readline()\n // let testNum = 1,\n // ans = null\n // while(testCases--) {\n // ans = solve()\n // console.log('Case #' + (testNum++) + ': ' + ans)\n // }\n}\n\n// function to solve problems\nfunction solve (){\n let n = BigInt(readline())\n let sum = 0,\n gcdSum = 0n,\n count = 2,\n tempGcdSum = 0,\n ans = n\n\n // find smallest of n, n+1 and n+2\n sum = sumOfDigits(n)\n gcdSum = findGcdSum(n, sum)\n while (count-- && gcdSum == 1) {\n n++\n if (n % 10n == 0) {\n sum = sumOfDigits(n)\n } else {\n sum++\n }\n tempGcdSum = findGcdSum(n, sum)\n // console.log('tempGcdSum:', tempGcdSum)\n if (tempGcdSum != 1) {\n ans = n\n break\n }\n }\n console.log(ans.toString())\n}\n\nfunction sumOfDigits (n) {\n let ans = 0n\n while (n > 0) {\n ans += n % 10n\n n = BigInt(n/10n)\n }\n return ans\n}\n\nfunction findGcdSum (a, b) {\n if (b == 0)\n return a\n return findGcdSum(b, a%b)\n}\n"}, {"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n) => {\r\n while (1) {\r\n let s = n.toString();\r\n let sum = 0n;\r\n for (const c of s) sum += BigInt(c);\r\n let res = gcd(n, sum);\r\n if (res > 1) return pr(s);\r\n n++;\r\n }\r\n};\r\n\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(BigInt(line));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0];\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i]);\r\n i++;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\nfunction solve(n) {\r\n // if (n.length <= 2) return 0\r\n for (let i = BigInt(n); ; i++) {\r\n let len = i.toString().length\r\n let sum = i.toString().split('').map(i => +i).reduce((acc, i) => acc + i, 0)\r\n sum = BigInt(sum)\r\n for (let j = 2n; j <= sum; j++) {\r\n if (BigInt(i) % j === 0n && sum % j === 0n) return i.toString()\r\n }\r\n\r\n }\r\n\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i++) console.log(solve(inputArr[i]))\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n const x = readline();\r\n\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var a = BigInt(readline());\r\n\r\n // var a = read\r\n while (gcd(a,SUMnUMBER(a))<=1) a++\r\n console.log(a.toString())\r\n var values\r\n })\r\n // var b = a.sort((a, b) => Math.abs(a) - Math.abs(b))\r\n\r\n}\r\n\r\nfunction SUMnUMBER(x) {\r\n var sum = 0n\r\n while (x>0n){\r\n sum+=x% 10n\r\n x = x/10n\r\n }\r\n return sum\r\n}\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n"}], "negative_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main() \n});\n\nfunction readline() {\n return inputString[currentLine++]\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n let testCases = readline()\n while(testCases--)\n solve()\n // let testCases = readline()\n // let testNum = 1,\n // ans = null\n // while(testCases--) {\n // ans = solve()\n // console.log('Case #' + (testNum++) + ': ' + ans)\n // }\n}\n\n// function to solve problems\nfunction solve (){\n let n = readline().split(' ').map(x => +x)\n let sum = 0,\n gcdSum = 0,\n count = 2,\n tempGcdSum = 0,\n ans = 0\n\n // find smallest of n, n+1 and n+2\n sum = sumOfDigits(n)\n gcdSum = findGcdSum(n, sum)\n ans = +n\n while (count-- && gcdSum == 1) {\n n++\n if (n % 10 == 0) {\n sum = sumOfDigits(n)\n } else {\n sum ++\n }\n tempGcdSum = findGcdSum(n, sum)\n // console.log('tempGcdSum:', tempGcdSum)\n if (tempGcdSum != 1) {\n gcdSum = tempGcdSum\n ans = n\n break\n }\n }\n console.log(ans)\n}\n\nfunction sumOfDigits (n) {\n let ans = 0\n while (n > 0) {\n ans += n % 10\n n = parseInt(n/10)\n }\n return ans\n}\n\nfunction findGcdSum (a, b) {\n if (b == 0)\n return a\n return findGcdSum(b, a%b)\n}\n"}], "src_uid": "204e75827b7016eb1f1fbe1d6b60b03d"} {"nl": {"description": "Let $$$a$$$ be a matrix of size $$$r \\times c$$$ containing positive integers, not necessarily distinct. Rows of the matrix are numbered from $$$1$$$ to $$$r$$$, columns are numbered from $$$1$$$ to $$$c$$$. We can construct an array $$$b$$$ consisting of $$$r + c$$$ integers as follows: for each $$$i \\in [1, r]$$$, let $$$b_i$$$ be the greatest common divisor of integers in the $$$i$$$-th row, and for each $$$j \\in [1, c]$$$ let $$$b_{r+j}$$$ be the greatest common divisor of integers in the $$$j$$$-th column. We call the matrix diverse if all $$$r + c$$$ numbers $$$b_k$$$ ($$$k \\in [1, r + c]$$$) are pairwise distinct. The magnitude of a matrix equals to the maximum of $$$b_k$$$.For example, suppose we have the following matrix: $$$\\begin{pmatrix} 2 & 9 & 7\\\\ 4 & 144 & 84 \\end{pmatrix}$$$ We construct the array $$$b$$$: $$$b_1$$$ is the greatest common divisor of $$$2$$$, $$$9$$$, and $$$7$$$, that is $$$1$$$; $$$b_2$$$ is the greatest common divisor of $$$4$$$, $$$144$$$, and $$$84$$$, that is $$$4$$$; $$$b_3$$$ is the greatest common divisor of $$$2$$$ and $$$4$$$, that is $$$2$$$; $$$b_4$$$ is the greatest common divisor of $$$9$$$ and $$$144$$$, that is $$$9$$$; $$$b_5$$$ is the greatest common divisor of $$$7$$$ and $$$84$$$, that is $$$7$$$. So $$$b = [1, 4, 2, 9, 7]$$$. All values in this array are distinct, so the matrix is diverse. The magnitude is equal to $$$9$$$.For a given $$$r$$$ and $$$c$$$, find a diverse matrix that minimises the magnitude. If there are multiple solutions, you may output any of them. If there are no solutions, output a single integer $$$0$$$. ", "input_spec": "The only line in the input contains two space separated integers $$$r$$$ and $$$c$$$ ($$$1 \\leq r,c \\leq 500$$$) — the number of rows and the number of columns of the matrix to be found.", "output_spec": "If there is no solution, output a single integer $$$0$$$. Otherwise, output $$$r$$$ rows. The $$$i$$$-th of them should contain $$$c$$$ space-separated integers, the $$$j$$$-th of which is $$$a_{i,j}$$$ — the positive integer in the $$$i$$$-th row and $$$j$$$-th column of a diverse matrix minimizing the magnitude. Furthermore, it must hold that $$$1 \\leq a_{i,j} \\leq 10^9$$$. It can be shown that if a solution exists, there is also a solution with this additional constraint (still having minimum possible magnitude).", "sample_inputs": ["2 2", "1 1"], "sample_outputs": ["4 12\n2 9", "0"], "notes": "NoteIn the first example, the GCDs of rows are $$$b_1 = 4$$$ and $$$b_2 = 1$$$, and the GCDs of columns are $$$b_3 = 2$$$ and $$$b_4 = 3$$$. All GCDs are pairwise distinct and the maximum of them is $$$4$$$. Since the GCDs have to be distinct and at least $$$1$$$, it is clear that there are no diverse matrices of size $$$2 \\times 2$$$ with magnitude smaller than $$$4$$$.In the second example, no matter what $$$a_{1,1}$$$ is, $$$b_1 = b_2$$$ will always hold, so there are no diverse matrices."}, "positive_code": [{"source_code": "\nfunction wr(x) {\n console.log(x)\n}\n\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const [r, c] = arr[0].split(' ').map(a => parseInt(a))\n\n let ar = new Array(r)\n\n if(r == 1 && c == 1) {\n wr(0)\n return\n }\n\n if(r == 1) {\n ar[0] = new Array(c)\n let x = 2\n for(let j = 0; j < c; j++, x++) {\n ar[0][j] = x\n }\n }\n else if(c == 1) {\n let x = 2\n for(let i = 0; i < r; i++) {\n ar[i] = new Array(c)\n for(let j = 0; j < c; j++, x++) {\n ar[i][j] = x\n }\n }\n }\n else {\n for(let i = 0; i < r; i++) {\n ar[i] = new Array(c)\n for(let j = 0; j < c; j++) {\n ar[i][j] = (i + 1) * (r + j + 1)\n }\n }\n }\n\n for(let i = 0; i < r; i++) {\n wr(ar[i].join(' '))\n }\n})"}], "negative_code": [{"source_code": "\nfunction wr(x) {\n console.log(x)\n}\n\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const [r, c] = arr[0].split(' ').map(a => parseInt(a))\n\n let ar = new Array(r)\n\n if(r == 1 && c == 1) {\n wr(0)\n return\n }\n\n if(r == 1) {\n ar[0] = new Array(c)\n let x = 4\n for(let j = 0; j < c; j++, x+= 2) {\n ar[0][j] = x\n }\n }\n else if(c == 1) {\n let x = 4\n for(let i = 0; i < r; i++) {\n ar[i] = new Array(c)\n for(let j = 0; j < c; j++, x+= 2) {\n ar[i][j] = x\n }\n }\n }\n else {\n for(let i = 0; i < r; i++) {\n ar[i] = new Array(c)\n for(let j = 0; j < c; j++) {\n ar[i][j] = (i + 1) * (r + j + 1)\n }\n }\n }\n\n for(let i = 0; i < r; i++) {\n wr(ar[i].join(' '))\n }\n})"}], "src_uid": "acebe5e1d927d32d65a4500d1d45c4ba"} {"nl": {"description": "Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells. ", "input_spec": "In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j).", "output_spec": "For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.", "sample_inputs": ["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"], "sample_outputs": ["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"], "notes": "NoteThe sample corresponds to the figure in the statement."}, "positive_code": [{"source_code": "const {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n const [n, m, k, t] = ils[0].split(' ').map(v => parseInt(v))\n\n let W = []\n ils.slice(1, k + 1).forEach(l => W.push(l.split(' ').map(v => parseInt(v))))\n let T = []\n let O = []\n ils.slice(k + 1).forEach(l => {\n l = l.split(' ').map(v => parseInt(v))\n T.push(l)\n O.push(l)\n })\n\n W.sort((a, b) => a[0] - b[0] || a[1] - b[1])\n O.sort((a, b) => a[0] - b[0] || a[1] - b[1])\n\n let i = 0\n O.forEach(p => {\n while (\n W[i]\n && (\n W[i][0] < p[0]\n || W[i][0] == p[0] && W[i][1] < p[1]\n )\n ) i++\n p.push(i)\n if (W[i] && W[i][0] == p[0] && W[i][1] == p[1]) p.push(3)\n })\n\n let C = ['Carrots', 'Kiwis', 'Grapes']\n T.forEach(p => {\n if (p[3]) return console.log('Waste')\n console.log(C[((p[0] - 1) * m + (p[1] - 1) - p[2]) % 3])\n })\n})"}], "negative_code": [{"source_code": "const {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n const [n, m, k, t] = ils[0].split(' ').map(v => parseInt(v))\n\n let W = []\n ils.slice(1, k + 1).forEach(l => W.push(l.split(' ').map(v => parseInt(v))))\n let T = []\n let O = []\n ils.slice(k + 1).forEach(l => {\n l = l.split(' ').map(v => parseInt(v))\n T.push(l)\n O.push(l)\n })\n\n W.sort((a, b) => a[0] - b[0] || a[1] - b[1])\n O.sort((a, b) => a[0] - b[0] || a[1] - b[1])\n\n let i = 0\n O.forEach(p => {\n while (\n W[i]\n && (\n W[i][0] < p[0]\n || W[i][0] == p[0] && W[i][1] < p[1]\n )\n ) i++\n p.push(i)\n if (W[i] && W[i][0] == p[0] && W[i][1] == p[1]) p.push(3)\n })\n\n let C = ['Carrots', 'Kiwis', 'Grapes']\n T.forEach(p => {\n if (p[3]) return console.log('Waste')\n console.log(C[(p[0] * m + p[1] - p[2]) % 3])\n })\n})"}], "src_uid": "bfef3f835357dae290620efabe650580"} {"nl": {"description": "Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.Help Shapur find how much He should travel.", "input_spec": "First line contains a single natural number n (1 ≤ n ≤ 105) — the amount of cities. Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 ≤ xi, yi ≤ n, 0 ≤ wi ≤ 2 × 104). xi and yi are two ends of a road and wi is the length of that road.", "output_spec": "A single integer number, the minimal length of Shapur's travel. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).", "sample_inputs": ["3\n1 2 3\n2 3 4", "3\n1 2 3\n1 3 3"], "sample_outputs": ["7", "9"], "notes": null}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tedges = {};\n\tif (n == 1) {\n\t\tprint(0);\n\t\treturn;\n\t}\n\tedges.add = function (u, v, cost) {\n\t\tif (edges[u] === undefined) {\n\t\t\tedges[u] = [];\n\t\t}\n\t\tedges[u].push({ v: v, cost: cost });\n\t};\n\tfor (var i = 1; i < n; ++i) {\n\t\tvar data = tokenizeIntegers(readline()),\n\t\t\tu = data[0], v = data[1], cost = data[2];\n\t\tedges.add(u, v, cost);\n\t\tedges.add(v, u, cost);\n\t}\n\tvar total = 0, seen = {}, maxPathCost = 0;\n\tfunction dfs(u, pathCost) {\n\t\tseen[u] = true;\n\t\tmaxPathCost = Math.max(maxPathCost, pathCost);\n\t\tvar vs = edges[u];\n\t\tfor (var i = 0; i < vs.length; ++i) {\n\t\t\tvar info = vs[i],\n\t\t\t\tv = info.v, cost = info.cost;\n\t\t\tif (!seen[v]) {\n\t\t\t\ttotal += cost;\n\t\t\t\tdfs(v, pathCost+cost);\n\t\t\t}\n\t\t}\n\t}\n\tdfs(1, 0);\n\t//print(total, maxPathCost);\n\tprint(2*total-maxPathCost);\n}\n\nmain();\n"}], "negative_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar data = tokenizeIntegers(readline()),\n\t\tn = data[0], m = data[1], k = data[2];\n}\n\nmain();\n"}], "src_uid": "a72873b2f845f733c9b898ad81b32d29"} {"nl": {"description": "Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k).For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi ≠ yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.Given n, k and B, you need to determine the lexicographically smallest A.", "input_spec": "The first line contains two space separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.", "output_spec": "Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.", "sample_inputs": ["5 2\n1 2 1 0 0", "4 2\n1 0 0 0"], "sample_outputs": ["4 1 5 2 3", "2 3 1 4"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n let [nk, B] = ipt.split(EOL)\n let [n, k] = nk.split(' ').map(v => parseInt(v))\n B = B.split(' ').map(v => parseInt(v))\n const A = []\n\n for (let i = B.length - 1; i >= 0; i--) {\n let j = 1\n let p = 0\n while (j <= B[i]) {\n if (A[p++] >= i + 1 + k) j++\n }\n A.splice(p, 0, i + 1)\n }\n\n console.log(A.join(' '))\n})"}], "negative_code": [], "src_uid": "3c73d33682dc4548646fd240b6e22471"} {"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 — 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$$$) — 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 — 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 — 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": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = '';\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n const lines = inputString.trim().split(\"\\n\").map(string => string.trim()).filter(Boolean);\r\n\r\n main(lines);\r\n});\r\n\r\nfunction main(lines) {\r\n let index = 0;\r\n let T = Number(lines[index++]);\r\n let shops, friends;\r\n let arr;\r\n\r\n while (T--) {\r\n [shops, friends] = lines[index++].split(' ').map(Number);\r\n arr = new Array(shops);\r\n \r\n for (let i = 0; i < shops; ++i) {\r\n arr[i] = lines[index++].split(' ').map(Number);\r\n }\r\n\r\n solve(shops, friends, arr);\r\n }\r\n}\r\n\r\nfunction solve(shops, friends, arr) { \r\n let [basicFriendMaxKey, basicFriendMinKey] = [0, 1];\r\n let [basicFriendMaxValue, basicFriendMinValue] = [\r\n Math.max(arr[0][0], arr[0][1]),\r\n Math.min(arr[0][0], arr[0][1]),\r\n ];\r\n let curMaxKey, prevMaxKey;\r\n let curMaxValue, prevMaxValue;\r\n\r\n let friendsMap = new Array(friends).fill(0);\r\n\r\n for (let i = 0; i < shops; ++i) {\r\n [curMaxKey, prevMaxKey] = [0, 1];\r\n [curMaxValue, prevMaxValue] = [0, 0];\r\n\r\n for (let j = 0; j < friends; ++j) {\r\n if (arr[i][j] >= curMaxValue) {\r\n prevMaxValue = curMaxValue;\r\n prevMaxKey = curMaxKey;\r\n \r\n curMaxValue = arr[i][j];\r\n curMaxKey = j;\r\n } else if (arr[i][j] >= prevMaxValue) {\r\n prevMaxValue = arr[i][j];\r\n prevMaxKey = j;\r\n }\r\n }\r\n\r\n if (prevMaxValue > basicFriendMinValue) {\r\n basicFriendMinValue = prevMaxValue;\r\n basicFriendMinKey = prevMaxKey;\r\n \r\n \r\n basicFriendMaxValue = curMaxValue;\r\n basicFriendMaxKey = curMaxKey;\r\n }\r\n }\r\n\r\n friendsMap[basicFriendMinKey] = basicFriendMinValue;\r\n friendsMap[basicFriendMaxKey] = basicFriendMaxValue;\r\n\r\n for (let i = 0; i < shops; ++i) { \r\n for (let j = 0; j < friends; ++j) { \r\n if (j === basicFriendMinKey || j === basicFriendMaxKey) {\r\n continue;\r\n }\r\n\r\n friendsMap[j] = Math.max(friendsMap[j], arr[i][j]);\r\n }\r\n }\r\n\r\n console.log(Math.min(...friendsMap));\r\n}"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nlet m;\r\nlet n;\r\nlet p;\r\nfunction can(mid) {\r\n const friends = af(n).fill(0);\r\n const shops = af(m).fill(0);\r\n for (let i = 0; i < m; i++) {\r\n for (let j = 0; j < n; j++) {\r\n if (p[i][j] >= mid) {\r\n friends[j]++;\r\n shops[i]++;\r\n }\r\n }\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (friends[i] == 0) {\r\n return false;\r\n }\r\n }\r\n for (let i = 0; i < m; i++) {\r\n if (shops[i] > 1) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n m = nextInt();\r\n n = nextInt();\r\n p = Array.from({ length: m });\r\n let mx = 0;\r\n for (let i = 0; i < m; i++) {\r\n p[i] = af(n);\r\n for (let j = 0; j < n; j++) {\r\n p[i][j] = nextInt();\r\n mx = Math.max(mx, p[i][j]);\r\n }\r\n }\r\n let lo = 0;\r\n let hi = mx + 1;\r\n let ans = 0;\r\n while (lo < hi) {\r\n let mid = lo + Math.trunc((hi - lo) / 2);\r\n if (!can(mid)) {\r\n hi = mid;\r\n }\r\n else {\r\n lo = mid + 1;\r\n ans = mid;\r\n }\r\n }\r\n printf(\"%d\\n\", ans);\r\n }\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n l++\n const [m, n] = lines[l++].trim().split(' ').map(Number)\n const arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))\n l += m\n output[i] = solve(n, m, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, m, arr) {\n return binarySearch(1, 1e9, x => check(n, m, arr, x))\n}\nfunction binarySearch(l, r, fn) {\n while (l <= r) {\n const m = Math.floor((l + r) / 2)\n if (fn(m)) {\n l = m + 1\n } else {\n r = m - 1\n }\n }\n return r\n}\nfunction check(n, m, arr, min) {\n const map = {}\n let has2 = 0\n for (let i = 0; i < n; i++) {\n let has = 0\n for (let j = 0; j < m; j++) {\n if (arr[j][i] >= min) {\n map[j] = (map[j] || 0) + 1\n has = 1\n if (map[j] > 1) has2 = 1\n }\n }\n if (!has) return false\n }\n return has2\n}\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\trl();\r\n\t\tconst [m, n] = rna();\r\n\t\tconst p = [];\r\n\t\tfor (let i = 0; i < m; i++)\r\n\t\t\tp[i] = rna();\r\n\r\n\t\tconst mxjoy = Array(n).fill(0);\r\n\t\tlet mxsmx = 0;\r\n\t\tfor (let i = 0; i < m; i++) {\r\n\t\t\tlet fmx = 0, smx = 0;\r\n\t\t\tfor (let j = 0; j < n; j++) {\r\n\t\t\t\tmxjoy[j] = Math.max(mxjoy[j], p[i][j]);\r\n\t\t\t\tif (p[i][j] > fmx) {\r\n\t\t\t\t\t[fmx, smx] = [p[i][j], fmx]\r\n\t\t\t\t} else if (p[i][j] > smx) \r\n\t\t\t\t\tsmx = p[i][j];\r\n\t\t\t}\r\n\t\t\tmxsmx = Math.max(mxsmx, smx);\r\n\t\t\t//console.log({mxsmx})\r\n\t\t}\r\n\r\n\t\tconst ans = Math.min(mxsmx, ...mxjoy);\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = '';\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n const lines = inputString.trim().split(\"\\n\").map(string => string.trim()).filter(Boolean);\r\n\r\n console.log(lines);\r\n});"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n console.log(inputString);\r\n});"}], "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$$$) — 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$$$) — 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": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var n = parseInt(readline());\n var arr = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n\n var flag = false;\n arr = arr.sort((a, b) => a - b);\n for (var i = 1; i < arr.length; i++) {\n if (Math.abs(arr[i] - arr[i - 1] == 1) == 1) {\n arr = arr.slice(0, i - 1).concat(arr.slice(i + 1));\n i -= 2;\n flag = true;\n }\n }\n if (arr.length == 0) print(\"Yes\");\n else {\n var odd = arr.filter((val) => val % 2 != 0);\n var even = arr.filter((val) => val % 2 == 0);\n\n if (odd.length % 2 == 0 && even.length % 2 == 0) print(\"Yes\");\n else if (flag) {\n print(\"Yes\");\n } else print(\"NO\");\n }\n}\n"}, {"source_code": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var n = +readline();\n var arr = readNumArray().sort((a, b) => a - b);\n var evens = 0;\n var odds = 0;\n var curr = arr[0];\n var has1diff = false;\n for (var j = 0; j < n; j++) {\n if (arr[j] - curr === 1) {\n has1diff = true;\n }\n curr = arr[j];\n if (arr[j] % 2) {\n odds++;\n } else {\n evens++;\n }\n }\n if (has1diff || odds % 2 === 0) {\n print(\"YES\");\n } else {\n print(\"NO\");\n }\n }\n\n}\n\nmain();\n"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var k = 0; k < t; k++){\n\t\tvar N = nextInt();\n\t\tvar list = nextIntArray();\n\t\tvar odd = [];\n\t\tvar even = [];\n\t\tfor(var i = 0; i < N; i++){\n\t\t\tif(list[i] % 2 == 1){\n\t\t\t\todd.push(list[i]);\n\t\t\t}else{\n\t\t\t\teven.push(list[i]);\n\t\t\t}\n\t\t}\n\t\tif(odd.length % 2 == 0 && even.length % 2 == 0){\n\t\t\toutput[k] = \"YES\";\n\t\t}else{\n\t\t\tvar isOK = false;\n\t\t\tfor(var i = 0; i < odd.length; i++){\n\t\t\t\tfor(var j = 0; j < even.length; j++){\n\t\t\t\t\tif(Math.abs(odd[i] - even[j]) == 1){\n\t\t\t\t\t\tisOK = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(isOK){\n\t\t\t\toutput[k] = \"YES\";\n\t\t\t}else{\n\t\t\t\toutput[k] = \"NO\";\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x)\n const p = [0, 0]\n for (const t of arr) {\n p[t%2]++\n }\n if (p[0]%2 !==0) {\n arr.sort((a, b) => a-b)\n let prev = arr[0]\n for (let i=1;i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n7\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\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\n\nfunction main() {\n\n let cases = parseInt(readline(), 10);\n for (var X = 0; X < cases; X++) {\n readline();\n let force = readline().split(\" \").map(e => parseInt(e));\n const {pow, max, min} = Math;\n\n force.sort((a,b) => a - b);\n\n const odds = force.filter(f => f % 2 === 0);\n const even = force.filter(f => f % 2 === 1);\n\n\n if (odds.length % 2 === 0 && even.length % 2 === 0) {\n console.log('YES');\n } else {\n let follow = false;\n for (let i = 0; i < force.length - 1; i++) {\n const c1 = force[i];\n const c2 = force[i+1];\n if (Math.abs(c1 - c2) === 1) {\n follow = true;\n break;\n }\n }\n if (follow) {\n console.log('YES');\n } else {\n console.log('NO');\n }\n }\n\n\n\n\n\n\n //break;\n //console.log(Math.pow(Math.max(a,b) + Math.max(a,b) , 2))\n }\n\n\n}\n"}], "negative_code": [{"source_code": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var n = parseInt(readline());\n var arr = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n\n var differs = [];\n var reminders = [];\n reminders.push(arr[0] % 2);\n for (var i = 1; i < arr.length; i++) {\n differs.push(Math.abs(arr[i] - arr[i - 1]));\n reminders.push(arr[i] % 2);\n }\n if (differs.includes(1)) print(\"Yes\");\n else {\n var found = false;\n for (var i = 1; i < reminders.length; i++) {\n if (reminders[i] == reminders[i - 1]) {\n print(\"Yes\");\n found = true;\n break;\n }\n }\n if (!found) print(\"No\");\n }\n\n differs = differs.sort((a, b) => a - b);\n print(differs[0]);\n}\n"}, {"source_code": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var n = parseInt(readline());\n var arr = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n\n var differs = [];\n var reminders = [];\n reminders.push(arr[0] % 2);\n for (var i = 1; i < arr.length; i++) {\n differs.push(Math.abs(arr[i] - arr[i - 1]));\n reminders.push(arr[i] % 2);\n }\n if (differs.includes(1)) print(\"Yes\");\n else {\n var found = false;\n for (var i = 1; i < reminders.length; i++) {\n if (reminders[i] == reminders[i - 1]) {\n print(\"Yes\");\n found = true;\n break;\n }\n }\n if (!found) print(\"No\");\n }\n}\n"}, {"source_code": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var n = parseInt(readline());\n var arr = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n\n var differs = [];\n var reminders = [];\n reminders.push(arr[0] % 2);\n for (var i = 1; i < arr.length; i++) {\n differs.push(Math.abs(arr[i] - arr[i - 1]));\n reminders.push(arr[i] % 2);\n }\n reminders = reminders.sort((a, b) => a - b);\n if (differs.includes(1)) print(\"Yes\");\n else {\n var found = false;\n for (var i = 1; i < reminders.length; i++) {\n if (reminders[i] == reminders[i - 1]) {\n print(\"Yes\");\n found = true;\n break;\n }\n }\n if (!found) print(\"No\");\n }\n}\n"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var k = 0; k < t; k++){\n\t\tvar N = nextInt();\n\t\tvar list = nextIntArray();\n\t\tfor(var i = 0; i < list.length; i++){\n\t\t\tif(list[i] == -1){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar ato = list[i] + 1;\n\t\t\tvar mae = list[i] - 1;\n\t\t\tif(list.indexOf(ato) != -1){\n\t\t\t\tlist[i] = -1;\n\t\t\t\tlist[list.indexOf(ato)] = -1;\n\t\t\t}else if(list.indexOf(mae) != -1){\n\t\t\t\tlist[i] = -1;\n\t\t\t\tlist[list.indexOf(mae)] = -1;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < list.length; i++){\n\t\t\tif(list[i] == -1){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(var j = 0; j < list.length; j++){\n\t\t\t\tif(list[j] == -1){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(i != j && (list[i] % 2 == list[j] % 2)){\n\t\t\t\t\tlist[i] = -1;\n\t\t\t\t\tlist[j] = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar isOK = true;\n\t\tfor(var i = 0; i < N; i++){\n\t\t\tif(list[i] != -1){\n\t\t\t\tisOK = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(isOK){\n\t\t\toutput[k] = \"YES\";\n\t\t}else{\n\t\t\toutput[k] = \"NO\";\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var k = 0; k < t; k++){\n\t\tvar N = nextInt();\n\t\tvar list = nextIntArray();\n\t\tif(N % 4 == 2){\n\t\t\tfor(var i = 0; i < list.length; i++){\n\t\t\t\tif(list[i] == -1){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvar ato = list[i] + 1;\n\t\t\t\tvar mae = list[i] - 1;\n\t\t\t\tif(list.indexOf(ato) != -1){\n\t\t\t\t\tlist[i] = -1;\n\t\t\t\t\tlist[list.indexOf(ato)] = -1;\n\t\t\t\t\tbreak;\n\t\t\t\t}else if(list.indexOf(mae) != -1){\n\t\t\t\t\tlist[i] = -1;\n\t\t\t\t\tlist[list.indexOf(mae)] = -1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(var i = 0; i < list.length; i++){\n\t\t\t\tif(list[i] == -1){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor(var j = 0; j < list.length; j++){\n\t\t\t\t\tif(list[j] == -1){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(i != j && (list[i] % 2 == list[j] % 2)){\n\t\t\t\t\t\tlist[i] = -1;\n\t\t\t\t\t\tlist[j] = -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t\tfor(var i = 0; i < list.length; i++){\n\t\t\t\tif(list[i] == -1){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor(var j = 0; j < list.length; j++){\n\t\t\t\t\tif(list[j] == -1){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(i != j && (list[i] % 2 == list[j] % 2)){\n\t\t\t\t\t\tlist[i] = -1;\n\t\t\t\t\t\tlist[j] = -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(var i = 0; i < list.length; i++){\n\t\t\t\tif(list[i] == -1){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvar ato = list[i] + 1;\n\t\t\t\tvar mae = list[i] - 1;\n\t\t\t\tif(list.indexOf(ato) != -1){\n\t\t\t\t\tlist[i] = -1;\n\t\t\t\t\tlist[list.indexOf(ato)] = -1;\n\t\t\t\t}else if(list.indexOf(mae) != -1){\n\t\t\t\t\tlist[i] = -1;\n\t\t\t\t\tlist[list.indexOf(mae)] = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar isOK = true;\n\t\tfor(var i = 0; i < N; i++){\n\t\t\tif(list[i] != -1){\n\t\t\t\tisOK = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(isOK){\n\t\t\toutput[k] = \"YES\";\n\t\t}else{\n\t\t\toutput[k] = \"NO\";\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n7\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\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r x - y);\n\n for(let i=0;i x !== undefined);\n if(!nums.length) {\n console.log('YES');\n } else {\n console.log('NO');\n }\n }\n}"}], "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$$$) — the number of queries. Each of the next $$$T$$$ lines contains one integer $$$\\text{ang}$$$ ($$$1 \\le \\text{ang} < 180$$$) — the angle measured in degrees. ", "output_spec": "For each query print single integer $$$n$$$ ($$$3 \\le n \\le 998244353$$$) — 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": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n let tmp=0, T=0, angles=[];\n\n rl.on('line', (input) => {\n if (tmp==0) {T=Number(input); tmp++;}\n else {\n if (tmp<=T){\n let angle=Number(input); \n angles.push(angle);\n tmp++;}\n }\n if (tmp>T){ rl.close(); therest();}\n return 0;}\n);\n\nlet therest=function() {\n for (let i=0; i {\n // TODO: Log the answer in a database\n console.log(`Thank you for your valuable feedback: ${answer}`);\n \n rl.close();\n });*/"}], "negative_code": [], "src_uid": "d11b56fe172110d5dfafddf880e48f18"} {"nl": {"description": "Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string \"coolmike\", in one move he can transform it into the string \"oolmikec\".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?", "input_spec": "The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.", "output_spec": "Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.", "sample_inputs": ["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"], "sample_outputs": ["5", "2", "0", "-1"], "notes": "NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into \"zwoxz\"."}, "positive_code": [{"source_code": "//@ts-check\n\n/**\n * @param {string} str\n * @param {number} steps\n */\nfunction makeSteps(str, steps) {\n return str.slice(steps) + str.slice(0, steps);\n}\n\n/**\n * @param {string[]} arr\n */\nfunction solve(arr) {\n const len = arr[0].length;\n const $ = arr.map(() => new Map());\n for (let j = 0; j < len; j++) {\n const target = makeSteps(arr[0], j);\n if (!$[0].has(target)) {\n $[0].set(makeSteps(arr[0], j), j);\n }\n }\n for (let i = 1; i < $.length; i++) {\n for (let j = 0; j < len; j++) {\n const target = makeSteps(arr[i], j);\n const currentSteps = $[i].has(target)\n ? $[i].get(target)\n : Number.POSITIVE_INFINITY;\n if ($[i - 1].has(target) || $[i - 1].get(target) === -1) {\n const prevLineSteps = $[i - 1].get(target);\n $[i].set(target, Math.min(currentSteps, prevLineSteps + j));\n } else {\n $[i].set(target, -1);\n }\n }\n }\n return Math.min(...$.pop().values());\n}\n\nfunction* main() {\n const n = parseInt(yield);\n const s = [];\n for (let index = 0; index < n; index++) {\n s.push(yield);\n }\n const r = solve(s);\n console.log(r);\n process.exit(0);\n}\n\nif (!module.parent) {\n (() => {\n const q = main();\n q.next();\n require(\"readline\")\n .createInterface({\n input: process.stdin,\n output: null,\n })\n .on(\"line\", (line) => q.next(line));\n })();\n}\n\nexports.solve = solve;\n"}, {"source_code": "'use strict';\n\nfunction createReadLine() {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n let inputString = '';\n let currentLine = 0;\n\n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n\n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n });\n\n function readline() {\n return inputString[currentLine++];\n }\n\n return readline;\n}\n\nconst readline = createReadLine();\n\nfunction readInts(){\n return readline().split(' ').map((value => Number.parseInt(value)));\n}\n\nfunction readFloats(){\n return readline().split(' ').map((value => Number.parseFloat(value)));\n}\n\nfunction readStr() {\n return readline();\n}\n\nfunction readInt(){\n return Number.parseInt(readline());\n}\n\nfunction readFloat(){\n return Number.parseFloat(readline());\n}\n\n\n\nfunction main() {\n const n = readInt();\n const strs = []\n for (let i = 0; i < n; i ++){\n strs.push(readStr())\n }\n const result = solve(strs);\n console.log(result);\n}\n\nfunction makeStep(str, steps) {\n return str.slice(steps) + str.slice(0, steps);\n}\n\nfunction solve(strs){\n let set = strs.map(() => new Map());\n const firstLine = new Array(strs[0].length);\n firstLine[0] = strs[0]\n for (let j = 1; j < firstLine.length; j++){\n firstLine[j] = makeStep(strs[0], j)\n }\n set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));\n const resultArr = new Array(strs.length).fill(0).map(() => new Array(strs[0].length).fill(0));\n const values = [...set[0].values()];\n resultArr[0] = [...strs[0]].map((val, index) => {\n if(values[index] !== undefined){\n return index;\n }\n return 0\n })\n for (let i = 1; i < set.length; i ++){\n for (let j = 0; j < strs[0].length; j ++){\n const current = makeStep(strs[i], j)\n let value = set[i -1].get(current);\n if(value === undefined) {\n value = -1;\n } else {\n const prev = makeStep(strs[i], j -1);\n const currentValue = set[i].get(current);\n if(currentValue) {\n resultArr[i][j] = currentValue;\n continue;\n }\n if(prev !== current){\n value += j;\n }\n }\n set[i].set(current, value);\n resultArr[i][j] = value;\n }\n }\n return Math.min(...resultArr[strs.length - 1])\n}\n\nmodule.exports.solve = solve;\n"}, {"source_code": "'use strict';\n\nfunction createReadLine() {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n let inputString = '';\n let currentLine = 0;\n\n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n\n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n });\n\n function readline() {\n return inputString[currentLine++];\n }\n\n return readline;\n}\n\nconst readline = createReadLine();\n\nfunction readInts(){\n return readline().split(' ').map((value => Number.parseInt(value)));\n}\n\nfunction readFloats(){\n return readline().split(' ').map((value => Number.parseFloat(value)));\n}\n\nfunction readStr() {\n return readline();\n}\n\nfunction readInt(){\n return Number.parseInt(readline());\n}\n\nfunction readFloat(){\n return Number.parseFloat(readline());\n}\n\n\n\nfunction main() {\n const n = readInt();\n const strs = []\n for (let i = 0; i < n; i ++){\n strs.push(readStr())\n }\n const result = solve(strs);\n console.log(result);\n}\n\nfunction makeStep(str, steps) {\n return str.slice(steps) + str.slice(0, steps);\n}\n\nfunction solve(strs){\n let set = strs.map(() => new Map());\n const firstLine = new Array(strs[0].length);\n firstLine[0] = strs[0]\n for (let j = 1; j < firstLine.length; j++){\n firstLine[j] = makeStep(strs[0], j)\n }\n set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));\n for (let i = 1; i < set.length; i ++){\n for (let j = 0; j < strs[0].length; j ++){\n const current = makeStep(strs[i], j)\n let value = set[i -1].get(current);\n if(value === undefined) {\n value = -1;\n } else {\n const prev = makeStep(strs[i], j -1);\n const currentValue = set[i].get(current);\n if(currentValue) {\n continue;\n }\n if(prev !== current){\n value += j;\n }\n }\n set[i].set(current, value);\n }\n }\n return Math.min(...set[strs.length - 1].values())\n}\n\nmodule.exports.solve = solve;\n"}, {"source_code": "'use strict';\n\nfunction createReadLine() {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n let inputString = '';\n let currentLine = 0;\n\n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n\n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n });\n\n function readline() {\n return inputString[currentLine++];\n }\n\n return readline;\n}\n\nconst readline = createReadLine();\n\nfunction readInts(){\n return readline().split(' ').map((value => Number.parseInt(value)));\n}\n\nfunction readFloats(){\n return readline().split(' ').map((value => Number.parseFloat(value)));\n}\n\nfunction readStr() {\n return readline();\n}\n\nfunction readInt(){\n return Number.parseInt(readline());\n}\n\nfunction readFloat(){\n return Number.parseFloat(readline());\n}\n\n\n\nfunction main() {\n const n = readInt();\n const strs = []\n for (let i = 0; i < n; i ++){\n strs.push(readStr())\n }\n const result = solve(strs);\n console.log(result);\n}\n\nfunction makeStep(str, steps) {\n return str.slice(steps) + str.slice(0, steps);\n}\n\nfunction solve(strs){\n let set = strs.map(() => new Map());\n const firstLine = new Array(strs[0].length);\n firstLine[0] = strs[0]\n for (let j = 1; j < firstLine.length; j++){\n firstLine[j] = makeStep(strs[0], j)\n }\n set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));\n for (let i = 1; i < set.length; i ++){\n for (let j = 0; j < strs[0].length; j ++){\n const current = makeStep(strs[i], j)\n let value = set[i -1].get(current);\n if(value === undefined) {\n return -1;\n } else {\n const prev = makeStep(strs[i], j -1);\n const currentValue = set[i].get(current);\n if(currentValue) {\n continue;\n }\n if(prev !== current){\n value += j;\n }\n }\n set[i].set(current, value);\n }\n }\n return Math.min(...set[strs.length - 1].values())\n}\n\nmodule.exports.solve = solve;\n"}, {"source_code": "var N = readline() | 0;\nvar lines = [];\nfor(var i = 0; i < N; ++i) {\n lines.push(readline());\n}\n\nvar results = lines.map(function (line) {\n return lines.map(function (x) {\n return (x+x).indexOf(line);\n });\n});\n\nif (results[0].indexOf(-1) >= 0) {\n print(-1);\n} else {\n print(results\n .map(function (x) { return x.reduce(function (a, x) { return a + x }, 0); })\n .reduce(function (a, x) { return Math.min(a,x); }, 10000000));\n}\n"}, {"source_code": "var l = [], res = 9999;\nfor (var i = Number(readline()); i > 0; i--) {\n var s = readline(), d = {};\n for (var j = s.length - 1; j >= 0; j--) d[s.substr(j) + s.substr(0, j)] = j;\n l.push(d)\n}\nfor (s in d) {\n var x = 0;\n for (var t of l) x += t.hasOwnProperty(s) ? t[s] : 9999;\n if (x >= 9999) res = -1;\n else if (res > x) res = x;\n}\nprint(res);\n"}, {"source_code": " var n = parseInt(readline());\n var s = [];\n String.prototype.rotate = function(x) {\n var a = x % this.length;\n var b;\n if(a > 0){\n b = this.length - a;\n } else {\n b = -a;\n }\n var c = this.substr(b, this.length);\n var d = this.substr(0, b);\n return c + d;\n };\n for(var i = 0; i < n; i += 1) {\n s[i] = readline();\n }\n var r = [];\n var t = [];\n var flag = true;\n var len = s[0].length;\n for(var i = 0; flag && i < n; i += 1) {\n var ok0 = false;\n var ok1 = false;\n for(var j = 0; j <= len; j += 1) {\n if(s[i].rotate(-j) == s[i] && j !== 0) {\n if(ok1 === false) {\n t[i] = j;\n ok1 = true;\n }\n }\n if(s[i].rotate(-j) == s[0]) {\n if(ok0 === false) {\n r[i] = j;\n ok0 = true;\n }\n }\n }\n if(ok0 == false) {\n flag = false;\n }\n }\n if(flag === false) {\n print(-1);\n } else {\n var res = Infinity;\n for(var i = 0; i < len; i += 1) {\n var tmp = 0;\n for(var j = 0; j < n; j += 1) {\n tmp += (r[j] + i) % t[j]; \n }\n res = Math.min(res, tmp);\n }\n print(res);\n }\n"}], "negative_code": [{"source_code": "//@ts-check\n\n/**\n * @param {string} str\n * @param {number} steps\n */\nfunction makeSteps(str, steps) {\n return str.slice(steps) + str.slice(0, steps);\n}\n\n/**\n * @param {string[]} arr\n */\nfunction solve(arr) {\n const len = arr[0].length;\n const $ = arr.map(() => new Map());\n for (let j = 0; j < len; j++) {\n $[0].set(makeSteps(arr[0], j), j);\n }\n for (let i = 1; i < $.length; i++) {\n for (let j = 0; j < len; j++) {\n const target = makeSteps(arr[i], j);\n if ($[i - 1].has(target) || $[i - 1].get(target) === -1) {\n const prevLineSteps = $[i - 1].get(target);\n $[i].set(target, prevLineSteps + j);\n } else {\n $[i].set(target, -1);\n }\n }\n }\n return Math.min(...$.pop().values());\n}\n\nfunction* main() {\n const n = parseInt(yield);\n const s = [];\n for (let index = 0; index < n; index++) {\n s.push(yield);\n }\n const r = solve(s);\n console.log(r);\n process.exit(0);\n}\n\nif (!module.parent) {\n (() => {\n const q = main();\n q.next();\n require(\"readline\")\n .createInterface({\n input: process.stdin,\n output: null,\n })\n .on(\"line\", (line) => q.next(line));\n })();\n}\n\nexports.solve = solve;\n"}, {"source_code": "'use strict';\n\nfunction createReadLine() {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n let inputString = '';\n let currentLine = 0;\n\n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n\n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n });\n\n function readline() {\n return inputString[currentLine++];\n }\n\n return readline;\n}\n\nconst readline = createReadLine();\n\nfunction readInts(){\n return readline().split(' ').map((value => Number.parseInt(value)));\n}\n\nfunction readFloats(){\n return readline().split(' ').map((value => Number.parseFloat(value)));\n}\n\nfunction readStr() {\n return readline();\n}\n\nfunction readInt(){\n return Number.parseInt(readline());\n}\n\nfunction readFloat(){\n return Number.parseFloat(readline());\n}\n\n\n\nfunction main() {\n const n = readInt();\n const strs = []\n for (let i = 0; i < n; i ++){\n strs.push(readStr())\n }\n const result = solve(strs);\n console.log(result);\n}\n\nfunction makeStep(str, steps) {\n return str.slice(steps) + str.slice(0, steps);\n}\n\nfunction solve(strs){\n let set = strs.map(() => new Map());\n const firstLine = new Array(strs[0].length);\n firstLine[0] = strs[0]\n for (let j = 1; j < firstLine.length; j++){\n firstLine[j] = makeStep(strs[0], j)\n }\n set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));\n const resultArr = new Array(strs.length).fill(0).map(() => new Array(strs[0].length).fill(0));\n const values = [...set[0].values()];\n resultArr[0] = [...strs[0]].map((_, index) => {\n if(values[index] !== undefined){\n return index;\n }\n return Math.max(...values)\n })\n for (let i = 1; i < set.length; i ++){\n for (let j = 0; j < strs[0].length; j ++){\n const current = makeStep(strs[i], j)\n let value = set[i -1].get(current);\n if(value === undefined) {\n value = -1;\n } else {\n const prev = makeStep(strs[i], j -1);\n if(prev !== current){\n value += j;\n }\n }\n set[i].set(current, value);\n resultArr[i][j] = value;\n }\n }\n return Math.min(...resultArr[strs.length - 1])\n}\n\nmodule.exports.solve = solve;\n"}, {"source_code": "\n var n = parseInt(readline());\n var s = [];\n String.prototype.rotate = function(x) {\n var a = x % this.length;\n var b;\n if(a > 0){\n b = this.length - a;\n } else {\n b = -a;\n }\n var c = this.substr(b, this.length);\n var d = this.substr(0, b);\n return c + d;\n };\n for(var i = 0; i < n; i += 1) {\n s[i] = readline();\n }\n var r = [];\n r[0] = 0;\n var flag = true;\n var len = s[0].length;\n for(var i = 1; flag && i < n; i += 1) {\n var ok = false;\n for(var j = 0; j < len; j += 1) {\n if(s[i].rotate(-j) == s[0]) {\n r[i] = j;\n ok = true;\n }\n }\n if(ok == false) {\n flag = false;\n }\n }\n if(flag === false) {\n print(-1);\n } else {\n var res = Infinity;\n for(var i = 0; i < len; i += 1) {\n var tmp = 0;\n for(var j = 0; j < n; j += 1) {\n tmp += (r[j] + i) % len; \n }\n res = Math.min(res, tmp);\n }\n print(res);\n }"}, {"source_code": " var n = parseInt(readline());\n var s = [];\n String.prototype.rotate = function(x) {\n var a = x % this.length;\n var b;\n if(a > 0){\n b = this.length - a;\n } else {\n b = -a;\n }\n var c = this.substr(b, this.length);\n var d = this.substr(0, b);\n return c + d;\n };\n for(var i = 0; i < n; i += 1) {\n s[i] = readline();\n }\n var r = [];\n r[0] = 0;\n var flag = true;\n var len = s[0].length;\n for(var i = 1; flag && i < n; i += 1) {\n var ok = false;\n for(var j = 0; j < len; j += 1) {\n if(s[i].rotate(-j) == s[0]) {\n r[i] = j;\n ok = true;\n break;\n }\n }\n if(ok == false) {\n flag = false;\n }\n }\n if(flag === false) {\n print(-1);\n } else {\n var res = Infinity;\n for(var i = 0; i < len; i += 1) {\n var tmp = 0;\n for(var j = 0; j < n; j += 1) {\n tmp += (r[j] + i) % len; \n }\n res = Math.min(res, tmp);\n }\n print(res);\n }\n"}], "src_uid": "a3a7515219ebb0154218ee3520e20d75"} {"nl": {"description": "You are given an array a1, a2, ..., an 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 ≤ k ≤ n ≤  105) — 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,  a2,  ...,  an ( - 109  ≤  ai ≤  109).", "output_spec": "Print single integer — 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,  r] (l ≤ r) of array a is the sequence al,  al + 1,  ...,  ar.Splitting of array a of n elements into k subsegments [l1, r1], [l2, r2], ..., [lk, rk] (l1 = 1, rk = n, li = ri - 1 + 1 for all i > 1) is k sequences (al1, ..., ar1), ..., (alk, ..., ark).In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. 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, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5."}, "positive_code": [{"source_code": "'use strict'\n// \n// http://codeforces.com/contest/872/problem/A\n\nconst input = readline().split(' ').map(x => parseInt(x));\nconst arr = readline().split(' ').map(x => parseInt(x));\n\n// const print = console.log;\n// const line0 = \"5 2\";\n// const line1 = \"1 2 3 4 5\";\n\n// const input = line0.split(' ').map(x => parseInt(x));\n// const arr = line1.split(' ').map(x => parseInt(x));\n\nconst splits = input[1];\n\nfunction maxMin(arr, splits) {\n if (splits === 1) {\n return Math.min(...arr);\n }\n if (splits > 2) {\n return Math.max(...arr);\n }\n\n const len = arr.length;\n\n const minLeft = [arr[0]];\n const minRight = [];\n minRight[len-1] = arr[len-1];\n\n for (let i = 1; i < len; i++) {\n minLeft[i] = Math.min(minLeft[i-1], arr[i]);\n minRight[len-1-i] = Math.min(minRight[len-i], arr[len-1-i]);\n }\n\n let result = arr[0];\n\n for (let i = 0; i < len-1; i++) {\n if (minLeft[i] > result) {\n result = minLeft[i];\n }\n if (minRight[i+1] > result) {\n result = minRight[i+1];\n }\n }\n return result;\n}\n\nprint(maxMin(arr, splits));"}], "negative_code": [], "src_uid": "ec1a29826209a0820e8183cccb2d2f01"} {"nl": {"description": "You are given three strings $$$s$$$, $$$t$$$ and $$$p$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from $$$p$$$, erase it from $$$p$$$ and insert it into string $$$s$$$ (you may insert this character anywhere you want: in the beginning of $$$s$$$, in the end or between any two consecutive characters). For example, if $$$p$$$ is aba, and $$$s$$$ is de, then the following outcomes are possible (the character we erase from $$$p$$$ and insert into $$$s$$$ is highlighted): aba $$$\\rightarrow$$$ ba, de $$$\\rightarrow$$$ ade; aba $$$\\rightarrow$$$ ba, de $$$\\rightarrow$$$ dae; aba $$$\\rightarrow$$$ ba, de $$$\\rightarrow$$$ dea; aba $$$\\rightarrow$$$ aa, de $$$\\rightarrow$$$ bde; aba $$$\\rightarrow$$$ aa, de $$$\\rightarrow$$$ dbe; aba $$$\\rightarrow$$$ aa, de $$$\\rightarrow$$$ deb; aba $$$\\rightarrow$$$ ab, de $$$\\rightarrow$$$ ade; aba $$$\\rightarrow$$$ ab, de $$$\\rightarrow$$$ dae; aba $$$\\rightarrow$$$ ab, de $$$\\rightarrow$$$ dea; Your goal is to perform several (maybe zero) operations so that $$$s$$$ becomes equal to $$$t$$$. Please determine whether it is possible.Note that you have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$) — the number of queries. Each query is represented by three 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| \\le 100$$$) consisting of lowercase Latin letters. The third line of each query contains the string $$$p$$$ ($$$1 \\le |p| \\le 100$$$) 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": ["4\nab\nacxb\ncax\na\naaaa\naaabbcc\na\naaaa\naabbcc\nab\nbaaa\naaaaa"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first test case there is the following sequence of operation: $$$s = $$$ ab, $$$t = $$$ acxb, $$$p = $$$ cax; $$$s = $$$ acb, $$$t = $$$ acxb, $$$p = $$$ ax; $$$s = $$$ acxb, $$$t = $$$ acxb, $$$p = $$$ a. In the second test case there is the following sequence of operation: $$$s = $$$ a, $$$t = $$$ aaaa, $$$p = $$$ aaabbcc; $$$s = $$$ aa, $$$t = $$$ aaaa, $$$p = $$$ aabbcc; $$$s = $$$ aaa, $$$t = $$$ aaaa, $$$p = $$$ abbcc; $$$s = $$$ aaaa, $$$t = $$$ aaaa, $$$p = $$$ bbcc. "}, "positive_code": [{"source_code": "\"use strict\";\n\nvar foo = function(s1, s2) {\n var f = [];\n for (var i = 0, j = 0; j < s2.length; ++j) {\n if (i < s1.length && s1[i] === s2[j]) {\n ++i;\n } else {\n f.push(s2[j]);\n }\n }\n \n return [i === s1.length, f];\n};\n\nvar main = function() {\n var q = +rd();\n loop:while (q-->0) {\n var s = rd().split('');\n var t = rd().split('');\n var p = rd().split('');\n \n var f1 = foo(s, t);\n if (f1[0]) {\n var f2 = foo(f1[1].sort(), p.sort());\n if (f2[0]) {\n pr('YES');\n continue loop;\n }\n }\n \n pr('NO');\n }\n};\n \nvar rd = readline;\nvar wr = write;\nvar pr = print;\nvar rdAr = () => rd().split(' ').map(v => +v);\nvar prAr = (a) => pr(a.join(' '));\nvar cmpLt = (a, b) => a - b;\nvar cmpGt = (a, b) => b - a;\n \nmain();"}, {"source_code": "const y = \"YES\";\nconst n = \"NO\";\nfunction solve(){\n var s = readline();\n var t = readline();\n var p = readline();\n if(s.length > t.length){\n print(n);\n return;\n }\n var jt = 0;\n var was = new Array(t.length);\n was.fill(0, 0, t.length);\n var buff = new Array(p.length);\n buff.fill(0, 0, p.length);\n for(var i = 0;i < t.length;i++){\n if(s[jt] == t[i]){\n was[i] = 1;\n jt++;\n if(jt == s.length){\n break;\n }\n }\n }\n if(jt != s.length){\n print(n);\n return;\n }\n for(var i = 0;i < t.length;i++){\n if(!was[i]){\n var can = 0;\n for(var j = 0;j < p.length;j++){\n if(!buff[j] && p[j] == t[i]){\n buff[j] = 1;\n can = 1;\n break;\n }\n }\n if(!can){\n print(n);\n return;\n }\n }\n }\n print(y);\n return;\n}\n\nvar t = Number(readline());\nwhile(t--){\n solve();\n}"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n\tterminal: false\n});\n\nvar q, s, t, p;\n\nrl.on(\"line\", (line) => {\n\tif (q == null) q = parseInt(line);\n\telse if (s == null) s = line;\n\telse if (t == null) t = line;\n\telse if (p == null) {\n\t\tp = line;\n\t\t// begin to solve\n\t\tvar mp = {};\n\t\tvar len1 = s.length;\n\t\tvar len2 = t.length;\n\t\tvar len3 = p.length;\n\t\tfor (var i = 0; i < len3; i ++) {\n\t\t\tif (! mp[ p[i] ]) mp[ p[i] ] = 1;\n\t\t\telse mp[ p[i] ] ++;\n\t\t}\n\t\tvar flag = true;\n\t\tvar j = 0;\n\t\tfor (var i = 0; i < len2; i ++) {\n\t\t\tif (j < len1 && s[j] == t[i]) j ++;\n\t\t\telse if (mp[ t[i] ]) mp[ t[i] ] --;\n\t\t\telse {\n\t\t\t\tflag = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (j < len1) flag = false;\n\t\tconsole.log( flag ? \"YES\" : \"NO\" );\n\t\t// end of solve\n\t\ts = t = p = null;\n\t\tq --;\n\t\tif (q == 0)\n\t\t\trl.close();\n\t} \n});"}], "negative_code": [{"source_code": "\"use strict\";\n\nvar foo = function(s1, s2) {\n var f = [];\n for (var i = 0, j = 0; j < s2.length; ++j) {\n if (i < s1.length && s1[i] === s2[j]) {\n ++i;\n } else {\n f.push(s2[j]);\n }\n }\n \n return [i === s1.length, f];\n};\n\nvar main = function() {\n var q = +rd();\n loop:while (q-->0) {\n var s = rd().split('');\n var t = rd().split('');\n var p = rd().split('');\n \n var f1 = foo(s, t);\n if (f1[0]) {\n //pr(f1[1]);\n var f2 = foo(f1[1], p);\n if (f2[0]) {\n pr('YES');\n continue loop;\n }\n }\n \n pr('NO');\n }\n};\n \nvar rd = readline;\nvar wr = write;\nvar pr = print;\nvar rdAr = () => rd().split(' ').map(v => +v);\nvar prAr = (a) => pr(a.join(' '));\nvar cmpLt = (a, b) => a - b;\nvar cmpGt = (a, b) => b - a;\n \nmain();"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n\tterminal: false\n});\n\nvar q, s, t, p;\n\nrl.on(\"line\", (line) => {\n\tif (q == null) q = parseInt(line);\n\telse if (s == null) s = line;\n\telse if (t == null) t = line;\n\telse if (p == null) {\n\t\tp = line;\n\t\t// begin to solve\n\t\tvar mp = {};\n\t\tvar len1 = s.length;\n\t\tvar len2 = t.length;\n\t\tvar len3 = p.length;\n\t\tfor (var i = 0; i < len3; i ++) {\n\t\t\tif (! mp[ p[i] ]) mp[ p[i] ] = 1;\n\t\t\telse mp[ p[i] ] ++;\n\t\t}\n\t\tvar flag = true;\n\t\tvar j = 0;\n\t\tfor (var i = 0; i < len2; i ++) {\n\t\t\tif (j < len1 && s[j] == t[i]) j ++;\n\t\t\telse if (mp[ t[i] ]) mp[ t[i] ] --;\n\t\t\telse {\n\t\t\t\tflag = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconsole.log( flag ? \"YES\" : \"NO\" );\n\t\t// end of solve\n\t\ts = t = p = null;\n\t\tq --;\n\t\tif (q == 0)\n\t\t\trl.close();\n\t} \n});"}], "src_uid": "a27ad7c21cd6402bfd082da4f6c7ab9d"} {"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 × n 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 ≤ n ≤ 100) — 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, 2) and (1, 3) (3, 1) and (3, 3) Pieces that share the same column are: (2, 1) and (3, 1) (1, 3) and (3, 3) "}, "positive_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nconst t = {0: 0, 1: 0, 2: 1};\nconst matrix = []\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n const n = +d;\n for (let i = 3; i <= n; i++) {\n t[i] = t[i - 1] + i - 1;\n }\n return;\n }\n\n matrix.push([...d]);\n\n c++;\n});\n\nrl.on('close', () => {\n let ans = 0;\n\n for (let i = 0; i < matrix.length; i++) {\n let countX = 0;\n let countY = 0;\n\n for (let j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] === 'C') {\n countX++;\n }\n\n if (matrix[j][i] === 'C') {\n countY++;\n }\n }\n\n ans += t[countX];\n ans += t[countY];\n }\n\n console.log(ans);\n});\n"}, {"source_code": "function rda(){ return readline().split(\" \").map(Number); };\nfunction rdn(){ return +readline(); };\n\nvar cnt = [];\nfor(var i = 0, s = 0; i <= 100; i++){\n s += i;\n cnt[i] = s;\n}\n\nvar n = rdn();\n\nvar ans = 0;\nvar cake = [];\nfor(var i = 0; i < n; i++){\n var line = readline();\n cake.push(line);\n var c = 0;\n for(var j = 0; j < n; j++){\n if(line[j] == \"C\") c++;\n }\n\n ans += (cnt[c-1] == undefined) ? 0 : cnt[c-1];\n}\n\nfor(var j = 0; j < n; j++){\n var c = 0;\n for(var i = 0; i < n; i++){\n if(cake[i][j] == \"C\") c++;\n }\n\n ans += (cnt[c-1] == undefined) ? 0 : cnt[c-1];\n}\n\nwrite(ans);\n\n"}, {"source_code": "var n = +readline();\nvar arr = [];\nfor(var i=0;i 1) {\n\t\t\tanswer += nCakes * (nCakes - 1) / 2; \n\t\t}\n\t\t\n\t\tnCakes = cakesInCol[i];\n\t\tif (nCakes > 1) {\n\t\t\tanswer += nCakes * (nCakes - 1) / 2; \n\t\t}\n\t}\n\tprint(answer);\n}\n\nmain();"}, {"source_code": "/* TEST CASE\ninput\n3\n.CC\nC..\nC.C\noutput\n4\ninput\n4\nCC..\nC..C\n.CC.\n.CC.\noutput\n9\n */\nfunction main() {\n\tvar n = parseInt(readline());\n\tvar answer = 0;\n\tvar cakesInRow = []\n\tvar cakesInCol = []\n\tvar i, j;\n\tfor (i = n; i >= 0; i--) {\n\t\tcakesInRow[i] = 0;\n\t\tcakesInCol[i] = 0;\n\t}\n\n\tfor (i = 0; i < n; i++) {\n\t\tvar s = readline();\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tif (s.charAt(j) == 'C') {\n\t\t\t\tcakesInRow[i]++;\n\t\t\t\tcakesInCol[j]++;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (i = 0; i < n; i++) {\n\t\tvar nCakes = cakesInRow[i];\n\t\tif (nCakes > 1) {\n\t\t\tanswer += nCakes * (nCakes - 1) / 2; \n\t\t}\n\t\t\n\t\tnCakes = cakesInCol[i];\n\t\tif (nCakes > 1) {\n\t\t\tanswer += nCakes * (nCakes - 1) / 2; \n\t\t}\n\t}\n\tprint(answer);\n}\n\nmain();"}, {"source_code": "'use strict';\n\n\nconst n = Number(readline());\nlet cake = [];\nlet count = 0;\n\nfor (let i = 0; i < n; i++) {\n let line = readline().split('');\n count += calc(line.filter((c) => c === 'C').length); \n cake.push(line); \n}\n\nfor (let i = 0; i < n; i++) {\n let _line = [];\n for (let j = 0; j < n; j++) {\n _line.push(cake[j][i])\n }\n count += calc(_line.filter((c) => c === 'C').length);\n}\n\nprint(count)\n\n\nfunction calc(n) {\n return n * (n - 1) / 2;\n}\n"}, {"source_code": "var n = Number(readline());\nvar tab = new Array(n);\nfor (var i = 0; i < n; ++i) {\n tab[i] = readline();\n}\n\nvar sum = 0;\nfor (var i = 0; i < n; ++i) {\n var num = 0;\n for (var j = 0; j < n; ++j) {\n if (tab[i][j] === \"C\") {\n ++num;\n }\n }\n sum += num * (num - 1) / 2;\n}\nfor (var i = 0; i < n; ++i) {\n var num = 0;\n for (var j = 0; j < n; ++j) {\n if (tab[j][i] === \"C\") {\n ++num;\n }\n }\n sum += num * (num - 1) / 2;\n}\n\n\nprint(sum);"}, {"source_code": "var readInt = () => parseInt(readline())\nvar readIntArray = () => readline().split(' ').forEach(item => parseInt(item))\nvar fact = n => n > 0 ? n*fact(n-1) : 1;\n\nvar N = readInt()\nvar cake = []\nfor (var i = 0; i < N; i++) {\n cake.push(readline())\n}\n\nvar ans = 0\ncake.forEach(function(s,i) {\n var n = Array.prototype.filter.call(s, c => c === 'C').length\n if (n > 1)\n ans+=fact(n)/(2*fact(n-2))\n \n n = cake.map(s => s[i]).filter(c => c ==='C').length\n if (n > 1)\n ans+=fact(n)/(2*fact(n-2))\n})\nprint(ans)"}], "negative_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nconst t = {1: 0, 2: 1};\nconst matrix = []\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n const n = +d;\n for (let i = 3; i <= n; i++) {\n t[i] = t[i - 1] + i - 1;\n }\n return;\n }\n\n matrix.push([...d]);\n\n c++;\n});\n\nrl.on('close', () => {\n let ans = 0;\n\n for (let i = 0; i < matrix.length; i++) {\n let countX = 0;\n let countY = 0;\n\n for (let j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] === 'C') {\n countX++;\n }\n\n if (matrix[j][i] === 'C') {\n countY++;\n }\n }\n\n ans += t[countX];\n ans += t[countY];\n }\n\n console.log(ans);\n});\n"}, {"source_code": "function rda(){ return readline().split(\" \").map(Number); };\nfunction rdn(){ return +readline(); };\n\nvar cnt = [];\nfor(var i = 0, s = 0; i <= 100; i++){\n s += i;\n cnt[i] = s;\n}\n\nvar n = rdn();\n\nvar ans = 0;\nvar cake = [];\nfor(var i = 0; i < n; i++){\n var line = readline();\n cake.push(line);\n var c = 0;\n for(var j = 0; j < n; j++){\n if(line[j] == \"C\") c++;\n }\n\n ans += cnt[c-1];\n}\n\nfor(var j = 0; j < n; j++){\n var c = 0;\n for(var i = 0; i < n; i++){\n if(cake[i][j] == \"C\") c++;\n }\n\n ans += (cnt[c-1] == undefined) ? 0 : cnt[c-1];\n}\n\nwrite(ans);\n\n"}, {"source_code": "function rda(){ return readline().split(\" \").map(Number); };\nfunction rdn(){ return +readline(); };\n\nvar cnt = [];\nfor(var i = 0, s = 0; i <= 100; i++){\n s += i;\n cnt[i] = s;\n}\n\nvar n = rdn();\n\nvar ans = 0;\nvar cake = [];\nfor(var i = 0; i < n; i++){\n var line = readline();\n cake.push(line);\n var c = 0;\n for(var j = 0; j < n; j++){\n if(line[j] == \"C\") c++;\n }\n\n ans += cnt[c-1];\n}\n\nfor(var j = 0; j < n; j++){\n var c = 0;\n for(var i = 0; i < n; i++){\n if(cake[i][j] == \"C\") c++;\n }\n\n ans += cnt[c-1];\n}\n\nwrite(ans);\n\n"}], "src_uid": "7749f37aa9bf88a00013557e14342952"} {"nl": {"description": "There are $$$n$$$ districts in the town, the $$$i$$$-th district belongs to the $$$a_i$$$-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build $$$n-1$$$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two districts belonging to the same gang are connected directly with a road, this gang will revolt.You don't want this so your task is to build $$$n-1$$$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build $$$n-1$$$ roads to satisfy all the conditions.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$) — 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 5000$$$) — the number of districts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the gang the $$$i$$$-th district belongs to. It is guaranteed that the sum of $$$n$$$ does not exceed $$$5000$$$ ($$$\\sum n \\le 5000$$$).", "output_spec": "For each test case, print: NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement. YES on the first line and $$$n-1$$$ roads on the next $$$n-1$$$ lines. Each road should be presented as a pair of integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le n; x_i \\ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are two districts the $$$i$$$-th road connects. For each road $$$i$$$, the condition $$$a[x_i] \\ne a[y_i]$$$ should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).", "sample_inputs": ["4\n5\n1 2 2 1 3\n3\n1 1 1\n4\n1 1000 101 1000\n4\n1 2 3 4"], "sample_outputs": ["YES\n1 3\n3 5\n5 4\n1 2\nNO\nYES\n1 2\n2 3\n3 4\nYES\n1 2\n1 3\n1 4"], "notes": null}, "positive_code": [{"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nconst print = console.log\nconst lines = []\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nfunction query(arr){\n let set = new Set(arr);\n if (set.size==1)\n return print('NO');\n print('YES');\n let left = [], last;\n for (let i=1; i+a);\n query(arr);\n }\n}\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet lineNum = 0;\nlet countOfData = null;\nlet data = [];\nreadline.on('line', line => {\n lineNum++;\n if(lineNum === 1) {\n countOfData = +line * 2;\n return;\n }\n\n data.push(line);\n \n if(lineNum - 1 === countOfData) {\n goToSolution(data);\n }\n \n});\n\nfunction goToSolution(data) { \n data.forEach((districts, i) => {\n if(i % 2 !== 0) {\n \n districts = districts.split(' ');\n const map = districts.reduce((acc, band, i) => {\n (band in acc) ?\n acc[band].push(i + 1) :\n acc[band] = [i + 1];\n return acc;\n }, {});\n\n const bands = Object.keys(map);\n if(bands.length > 1) {\n console.log('YES');\n for(let i = 0; i < bands.length; i++) {\n if(bands.length - 1 !== i) console.log(`${map[bands[i]][0]} ${map[bands[i + 1]][0]}`);\n\n if(i > 0) {\n for(let j = 1; j < map[bands[i - 1]].length; j++) {\n console.log(`${map[bands[i]][0]} ${map[bands[i - 1]][j]}`)\n }\n }\n\n if(bands.length - 1 === i) {\n for(let j = 1; j < map[bands[i]].length; j++) {\n console.log(`${map[bands[i - 1]][map[bands[i - 1]].length - 1]} ${map[bands[i]][j]}`)\n }\n }\n \n }\n } else {\n console.log('NO');\n }\n }\n })\n}\n\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n const arr = readLine().split(\" \").map(Number);\n const map = new Map();\n\n for (let i = 0; i < len; i++) {\n const num = arr[i];\n if (map.has(num)) {\n map.set(num, [...map.get(num), i + 1]);\n } else {\n map.set(num, [i + 1]);\n }\n }\n\n if (map.size === 1) console.log(\"NO\");\n else {\n console.log(\"YES\");\n const values = [...map.values()];\n const [firstRow, secondRow] = [values[0], values[1]];\n for (let row = 1; row < values.length; row++) {\n for (let col = 0; col < values[row].length; col++) {\n console.log(`${firstRow[0]} ${values[row][col]}`);\n }\n }\n for (let col = 1; col < firstRow.length; col++) {\n console.log(`${secondRow[0]} ${firstRow[col]}`);\n }\n }\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = [];\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = nextInt();\n\t\tvar tmp = nextIntArray();\n\t\tvar isOK = false;\n\t\tvar list = new Array(N);\n\t\tvar uf = unionFind(N);\n\t\tfor(var j = 0; j < N; j++){\n\t\t\tlist[j] = {\n\t\t\t\tno : j,\n\t\t\t\tG : tmp[j],\n\t\t\t\tchild : new Set()\n\t\t\t}\n\t\t}\n\t\tvar connect = new Set();\n\t\tfor(var j = 0; j < N - 1; j++){\n\t\t\tfor(var k = j + 1; k < N; k++){\n\t\t\t\tif(list[j].child.has(list[k].no) || list[k].child.has(list[j].no)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(list[j].G != list[k].G && !uf.isSame(j, k)){\n\t\t\t\t\tisOK = true;\n\t\t\t\t\tlist[j].child.add(list[k].no);\n\t\t\t\t\tlist[k].child.add(list[j].no);\n\t\t\t\t\tconnect.add((j + 1) + \":\" + (k + 1));\n\t\t\t\t\tuf.doUnion(j, k);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(isOK){\n\t\t\toutput.push(\"YES\");\n\t\t\tvar keys = Array.from(connect);\n\t\t\tfor(var j = 0; j < keys.length; j++){\n\t\t\t\toutput.push(keys[j].split(\":\").join(\" \"));\n\t\t\t}\n\t\t}else{\n\t\t\toutput.push(\"NO\");\n\t\t}\n\t}\n\tmyout(myconv(output, 9));\n}\nfunction unionFind(n){\n var uf = {\n //全てのインデックスは「-X(親、絶対値はグループの大きさ)」「自分が属する親(≒根)」のいずれかを持つ。\n //最初はみんなグループの大きさ1の親\n \"list\" : new Array(n).fill(-1),\n \n //同じ親を持つか\n \"isSame\" : function(mae, ato){\n return this.getRootIndex(mae) == this.getRootIndex(ato);\n },\n //自身の親インデックスをたどって根っこに着く\n //親にたどり終えたら子に帰っていくついでに、子たちに「共通の親を持っている」ことを知らせる\n \"getRootIndex\" : function(index){\n if(this.list[index] < 0){\n return index;\n }else{\n this.list[index] = this.getRootIndex(this.list[index]);\n return this.list[index];\n }\n },\n //異なる親同士のまとまりを一つにする(同じ親ならスルー)\n //小さいグループの親が大きいグループの親の直下に着く\n //グループの大きさも更新する\n \"doUnion\" : function(mae, ato){\n var maeRoot = this.getRootIndex(mae);\n var atoRoot = this.getRootIndex(ato);\n if(!this.isSame(maeRoot, atoRoot)){\n if(maeRoot >= atoRoot){\n this.list[maeRoot] += this.list[atoRoot];\n this.list[atoRoot] = maeRoot;\n }else{\n this.list[atoRoot] += this.list[maeRoot];\n this.list[maeRoot] = atoRoot;\n }\n }\n },\n //「-X(親、絶対値はグループの大きさ)」\n //なので、インデックスを指定→親を知る→親の持つグループの大きさがわかる。\n //ただしマイナス値なので、掛け算して返す。\n \"getSize\" : function(index){\n return -this.list[this.getRootIndex(index)];\n }\n }\n return uf;\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n})\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n})\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 2;\n let i = 1;\n while (i <= testCases) {\n // let a = data[i].trim();\n // const n = data[i] * 1;\n // const k = a[1];\n const s = data[i + 1].trim().split(' ').map(Number);\n // s.sort((a, b) => b - a);\n let idx = 0;\n let max = 0;\n let obj = {};\n \n for (let j = 0; j < s.length; j += 1) {\n if (obj[s[j]]) obj[s[j]].push(j);\n else obj[s[j]] = [j];\n // if (s[j] > max) {\n // max = s[j];\n // idx = j;\n // }\n }\n \n let arr = Object.values(obj);\n // console.log(arr);\n\n if (arr.length < 2) console.log('NO');\n else {\n console.log('YES');\n for (let j = 1; j < arr.length; j += 1) {\n for (let k = 0; k < arr[j].length; k += 1) {\n console.log(arr[0][0] + 1 + ' ' + (arr[j][k] + 1));\n }\n }\n for (let j = 1; j < arr[0].length; j += 1) {\n console.log(arr[1][0] + 1 + ' ' + (arr[0][j] + 1));\n }\n }\n \n i += 2;\n }\n}"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){return Math.max(...this)},Array.prototype.min=function(){return Math.min(...this)},Array.prototype.sum=function(){let t=0;for(let e=0;e{if(a)return s=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),void(o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()&&console.log(\"✅ AC!\"));process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{u+=t})),process.stdin.on(\"end\",(e=>{s=u.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return s[i++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function d(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt==r)).length==t)return void o.default.puts(\"NO\");o.default.puts(\"YES\");let n={};for(let r=0;r{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n districtConnections();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction districtConnections(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let a = ti(readline().split(' '));\n\n let count = 0;\n let map = new Array(1000000005);\n let x = [];\n for(let i = 0; i < n; i++){\n if(map[a[i]] === undefined){\n count++;\n map[a[i]] = i+1;\n x.push(a[i]);\n }\n\n if(count >= 2)\n break;\n }\n\n if(count < 2){\n console.log('NO');\n continue;\n }\n\n console.log('YES');\n let visited = new Array(n+1);\n\n for(let i = 1; i <= n; i++){\n if(a[i-1] !== x[0]){\n if(!(visited[i] && visited[map[x[0]]])){\n console.log(i, map[x[0]]);\n visited[i] = true;\n visited[map[x[0]]] = true;\n }\n }else{\n if(!(visited[i] && visited[map[x[1]]])){\n console.log(i, map[x[1]]);\n visited[i] = true;\n visited[map[x[1]]] = true;\n }\n }\n }\n }\n}"}], "negative_code": [{"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = [];\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = nextInt();\n\t\tvar tmp = nextIntArray();\n\t\tvar isOK = false;\n\t\tvar list = new Array(N);\n\t\tfor(var j = 0; j < N; j++){\n\t\t\tlist[j] = {\n\t\t\t\tno : j,\n\t\t\t\tG : tmp[j],\n\t\t\t\tchild : new Set()\n\t\t\t}\n\t\t}\n\t\tvar connect = 0;\n\t\tfor(var j = 0; j < N - 1; j++){\n\t\t\tif(connect == N - 1){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfor(var k = j + 1; k < N; k++){\n\t\t\t\tif(list[j].child.has(list[k].no) || list[k].child.has(list[j].no)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(list[j].G != list[k].G){\n\t\t\t\t\tisOK = true;\n\t\t\t\t\tlist[j].child.add(list[k].no);\n\t\t\t\t\tconnect++;\n\t\t\t\t\tif(connect == N - 1){\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t//list[k].child.add(list[j].no);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(isOK){\n\t\t\toutput.push(\"YES\");\n\t\t\tfor(var j = 0; j < N; j++){\n\t\t\t\tvar keys = Array.from(list[j].child);\n\t\t\t\tfor(var k = 0; k < keys.length; k++){\n\t\t\t\t\toutput.push((j + 1) + \" \" + (keys[k] + 1));\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t\toutput.push(\"NO\");\n\t\t}\n\t}\n\tmyout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n districtConnections();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction districtConnections(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let a = ti(readline().split(' '));\n\n let count = 0;\n let map = new Array(1000000005);\n let x = [];\n for(let i = 0; i < n; i++){\n if(map[a[i]] === undefined){\n count++;\n map[a[i]] = i+1;\n x.push(a[i]);\n }\n\n if(count >= 2)\n break;\n }\n\n if(count < 2){\n console.log('NO');\n continue;\n }\n\n console.log('YES');\n for(let i = 1; i < n; i++){\n if(a[i-1] !== x[0]){\n console.log(i, map[x[0]]);\n }else{\n console.log(i, map[x[1]]);\n }\n }\n }\n}"}], "src_uid": "d8136eb72931851f501c5ce9042ce4eb"} {"nl": {"description": "You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones and an integer $$$k$$$. In one operation you can do one of the following: Select $$$2$$$ consecutive elements of $$$a$$$ and replace them with their minimum (that is, let $$$a := [a_{1}, a_{2}, \\ldots, a_{i-1}, \\min(a_{i}, a_{i+1}), a_{i+2}, \\ldots, a_{n}]$$$ for some $$$1 \\le i \\le n-1$$$). This operation decreases the size of $$$a$$$ by $$$1$$$. Select $$$k$$$ consecutive elements of $$$a$$$ and replace them with their maximum (that is, let $$$a := [a_{1}, a_{2}, \\ldots, a_{i-1}, \\max(a_{i}, a_{i+1}, \\ldots, a_{i+k-1}), a_{i+k}, \\ldots, a_{n}]$$$ for some $$$1 \\le i \\le n-k+1$$$). This operation decreases the size of $$$a$$$ by $$$k-1$$$. Determine if it's possible to turn $$$a$$$ into $$$[1]$$$ after several (possibly zero) operations.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le k \\le n \\le 50$$$), the size of array $$$a$$$ and the length of segments that you can perform second type operation on. The second line contains $$$n$$$ integers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$.", "output_spec": "For each test case, if it is possible to turn $$$a$$$ into $$$[1]$$$, print \"YES\", otherwise print \"NO\".", "sample_inputs": ["7\n\n3 2\n\n0 1 0\n\n5 3\n\n1 0 1 1 0\n\n2 2\n\n1 1\n\n4 4\n\n0 0 0 0\n\n6 3\n\n0 0 1 0 0 1\n\n7 5\n\n1 1 1 1 1 1 1\n\n5 3\n\n0 0 1 0 0"], "sample_outputs": ["YES\nYES\nYES\nNO\nYES\nYES\nYES"], "notes": "NoteIn the first test case, you can perform the second type operation on second and third elements so $$$a$$$ becomes $$$[0, 1]$$$, then you can perform the second type operation on first and second elements, so $$$a$$$ turns to $$$[1]$$$.In the fourth test case, it's obvious to see that you can't make any $$$1$$$, no matter what you do.In the fifth test case, you can first perform a type 2 operation on the first three elements so that $$$a$$$ becomes $$$[1, 0, 0, 1]$$$, then perform a type 2 operation on the elements in positions two through four, so that $$$a$$$ becomes $$$[1, 1]$$$, and finally perform the first type operation on the remaining elements, so that $$$a$$$ becomes $$$[1]$$$."}, "positive_code": [{"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n var a = lines[i].split(' ').map(Number);\n if(i % 2 == 1){\n n = a[0];\n }else{\n var ans = 0;\n var flag = false;\n for(j = 0; j < n; j++){\n if(a[j] == 1){\n flag = true;\n break;\n }\n }\n console.log(flag ? 'YES' : 'NO');\n }\n }\n});"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar K = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tif(list.indexOf(1) == -1){\r\n\t\t\tmyout(\"NO\");\r\n\t\t}else{\r\n\t\t\tmyout(\"YES\");\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable',function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end',function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n for(let _=1;_<=t;_++)\r\n {\r\n let [n,k]=line[2*_-1].split(' ').map(x=>{return parseInt(x)});\r\n let a=line[2*_].split(' ').map(x=>{return parseInt(x)});\r\n flag=false;\r\n for(let i=0;i Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst sqrt = (n) => {\r\n let low = 1n,\r\n high = n,\r\n ans;\r\n while (low <= high) {\r\n let mid = (low + high) / 2n;\r\n if (mid * mid <= n) {\r\n ans = mid;\r\n low = mid + 1n;\r\n } else high = mid - 1n;\r\n }\r\n return ans;\r\n};\r\n\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [n, k] = iInpArr();\r\n let arr = iInpArr();\r\n let ans = \"NO\";\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] === 1) {\r\n ans = \"YES\";\r\n break;\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "(()=>{\"use strict\";var e={188:function(e,t,n){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,\"__esModule\",{value:!0}),t.singleWordInput=t.singleInput=t.testInput=void 0;const l=o(n(58)).default.createInterface({input:process.stdin,output:process.stdout});t.testInput=e=>{let t=[],n=0;l.on(\"line\",(function(o){if(t.push(o),1===t.length&&(n=+t[0]),t.length===2*n+1){l.close();for(let n=2;n{let t=[];l.on(\"line\",(function(n){t.push(n),1===t.length&&(l.close(),console.log(e(t[0])))}))},t.singleWordInput=e=>{let t=[];l.on(\"line\",(function(n){t.push(n),1===t.length&&(l.close(),console.log(e(n)))}))}},58:e=>{e.exports=require(\"readline\")}},t={};(function n(o){var l=t[o];if(void 0!==l)return l.exports;var s=t[o]={exports:{}};return e[o].call(s.exports,s,s.exports,n),s.exports})(188).testInput((function(e,t){return t.includes(1)?\"YES\":\"NO\"}))})();"}, {"source_code": "function solve() {\r\n read();\r\n write(~(read().indexOf('1')) ? 'YES' : 'NO'); \r\n}\r\n\r\nfunction start() {\r\n var T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n writeAns();\r\n}\r\n\r\nvar MEMORY;\r\nvar MEMORY_INDEX = 0;\r\nvar ANS = '';\r\n\r\ntry {\r\n initInput(start);\r\n} catch (e) {\r\n console.log(e);\r\n}\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\nfunction sortNumbers(a, b) {\r\n return a - b;\r\n}\r\nfunction sortNumbersDec(a, b) {\r\n return b - a;\r\n}\r\nvar ANS;\r\n// вывод через ANS быстрее, но ест кучу памяти.\r\n// К тому же, максимальная длина строки - 2097151.\r\nfunction write(value) {\r\n // console.log(value);\r\n ANS += value + '\\n';\r\n}\r\nfunction writeAns() {\r\n if (ANS) {\r\n console.log(ANS);\r\n }\r\n}\r\nfunction read() {\r\n return MEMORY[MEMORY_INDEX++];\r\n}\r\nfunction initInput(callback) {\r\n var fs = require('fs');\r\n var isLocalStart = process.argv[2] === 'lorelvate';\r\n if (!isLocalStart) {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n callback();\r\n return;\r\n }\r\n var path = require('path');\r\n fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {\r\n if (err) {\r\n write(err);\r\n return;\r\n }\r\n MEMORY = data.split('\\r\\n');\r\n callback();\r\n });\r\n}\r\n"}, {"source_code": "var test_number = readline();\r\nvar n = 0,\r\n k = 0;\r\nvar temp_line = \"\",\r\n array_number;\r\nwhile (test_number--) {\r\n temp_line = readline();\r\n array_number = readline();\r\n if (array_number.includes(\"1\")) print(\"YES\");\r\n else print(\"NO\");\r\n}"}, {"source_code": "var n = parseInt(readline());\r\n\r\nfor (var i = 0; i < n; i++){\r\n var num = readline();\r\n var arr = readline().split(\" \");\r\n var counter = false;\r\n\r\n for(var k = 0; k < arr.length; k++){\r\n if(arr[k] == 1){\r\n counter = true;\r\n break;\r\n }\r\n }\r\n if(counter === true) {\r\n print(\"YES\");\r\n }else{\r\n print(\"NO\");\r\n }\r\n}"}, {"source_code": "var t = readline();\r\n for(var i = 0 ; i < t ; ++i){\r\n var inputs = readline().split(' '), n = inputs[0] , k = inputs[1];\r\n var a = readline().split(' ');\r\n a.indexOf('1') == -1 ? print(\"NO\") : print(\"YES\");\r\n }"}, {"source_code": "const cntLines = readline();\r\n\r\nfor (var i=0; i item == 1) ? print('YES') : print('NO');\r\n}"}], "negative_code": [{"source_code": "var test_number = readline();\r\nvar n = 0;"}], "src_uid": "95d83cfdb2131f2f23ba5ef005c18b38"} {"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 — 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 ≤ n ≤ 105) — a number of rod-blanks. The second line contains n integers li (1 ≤ li ≤ 109) — 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 — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) 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 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}. "}, "positive_code": [{"source_code": "var n = parseInt(readline());\nvar input = readline().split(' ').map(function (item) {\n return parseInt(item);\n});\nvar max = 0;\nvar sum = input.reduce(function(acc, curr){\n if(curr > max){\n max = curr;\n }\n return acc+curr;\n}, 0)\nprint(2*max-sum+1);"}, {"source_code": "function getInput() {\n var line = readline();\n var lines = [line];\n while (line = readline()) {\n lines.push(line);\n }\n return lines;\n}\n\nfunction main() {\n var items = getInput().pop().split(' ').map(i => Number(i));\n var max = 0;\n items.forEach(item => {\n if (max < item) {\n max = item;\n }\n });\n \n print(max - (items.reduce((res, cur) => res + cur, 0) - max) + 1);\n}\n\nmain();"}], "negative_code": [], "src_uid": "f00d94eb37c98a449615f0411e5a3572"} {"nl": {"description": "You are given a string $$$s$$$ consisting of the characters 0, 1, and ?.Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.Calculate the number of beautiful contiguous substrings of the string $$$s$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — number of test cases. The first and only line of each test case contains the string $$$s$$$ ($$$1 \\le |s| \\le 2 \\cdot 10^5$$$) consisting of characters 0, 1, and ?. It is guaranteed that the sum of the string lengths over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single integer — the number of beautiful substrings of the string $$$s$$$.", "sample_inputs": ["3\n0?10\n???\n?10??1100"], "sample_outputs": ["8\n6\n25"], "notes": null}, "positive_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst s = rl().split('');\r\n\t\tconst n = s.length;\r\n\r\n\t\tconst px = Array(n).fill(0); px[-1] = 0;\r\n\t\tfor (let i = 0; i < n; i++) if (s[i] == '?') px[i] = px[i-1] + 1; \r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 0, cnt = 0; i < n; i++) {\r\n\r\n\t\t\tif (s[i] == '?') s[i] = 1 ^ s[i-1];\r\n\r\n\t\t\tif (s[i] == s[i-1]) cnt = 1 + px[i-1];\r\n\t\t\telse cnt++;\r\n\r\n\t\t\tans += cnt;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst S = rl().split('');\r\n\t\tconst n = S.length;\r\n\r\n\t\tfor (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;\r\n\t\tconst px = Array(n).fill(0); px[-1] = 0;\r\n\t\tfor (let i = 0; i < n; i++) if (S[i] == '?') px[i] = px[i-1] + 1; \r\n\r\n\r\n\t\ts = S.slice();\r\n\t\tif (s[0] == '?') s[0] = 0;\r\n\r\n\t\tlet ans = 0;\r\n\r\n\t\tlet res = 1, cnt = 1;\r\n\t\tfor (let j = 1; j < n; j++) {\r\n\t\t\tif (s[j] == '?') s[j] = 1 ^ s[j-1];\r\n\t\t\tif (s[j] == s[j-1]) {\r\n\t\t\t\tcnt = 1 + px[j-1];\r\n\t\t\t} else {\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t\tres += cnt;\r\n\t\t}\r\n\t\tans = Math.max(ans, res);\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst S = rl().split('');\r\n\t\tconst n = S.length;\r\n\r\n\t\tfor (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;\r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 0; i < 2; i++) {\r\n\t\t\ts = S.slice();\r\n\t\t\tif (s[0] == '?') s[0] = i;\r\n\r\n\t\t\tlet res = 1, cnt = 1;\r\n\t\t\tfor (let j = 1; j < n; j++) {\r\n\t\t\t\tif (s[j] == '?') s[j] = 1 ^ s[j-1];\r\n\t\t\t\tif (s[j] == s[j-1]) {\r\n\t\t\t\t\tcnt = 1;\r\n\t\t\t\t\tk = j-1;\r\n\t\t\t\t\twhile (k >= 0 && S[k] == '?') { cnt++; k--;}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tcnt++;\r\n\t\t\t\t}\r\n\t\t\t\tres += cnt;\r\n\t\t\t}\r\n\r\n\t\t\tans = Math.max(ans, res);\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if (y === 0) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction solve() {\r\n var str = read();\r\n var mark = [];\r\n var n = str.length;\r\n var curStreak = -1;\r\n var lastIndex = -1n;\r\n var lastDigitIndex = -1n;\r\n var questionStreak = 0n;\r\n var ans = 0n;\r\n for (var i = 0; i < n; i++) {\r\n var char = str[i];\r\n if (char === '?') {\r\n questionStreak += 1n;\r\n continue;\r\n }\r\n var x = (char === '1') ? !(i & 1) : !!(i & 1);\r\n if (curStreak === -1) {\r\n curStreak = x;\r\n }\r\n var bigi = BigInt(i); \r\n if (curStreak === x) {\r\n lastDigitIndex = bigi;\r\n questionStreak = 0n;\r\n continue;\r\n }\r\n curStreak = x;\r\n var len = bigi - 1n - lastIndex;\r\n ans = ans + (len * (len + 1n) / 2n) - (questionStreak * (questionStreak + 1n) / 2n);\r\n lastIndex = lastDigitIndex;\r\n lastDigitIndex = bigi;\r\n questionStreak = 0n;\r\n }\r\n var len = BigInt(n - 1) - lastIndex;\r\n ans = ans + (len * (len + 1n) / 2n);\r\n write(ans); \r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 06/04/21 morning\r\n * https://codeforces.com/contest/1535/problem/C\r\n */\r\n\r\nconst solve = (s) => {\r\n let n = s.length;\r\n let pos = Array(n).fill(-1);\r\n for (let i = 0; i < n; i++) {\r\n if (s[i] != '?') pos[i] = s[i] ^ (i % 2);\r\n }\r\n let zero = one = res = 0;\r\n // pr(pos);\r\n let j = -1; // right\r\n for (let i = 0; i < n; i++) {\r\n while (j < n && (zero == 0 || one == 0)) {\r\n j++;\r\n if (pos[j] == 0) {\r\n zero++;\r\n } else if (pos[j] == 1) {\r\n one++;\r\n }\r\n }\r\n res += j - i;\r\n if (pos[i] == 0) {\r\n zero--;\r\n } else if (pos[i] == 1) {\r\n one--;\r\n }\r\n }\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line);\r\n });\r\n rl.on('close', () => {\r\n let t = Number(input[0]);\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i]);\r\n i++;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = parseInt(lines[0]);\n var l = 1;\n for (var i = 0; i < t; i++) {\n var str = lines[l++]\n console.log(solve(str));\n }\n});\n \nfunction solve(str) {\n let sum = 0\n let expect = '?'\n let prev = 0\n for (let i = 0; i < str.length; i++) {\n const ch = str[i]\n if (isMatch(expect, ch)) {\n prev++\n\n if (expect === '?') {\n if (ch !== '?') expect = getOther(ch)\n } else {\n expect = getOther(expect)\n }\n } else {\n let j = i\n while (j >= 0) {\n const change = (i - j) & 1\n const other = getOther(str[j])\n if (str[j] !== '?'\n && !isMatch(ch, change ? other : str[j])) {\n j++\n break\n }\n j--\n }\n prev = i - j + 1\n expect = getOther(ch)\n }\n \n// console.log(prev)\n sum += prev\n }\n// console.log('----')\n return sum \n}\n\nfunction isMatch(expect, actual) {\n if (expect === '?' || actual === '?') return true\n return expect === actual\n}\nfunction getOther(ch) {\n return ch === '0' ? '1' : '0'\n}\n"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst S = rl().split('');\r\n\t\tconst n = S.length;\r\n\r\n\t\tfor (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;\r\n\t\tconst px = Array(n).fill(0); px[-1] = 0;\r\n\t\tfor (let i = 0; i < n; i++) if (S[i] == '?') px[i] = px[i-1] + 1; \r\n\r\n\r\n\t\ts = S.slice();\r\n\t\tif (s[0] == '?') s[0] = 0;\r\n\r\n\t\tlet ans = 0;\r\n\r\n\t\tlet res = 1, cnt = 1;\r\n\t\tfor (let j = 1; j < n; j++) {\r\n\t\t\tif (s[j] == '?') s[j] = 1 ^ s[j-1];\r\n\t\t\tif (s[j] == s[j-1]) {\r\n\t\t\t\tcnt = 1 + px[j-1];\r\n\t\t\t} else {\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t\tres += cnt;\r\n\r\n\t\t\tans = Math.max(ans, res);\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst S = rl().split('');\r\n\t\tconst n = S.length;\r\n\r\n\t\tfor (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;\r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 0; i < 2; i++) {\r\n\t\t\ts = S.slice();\r\n\t\t\tif (s[0] == '?') s[0] = i;\r\n\t\t\t//else s[0] = s[0]-0;\r\n\r\n\t\t\tlet res = 1, cnt = 1;\r\n\t\t\tfor (let j = 1; j < n; j++) {\r\n\t\t\t\tif (s[j] == '?') s[j] = 1 ^ s[j-1];\r\n\t\t\t\tif (s[j] == s[j-1]) {\r\n\t\t\t\t\tcnt = 1;\r\n\t\t\t\t\tk = j-1;\r\n\t\t\t\t\twhile (k >= 0 && S[k] == '?') { cnt++; k++;}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tcnt++;\r\n\t\t\t\t}\r\n\t\t\t\tres += cnt;\r\n\t\t\t}\r\n\r\n\t\t\tans = Math.max(ans, res);\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if (y === 0) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction solve() {\r\n var str = read();\r\n var mark = [];\r\n var n = str.length;\r\n var curStreak = -1;\r\n var lastIndex = -1n;\r\n var lastDigitIndex = -1n;\r\n var questionStreak = 0n;\r\n var ans = 0n;\r\n for (var i = 0; i < n; i++) {\r\n var char = str[i];\r\n if (char === '?') {\r\n questionStreak += 1n;\r\n continue;\r\n }\r\n var x = (char === '1') ? !(i & 1) : !!(i & 1);\r\n if (curStreak === -1) {\r\n curStreak = x;\r\n }\r\n var bigi = BigInt(i); \r\n if (curStreak === x) {\r\n lastDigitIndex = bigi;\r\n questionStreak = 0n;\r\n continue;\r\n }\r\n curStreak = x;\r\n var len = bigi - 1n - lastIndex;\r\n ans = ans + (len * (len + 1n) / 2n) - (questionStreak * (questionStreak + 1n) / 2n);\r\n lastIndex = lastDigitIndex;\r\n }\r\n var len = BigInt(n - 1) - lastIndex;\r\n ans = ans + (len * (len + 1n) / 2n);\r\n write(ans); \r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if (y === 0) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction solve() {\r\n var str = read();\r\n var mark = [];\r\n var n = str.length;\r\n var curStreak = -1;\r\n var lastIndex = -1n;\r\n var lastDigitIndex = -1n;\r\n var ans = BigInt(n);\r\n for (var i = 0; i < n; i++) {\r\n var char = str[i];\r\n if (char === '?') {\r\n continue;\r\n }\r\n var x = (char === '1') ? !(i & 1) : !!(i & 1);\r\n if (curStreak === -1) {\r\n curStreak = x;\r\n }\r\n var bigi = BigInt(i); \r\n if (curStreak === x) {\r\n lastDigitIndex = bigi;\r\n continue;\r\n }\r\n curStreak = x;\r\n var len = bigi - 1n - lastIndex;\r\n ans = ans + (len * (len - 1n) / 2n);\r\n lastIndex = lastDigitIndex;\r\n lastDigitIndex = bigi;\r\n }\r\n var len = BigInt(n - 1) - lastIndex;\r\n ans = ans + (len * (len - 1n) / 2n);\r\n write(ans); \r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}, {"source_code": "var timer = 0;\r\nfunction dfs(v, prev) {\r\n var h = {};\r\n v.__h = h;\r\n h.tin = ++timer;\r\n h.up = [];\r\n var i = 0;\r\n var next = prev;\r\n while (next) {\r\n h.up[i] = next;\r\n next = next.__h.up[i++];\r\n }\r\n var children = v.childNodes;\r\n for (i = 0; i < children.length; i++) {\r\n dfs(children[i], v);\r\n }\r\n h.tout = ++timer;\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if (y === 0) {\r\n return x;\r\n }\r\n return gcd(y, x % y);\r\n}\r\n\r\nfunction solve() {\r\n var str = read();\r\n var mark = [];\r\n var n = str.length;\r\n var curStreak = -1;\r\n var lastIndex = -1n;\r\n var lastDigitIndex = -1n;\r\n var ans = BigInt(n);\r\n for (var i = 0; i < n; i++) {\r\n var char = str[i];\r\n if (char === '?') {\r\n continue;\r\n }\r\n var x = (char === '1') ? !(i & 1) : !!(i & 1);\r\n if (curStreak === -1) {\r\n curStreak = x;\r\n }\r\n var bigi = BigInt(i); \r\n if (curStreak === x) {\r\n lastDigitIndex = bigi;\r\n continue;\r\n }\r\n curStreak = x;\r\n var len = bigi - 1n - lastIndex;\r\n ans = ans + (len * (len - 1n) / 2n);\r\n lastIndex = lastDigitIndex;\r\n }\r\n var len = BigInt(n - 1) - lastIndex;\r\n ans = ans + (len * (len - 1n) / 2n);\r\n write(ans); \r\n}\r\n\r\nfunction init() {\r\n var T;\r\n T = 1;\r\n T = Number(read());\r\n for (var t = 0; t < T; t++) {\r\n solve();\r\n }\r\n}\r\n\r\nfunction sortF(a, b) {\r\n if (a < b) {\r\n return -1;\r\n }\r\n if (a > b) {\r\n return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction readArray(f) {\r\n return read().split(' ').map(f);\r\n}\r\n\r\n\r\nvar isNode = typeof console !== 'undefined';\r\nvar MEMORY = [];\r\nvar MEMORY_INDEX = 0;\r\nif (isNode) {\r\n var fs = require('fs');\r\n var path = require('path');\r\n\r\n var inTextName;\r\n var outTextName;\r\n\r\n var needWriteFile = false;\r\n\r\n var writeResult = '';\r\n if (process.argv.length === 5) {\r\n inTextName = process.argv[3];\r\n outTextName = process.argv[4];\r\n }\r\n\r\n if (inTextName) {\r\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\r\n MEMORY = data.split('\\r\\n');\r\n init();\r\n if (needWriteFile) {\r\n fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {\r\n err ? console.error(err) : console.log('good')\r\n });\r\n }\r\n });\r\n } else {\r\n MEMORY = fs.readFileSync(0, 'utf-8').split('\\r\\n');\r\n init();\r\n }\r\n} else {\r\n init();\r\n}\r\n\r\nfunction write(value) {\r\n if (needWriteFile) {\r\n writeResult += value + '\\n';\r\n return;\r\n }\r\n isNode ? console.log('' + value) : print('' + value);\r\n}\r\nfunction read() {\r\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\r\n}\r\nfunction readAll() {\r\n return isNode && MEMORY;\r\n}\r\n"}], "src_uid": "639eeeabcb005152035a1fcf09ed3b44"} {"nl": {"description": "Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.", "input_spec": "The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.", "output_spec": "If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.", "sample_inputs": ["3\n1 2\n2 3\n3", "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 6 3", "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 3 6"], "sample_outputs": ["1 2 3 2 1", "1 2 4 5 4 6 4 2 1 3 1", "-1"], "notes": null}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar vertexNum = parseInt(readline());\n\t\n\tvar edges = {\n\t\taugment: function(u, v) {\n\t\t\tif (edges[u] === undefined) {\n\t\t\t\tedges[u] = [v];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tedges[u].push(v);\n\t\t\t}\n\t\t}\n\t};\n\n\tfor (var i = 1; i < vertexNum; ++i) {\n\t\tvar pair = tokenizeIntegers(readline());\n\t\tedges.augment(pair[0], pair[1]);\n\t\tedges.augment(pair[1], pair[0]);\n\t}\n\n\tvar nodes = {};\n\tvar root = 1;\n\n\tfunction descend(path) {\n\t\tvar current = path[path.length-1];\n\t\tnodes[current] = { index: current,\n\t\t\t\tchildren: [],\n\t\t\t\tleaves: [], hasLeaf: {}, leafCount: 0,\n\t\t\t\tparent: path[path.length-2], visitCount: 0 };\n\n\t\tvar neighbors = edges[current];\n\t\tif (neighbors.length == 1 && current != root) {\n\t\t\tnodes[current].isLeaf = true;\n\t\t\tfor (var i = path.length-1; i >= 0; --i) {\n\t\t\t\tvar node = nodes[path[i]];\n\t\t\t\tnode.leaves.push(current);\n\t\t\t\tnode.hasLeaf[current] = true;\n\t\t\t\tnode.leafCount += 1;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0; i < neighbors.length; ++i) {\n\t\t\tvar child = neighbors[i];\n\t\t\tif (path.length > 1 && path[path.length-2] == child) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnodes[current].children.push(child);\n\n\t\t\tpath.push(child);\n\t\t\tdescend(path);\n\t\t\tpath.pop();\n\t\t}\n\t}\n\n\tdescend([root]);\n\n\tvar order = tokenizeIntegers(readline());\n\n\tvar seek = root,\n\t\troute = [root],\n\t\tnode = nodes[root];\n\tnode.visitCount = 1;\n\n\tfor (var i = 0; i < order.length; ++i) {\n\t\tvar target = order[i];\n\t\twhile (!node.hasLeaf[target]) { // ascend\n\t\t\tseek = node.parent;\n\t\t\troute.push(seek);\n\t\t\tnode = nodes[seek];\n\t\t\tnode.visitCount += 1;\n\t\t\tif (node.visitCount > 1+node.children.length) {\n\t\t\t\tprint(-1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\twhile (seek != target) { // descend\n\t\t\tfor (var j = 0; j < node.children.length; ++j) {\n\t\t\t\tif (nodes[node.children[j]].hasLeaf[target]) {\n\t\t\t\t\tseek = node.children[j];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\troute.push(seek);\n\t\t\tnode = nodes[seek];\n\t\t\tnode.visitCount += 1;\n\t\t}\n\t}\n\n\twhile (seek != root) {\n\t\tseek = node.parent;\n\t\troute.push(seek);\n\t\tnode = nodes[seek];\n\t\tnode.visitCount += 1;\n\t\tif (node.visitCount != 1+node.children.length) {\n\t\t\tprint(-1);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprint(route.join(\" \"));\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar vertexNum = parseInt(readline());\n\t\n\tvar edges = {\n\t\taugment: function(u, v) {\n\t\t\tif (edges[u] === undefined) {\n\t\t\t\tedges[u] = [v];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tedges[u].push(v);\n\t\t\t}\n\t\t}\n\t};\n\n\tfor (var i = 1; i < vertexNum; ++i) {\n\t\tvar pair = tokenizeIntegers(readline());\n\t\tedges.augment(pair[0], pair[1]);\n\t\tedges.augment(pair[1], pair[0]);\n\t}\n\n\tvar nodes = {};\n\tvar root = 1;\n\n\tfunction descend(path) {\n\t\tvar current = path[path.length-1];\n\t\tnodes[current] = {\n\t\t\t\tchildren: [],\n\t\t\t\tleadsToLeaf: {},\n\t\t\t\tparent: path[path.length-2], visitCount: 0\n\t\t};\n\n\t\tvar neighbors = edges[current];\n\t\tif (neighbors.length == 1 && current != root) { // it's a leaf\n\t\t\tfor (var i = path.length-1; i >= 0; --i) {\n\t\t\t\tvar node = nodes[path[i]];\n\t\t\t\tnode.leadsToLeaf[current] = true;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0; i < neighbors.length; ++i) {\n\t\t\tvar child = neighbors[i];\n\t\t\tif (path.length > 1 && path[path.length-2] == child) {\n\t\t\t\tcontinue; // don't descend to the parent\n\t\t\t}\n\n\t\t\tnodes[current].children.push(child);\n\n\t\t\tpath.push(child);\n\t\t\tdescend(path);\n\t\t\tpath.pop();\n\t\t}\n\t}\n\n\tdescend([root]);\n\n\tvar order = tokenizeIntegers(readline());\n\n\tvar seek = root,\n\t\troute = [root],\n\t\tnode = nodes[root];\n\tnode.visitCount = 1;\n\n\tfor (var i = 0; i < order.length; ++i) {\n\t\tvar target = order[i];\n\t\twhile (!node.leadsToLeaf[target]) { // ascend\n\t\t\tseek = node.parent;\n\t\t\troute.push(seek);\n\t\t\tnode = nodes[seek];\n\t\t\tnode.visitCount += 1;\n\t\t\tif (node.visitCount > 1+node.children.length) {\n\t\t\t\tprint(-1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\twhile (seek != target) { // descend\n\t\t\tfor (var j = 0; j < node.children.length; ++j) {\n\t\t\t\tif (nodes[node.children[j]].leadsToLeaf[target]) {\n\t\t\t\t\tseek = node.children[j];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\troute.push(seek);\n\t\t\tnode = nodes[seek];\n\t\t\tnode.visitCount += 1;\n\t\t}\n\t}\n\n\twhile (seek != root) { // ascend to the root one last time\n\t\tseek = node.parent;\n\t\troute.push(seek);\n\t\tnode = nodes[seek];\n\t\tnode.visitCount += 1;\n\t\tif (node.visitCount != 1+node.children.length) {\n\t\t\tprint(-1);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprint(route.join(\" \"));\n}\n\nmain();\n"}], "negative_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar vertexNum = parseInt(readline());\n\t\n\tvar edges = {\n\t\taugment: function(u, v) {\n\t\t\tif (edges[u] === undefined) {\n\t\t\t\tedges[u] = [v];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tedges[u].push(v);\n\t\t\t}\n\t\t}\n\t};\n\n\tfor (var i = 1; i < vertexNum; ++i) {\n\t\tvar pair = tokenizeIntegers(readline());\n\t\tedges.augment(pair[0], pair[1]);\n\t\tedges.augment(pair[1], pair[0]);\n\t}\n\n\tvar nodes = {};\n\tvar root = 1;\n\n\tfunction descend(path) {\n\t\tvar current = path[path.length-1];\n\t\tnodes[current] = { index: current,\n\t\t\t\tchildren: [],\n\t\t\t\tleaves: [], hasLeaf: {}, leafCount: 0,\n\t\t\t\tparent: path[path.length-2], visitCount: 0 };\n\n\t\tvar neighbors = edges[current];\n\t\tif (neighbors.length == 1 && current != root) {\n\t\t\tnodes[current].isLeaf = true;\n\t\t\tfor (var i = path.length-1; i >= 0; --i) {\n\t\t\t\tvar node = nodes[path[i]];\n\t\t\t\tnode.leaves.push(current);\n\t\t\t\tnode.hasLeaf[current] = true;\n\t\t\t\tnode.leafCount += 1;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0; i < neighbors.length; ++i) {\n\t\t\tvar child = neighbors[i];\n\t\t\tif (path.length > 1 && path[path.length-2] == child) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnodes[current].children.push(child);\n\n\t\t\tpath.push(child);\n\t\t\tdescend(path);\n\t\t\tpath.pop();\n\t\t}\n\t}\n\n\tdescend([root]);\n\n\tvar order = tokenizeIntegers(readline());\n\n\tvar seek = root,\n\t\troute = [root],\n\t\tnode = nodes[root];\n\n\tfor (var i = 0; i < order.length; ++i) {\n\t\tvar target = order[i];\n\t\twhile (!node.hasLeaf[target]) { // ascend\n\t\t\tseek = node.parent;\n\t\t\troute.push(seek);\n\t\t\tnode = nodes[seek];\n\t\t\tnode.visitCount += 1;\n\t\t\tif (node.visitCount > 2*node.children.length) {\n\t\t\t\tprint(-1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\twhile (seek != target) { // descend\n\t\t\tfor (var i = 0; i < node.children.length; ++i) {\n\t\t\t\tif (nodes[node.children[i]].hasLeaf[target]) {\n\t\t\t\t\tseek = node.children[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\troute.push(seek);\n\t\t\tnode = nodes[seek];\n\t\t\tnode.visitCount += 1;\n\t\t}\n\t}\n\n\twhile (true) {\n\t\tseek = node.parent;\n\t\troute.push(seek);\n\t\tnode = nodes[seek];\n\t\tnode.visitCount += 1;\n\t\tif (seek == root) {\n\t\t\tprint(route.join(\" \"));\n\t\t\treturn;\n\t\t}\n\t\tif (node.visitCount != 2*node.children.length) {\n\t\t\tprint(-1);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nmain();\n"}], "src_uid": "915bb1dec7af4427c4cc33f7803f6651"} {"nl": {"description": "Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words \"lios\", \"liala\", \"etr\" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.", "input_spec": "The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.", "output_spec": "If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print \"NO\" (without the quotes). Otherwise, print \"YES\" (without the quotes).", "sample_inputs": ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"], "sample_outputs": ["YES", "NO", "YES"], "notes": null}, "positive_code": [{"source_code": "var str = readline();\nvar arr = str.split(' ');\nvar adj_fem = function(str) {return (str.substr(-5, 5) === 'liala')};\nvar adj_mal = function(str) {return (str.substr(-4, 4) === 'lios')};\nvar noun_fem = function(str) {return (str.substr(-4, 4) === 'etra')};\nvar noun_mal = function(str) {return (str.substr(-3, 3) === 'etr')};\nvar verb_fem = function(str) {return (str.substr(-6, 6) === 'inites')};\nvar verb_mal = function(str) {return (str.substr(-6, 6) === 'initis')};\nvar checks = [adj_fem, adj_mal, noun_fem, noun_mal, verb_fem, verb_mal];\nvar result = 0;\nvar i;\nif (arr.length === 1) {\n i = -1;\n while (++i < checks.length) \n result |= checks[i](arr[0]);\n} else {\n i = 0;\n result = 1;\n while ((i < arr.length) && (result &= (checks[0](arr[i]) || checks[1](arr[i])))) i++;\n result = 1;\n result &= ((i < arr.length) && (checks[2](arr[i]) || checks[3](arr[i])));\n i++;\n while ((i < arr.length) && (result &= (checks[4](arr[i]) || checks[5](arr[i])))) i++;\n \n i = 0;\n test2 = true, test3 = true;\n while ((i < arr.length) && (test2 &= (checks[0](arr[i]) || checks[2](arr[i]) || checks[4](arr[i])))) i++;\n i = 0;\n while ((i < arr.length) && (test3 &= (checks[1](arr[i]) || checks[3](arr[i]) || checks[5](arr[i])))) i++;\n result = (result & test2) || (result & test3);\n}\nwrite(result ? 'YES' : 'NO')"}], "negative_code": [], "src_uid": "0c9550a09f84de6bed529d007ccb4ae8"} {"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. e. $$$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$$$) — 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$$$) — 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$$$) — 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}$$$) — 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": "const solve = (ch,cd,mh,md,k,w,a)=>{\r\n let chelath = Math.ceil(ch/md);\r\n let cdamage = Math.ceil(mh/cd);\r\n if(cdamage<=chelath) console.log(\"YES\");\r\n else if(k===0) console.log(\"NO\");\r\n else{\r\n cd = cd + (k*w);\r\n for(let i=0;i<=k;i++){\r\n if(i!=0){\r\n cd-=w;\r\n ch+=a;\r\n }\r\n chelath = Math.ceil(ch/md);\r\n cdamage = Math.ceil(mh/cd);\r\n if(cdamage<=chelath){\r\n console.log(\"YES\");\r\n return;\r\n }\r\n }\r\n console.log(\"NO\");\r\n }\r\n}\r\nfunction main() {\r\n const fs = require(\"fs\");\r\n const input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\r\n let line = 0;\r\n function readline() {\r\n return input[line++];\r\n }\r\n let t = parseInt(readline());\r\n for(let i=0;iparseInt(cur));\r\n let arr2 = readline().trim().split(\" \").map(cur=>parseInt(cur));\r\n let arr3 = readline().trim().split(\" \").map(cur=>parseInt(cur));\r\n solve(arr1[0],arr1[1],arr2[0],arr2[1],arr3[0],arr3[1],arr3[2]);\r\n }\r\n}\r\nmain();"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [hc, dc] = lines[l++].trim().split(' ').map(Number)\n const [hm, dm] = lines[l++].trim().split(' ').map(Number)\n const [k, w, a] = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(hc, dc, hm, dm, k, w, a) ? 'YES' : 'NO'\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(hc, dc, hm, dm, k, w, a) {\n for (let i = 0; i <= k; i++) {\n const j = k - i\n if (win(hc + i * a, dc + j * w, hm, dm)) return true\n }\n return false\n}\nfunction win(hc, dc, hm, dm) {\n const a = Math.ceil(hc / dm)\n const b = Math.ceil(hm / dc)\n return a >= b\n}\n"}, {"source_code": "const check = (hc,dc,hm,dm) =>{\r\n return (Math.ceil(hc/dm)>=Math.ceil(hm/dc));\r\n}\r\nvar t=readline();\r\nwhile(t--){\r\n var h=readline().split(\" \").map(x => parseInt(x));\r\n var m=readline().split(\" \").map(x => parseInt(x));\r\n var att=readline().split(\" \").map(x => parseInt(x));\r\n var pos=0;\r\n var l,r;\r\n for(var i=0;i<=att[0];i++){\r\n l=i;\r\n r=att[0]-i;\r\n pos|=check(h[0]+att[2]*l,h[1]+att[1]*r,m[0],m[1]);\r\n }\r\n \r\n if(pos>0){\r\n print(\"YES\");\r\n }else print(\"NO\");\r\n}"}, {"source_code": "function check(hc,dc,hm,dm){\r\n return (Math.ceil(hc/dm)>=Math.ceil(hm/dc));\r\n}\r\nvar t=readline();\r\nwhile(t--){\r\n var h=readline().split(\" \").map(x => parseInt(x));\r\n var m=readline().split(\" \").map(x => parseInt(x));\r\n var att=readline().split(\" \").map(x => parseInt(x));\r\n var pos=0;\r\n var l,r;\r\n for(var i=0;i<=att[0];i++){\r\n l=i;\r\n r=att[0]-i;\r\n pos|=check(h[0]+att[2]*l,h[1]+att[1]*r,m[0],m[1]);\r\n }\r\n \r\n if(pos>0){\r\n print(\"YES\");\r\n }else print(\"NO\");\r\n}"}, {"source_code": "var lines = parseInt(readline());\r\n\r\nfor (var i = 0; i < lines; i++) {\r\n var line = readline().split(\" \");\r\n var hpC = parseInt(line[0]);\r\n var damC = parseInt(line[1]);\r\n line = readline().split(\" \");\r\n var hpE = parseInt(line[0]);\r\n var damE = parseInt(line[1]);\r\n line = readline().split(\" \");\r\n var coins = parseInt(line[0]);\r\n var attack = parseInt(line[1]);\r\n var defense = parseInt(line[2]);\r\n var h = 0;\r\n var win = false;\r\n while (!win && h <= coins) {\r\n var turnsC = Math.ceil(hpE / (damC + attack * h));\r\n var turnsE = Math.ceil((hpC + defense * (coins - h)) / damE);\r\n if (turnsC <= turnsE) {\r\n win = true;\r\n print(\"YES\");\r\n } else {\r\n var hForSpeedUp = Math.ceil((hpE / (turnsC - 1) - damC) / attack);\r\n var hForSlowDown = Math.ceil(((turnsE + 1) * damE - hpC) / defense);\r\n h += Math.min(hForSpeedUp - h, hForSlowDown - (coins - h));\r\n }\r\n }\r\n if (!win) print(\"NO\");\r\n}\r\n"}], "negative_code": [{"source_code": "const solve = (ch,cd,mh,md,k,w,a)=>{\r\n let chelath = Math.floor(ch/md)+1;\r\n let cdamage = Math.ceil(mh/cd);\r\n if(cdamage<=chelath) console.log(\"YES\");\r\n else if(k===0) console.log(\"NO\");\r\n else{\r\n cd = cd + (k*w);\r\n for(let i=0;i<=k;i++){\r\n if(i!=0){\r\n cd-=w;\r\n ch+=a;\r\n }\r\n chelath = Math.floor(ch/md)+1;\r\n cdamage = Math.ceil(mh/cd);\r\n if(cdamage<=chelath){\r\n console.log(\"YES\");\r\n return;\r\n }\r\n }\r\n console.log(\"NO\");\r\n }\r\n}\r\nfunction main() {\r\n const fs = require(\"fs\");\r\n const input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\r\n let line = 0;\r\n function readline() {\r\n return input[line++];\r\n }\r\n let t = parseInt(readline());\r\n for(let i=0;iparseInt(cur));\r\n let arr2 = readline().trim().split(\" \").map(cur=>parseInt(cur));\r\n let arr3 = readline().trim().split(\" \").map(cur=>parseInt(cur));\r\n solve(arr1[0],arr1[1],arr2[0],arr2[1],arr3[0],arr3[1],arr3[2]);\r\n }\r\n}\r\nmain();"}], "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 ≤ n ≤ 150 000, ) — 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 ≤ ai, bi ≤ n, ai ≠ bi). 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, 3) are friends and members (3, 4) are friends, while members (2, 4) are not. "}, "positive_code": [{"source_code": "\n var tmp = readline().split(' ').map(function(x) { return parseInt(x)});\n var n = tmp[0];\n var m = tmp[1];\n var e = [];\n var vis = [];\n for(var i = 1; i <= n; i += 1) {\n e[i] = [];\n vis[i] = false;\n }\n for(var i = 1; i <= m; i += 1) {\n var tmp = readline().split(' ').map(function(x) { return parseInt(x)});\n e[tmp[0]].push(tmp[1]);\n e[tmp[1]].push(tmp[0]);\n }\n var finding = true;\n for(var i = 1; i <= n && finding; i += 1) {\n if(!vis[i]) {\n vis[i] = true;\n var vn = 1;\n var en = e[i].length;\n var stack = [i];\n while(stack.length > 0) {\n var d = stack.pop();\n for(var b in e[d]) {\n if(!vis[e[d][b]]) {\n vis[e[d][b]] = true;\n stack.push(e[d][b]);\n vn += 1;\n en += e[e[d][b]].length;\n }\n }\n }\n if(en !== vn * (vn - 1)) {\n finding = false;\n }\n }\n }\n if(finding) {\n print('YES');\n } else {\n print('NO');\n }"}, {"source_code": "/*filesystem = require('fs');\nvar inputLines = filesystem.readFileSync('input.txt').toString().split('\\n');\nvar inputIndex = 0;\n\nfunction readline() {\n return inputLines[inputIndex++];\n}\n\nfunction print() {\n var ans = \"\";\n for (var i = 0; i < arguments.length; i++) {\n if (i != 0) ans += \" \";\n ans += arguments[i].toString();\n }\n console.log(ans);\n}*/\n//FILESYSTEM\n\nvar currentLine;\nvar currentIndex;\nfunction read() {\n if ((currentLine == null) || (currentIndex == currentLine.length)) {\n currentLine = readline().split(' ');\n currentIndex = 0;\n }\n return currentLine[currentIndex++];\n}\n\nfunction readInt() {\n return parseInt(read());\n}\n//HELPERS\nfunction dfs(v) {\n var q = [];\n q.push(v);\n w[v] = true;\n for (var i = 0; i < q.length; i++) {\n var v = q[i];\n for (var j = 0; j < e[v].length; j++) {\n var u = e[v][j];\n if (!w[u]) {\n q.push(u);\n w[u] = true;\n }\n }\n }\n return q.length;\n}\n\nvar n = readInt(), m = readInt();\nvar w = new Array(n + 1).fill(false);\nvar e = new Array(n + 1);\nfor (var i = 1; i <= n; i++) e[i] = [];\nfor (var i = 0; i < m; i++) {\n var a = readInt(), b = readInt();\n e[a].push(b);\n e[b].push(a);\n}\nvar tot = 0;\nfor (var i = 1; i <= n; i++) {\n if (!w[i]) {\n var size = dfs(i);\n tot += size * (size - 1);\n }\n}\nif (tot == 2 * m) print('YES');\nelse print('NO');"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tlinks_count = [],\n\tlinks = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfailed = false\n\nif (m == 0) {\n\tprint(\"YES\")\n} else {\n\tfor(i = 0; i <=n; i++) {\n\t\tlinks[i] = []\n\t\tlinks_count[i] = 0\n\t}\n\n\tfor(i = 0; i < m; i++) {\n\t\tpos = ints()\n\t\tlinks_count[pos[0]] ++\n\t\tlinks_count[pos[1]] ++\n\t\tif (pos[0] < pos[1])\n\t\t\tlinks[pos[0]].push(pos[1])\n\t\telse\n\t\t\tlinks[pos[1]].push(pos[0])\n\t}\n\n\tfor (x = 1; x < n && !failed; x ++) {\n\t\ti = links[x].length - 1\n\t\twhile (i >= 0 && !failed) {\n\t\t\tfailed = links_count[x] != links_count[links[x][i]]\n\t\t\tlinks_count[links[x][i]] --\n\t\t\ti --\n\t\t}\n\t}\n\n\tif (failed)\n\t\tprint(\"NO\")\n\telse\n\t\tprint(\"YES\")\n}\n"}, {"source_code": " var tmp = readline().split(' ').map(function(x) { return parseInt(x)});\n var n = tmp[0];\n var m = tmp[1];\n var e = [];\n var vis = [];\n for(var i = 1; i <= n; i += 1) {\n e[i] = [];\n vis[i] = false;\n }\n for(var i = 1; i <= m; i += 1) {\n var tmp = readline().split(' ').map(function(x) { return parseInt(x)});\n e[tmp[0]].push(tmp[1]);\n e[tmp[1]].push(tmp[0]);\n }\n var cnt_vertices = 0\n var cnt_edges = 0;\n var stack = [];\n var dfs = function(x) {\n stack.push(x);\n while(stack.length > 0) {\n var a = stack.pop();\n if(vis[a]) {\n continue;\n }\n vis[a] = true;\n vn += 1;\n en += e[a].length;\n for(var b in e[a]) {\n stack.push(e[a][b]);\n // dfs(e[a][b]);\n }\n }\n };\n var finding = true;\n var vn = 0;\n var en = 0;\n for(var i = 1; i <= n && finding; i += 1) {\n if(!vis[i]) {\n vn = 0\n en = 0;\n dfs(i);\n if(en !== vn * (vn - 1)) {\n finding = false;\n }\n }\n }\n if(finding) {\n print('YES');\n } else {\n print('NO');\n }"}], "negative_code": [{"source_code": " var tmp = readline().split(' ').map(function(x) { return parseInt(x)});\n var n = tmp[0];\n var m = tmp[1];\n var e = [];\n var vis = [];\n for(var i = 1; i <= n; i += 1) {\n e[i] = [];\n vis[i] = false;\n }\n for(var i = 1; i <= m; i += 1) {\n var tmp = readline().split(' ').map(function(x) { return parseInt(x)});\n e[tmp[0]].push(tmp[1]);\n e[tmp[1]].push(tmp[0]);\n }\n var finding = true;\n for(var i = 1; i <= n && finding; i += 1) {\n if(!vis[i]) {\n vis[i] = true;\n var vn = 1;\n var en = e[i].length;\n var stack = [i];\n while(stack.length > 0) {\n var d = stack.pop();\n for(var b in e[d]) {\n if(!vis[e[d][b]]) {\n vis[e[d][b]] = true;\n stack.push(e[d][b]);\n vn += 1;\n en += e[d].length;\n }\n }\n }\n if(en !== vn * (vn - 1)) {\n finding = false;\n }\n }\n }\n if(finding) {\n print('YES');\n } else {\n print('NO');\n }"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tlinks_count = [],\n\tlinks = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfailed = false\n\nif (m == 0) {\n\tprint(\"YES\")\n} else {\n\tfor(i = 0; i <=n; i++) {\n\t\tlinks[i] = []\n\t\tlinks_count[i] = 0\n\t}\n\n\tfor(i = 0; i < m; i++) {\n\t\tpos = ints()\n\t\tlinks_count[pos[0]] ++\n\t\tlinks_count[pos[1]] ++\n\t\tif (pos[0] < pos[1])\n\t\t\tlinks[pos[0]].push(pos[1])\n\t\telse\n\t\t\tlinks[pos[1]].push(pos[0])\n\t}\n\n\tfor (x = 1; x < n && !failed; x ++) {\n\t\ti = links[x].length - 1\n\t\twhile (i >= 0 && !failed) {\n\t\t\tfailed = links_count[x] != links_count[links[x][i]]\n\t\t\ti --\n\t\t}\n\t}\n\n\tif (failed)\n\t\tprint(\"NO\")\n\telse\n\t\tprint(\"YES\")\n}\n"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tmem = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfriend = function(x, y) {\n\t\treturn x < y ? (mem[x][y] !== undefined) : (mem[y][x] !== undefined) \n\t},\n\tfailed = false\n\nfor(i = 0; i <=n; i++) {\n\tmem[i] = {}\n}\n\nfor(i = 0; i < m; i++) {\n\tpos = ints()\n\tif (pos[0] < pos[1]) {\n\t\tx = pos[0]\n\t\ty = pos[1]\n\t} else {\n\t\tx = pos[1]\n\t\ty = pos[0]\n\t}\n\tmem[x][y] = true\n}\n\ni = 1\nwhile (i <= n && !failed) {\n\tfor (x in mem[i]) {\n\t\tfor(y in mem[x]) {\n\t\t\tif (! friend(i, y)) {\n\t\t\t\tfailed = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (failed)\n\t\t\tbreak\n\t}\n\ti ++\n}\n\nif (failed)\n\tprint(\"NO\")\nelse\n\tprint(\"YES\")\n"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tmem = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfriend = function(x, y) {\n\t\treturn x < y ? (mem[x][y] !== undefined) : (mem[y][x] !== undefined) \n\t},\n\tfailed = false\n\nif (m == 0) {\n\tprint(\"YES\")\n} else {\n\tfor(i = 0; i <=n; i++) {\n\t\tmem[i] = {}\n\t\tmem[i][i] = true\n\t}\n\n\tfor(i = 0; i < m; i++) {\n\t\tpos = ints()\n\t\tif (pos[0] < pos[1]) {\n\t\t\tx = pos[0]\n\t\t\ty = pos[1]\n\t\t} else {\n\t\t\tx = pos[1]\n\t\t\ty = pos[0]\n\t\t}\n\t\tmem[x][y] = true\n\t}\n\n\ti = 1\n\twhile (i <= n && !failed) {\n\t\tfor (x in mem[i]) {\n\t\t\tfor(y in mem[x]) {\n\t\t\t\tif (! friend(i, y)) {\n\t\t\t\t\tfailed = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (failed)\n\t\t\t\tbreak\n\t\t}\n\t\ti ++\n\t}\n\n\tif (failed)\n\t\tprint(\"NO\")\n\telse\n\t\tprint(\"YES\")\n}\n"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tmem = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfailed = false\n\nif (m == 0) {\n\tprint(\"YES\")\n} else {\n\tfor(i = 0; i <=n; i++) {\n\t\tmem[i] = 0\n\t}\n\n\tfor(i = 0; i < m; i++) {\n\t\tpos = ints()\n\t\tmem[pos[0]] ++\n\t\tmem[pos[1]] ++\n\t}\n\n\tfor (x = 1; x < n && !failed; x ++)\n\t\tfor (y = x + 1; y <= n && !failed; y ++)\n\t\t\tfailed = (mem[x] != mem[y])\n\n\tif (failed)\n\t\tprint(\"NO\")\n\telse\n\t\tprint(\"YES\")\n}\n"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tmem = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfriend = function(x, y) {\n\t\treturn mem[x][y]\n\t},\n\tfailed = false\n\nif (m == 0) {\n\tprint(\"YES\")\n} else {\n\tfor(i = 0; i <=n; i++) {\n\t\tmem[i] = []\n\t\tfor(x = 0; x <=n; x++)\n\t\t\tmem[i][x] = false\n\t}\n\n\tfor(i = 0; i < m; i++) {\n\t\tpos = ints()\n\t\tmem[pos[0]][pos[1]] = true\n\t\tmem[pos[1]][pos[0]] = true\n\t}\n\n\tfor(i = 1; i <=n && !failed; i++) {\n\t\tfor(x = 1; x <=n && !failed; x++) {\n\t\t\tfor(y = 1; y <=n && !failed; y++) {\n\t\t\t\tfailed = friend(i, x) && friend(x, y) && !friend(i, y)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (failed)\n\t\tprint(\"NO\")\n\telse\n\t\tprint(\"YES\")\n}\n"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tmem = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfriend = function(x, y) {\n\t\treturn x == y || mem[x][y]\n\t},\n\tfailed = false\n\nif (m == 0) {\n\tprint(\"YES\")\n} else {\n\tfor(i = 0; i <=n; i++) {\n\t\tmem[i] = []\n\t\tfor(x = 0; x <=n; x++)\n\t\t\tmem[i][x] = false\n\t}\n\n\tfor(i = 0; i < m; i++) {\n\t\tpos = ints()\n\t\tmem[pos[0]][pos[1]] = true\n\t}\n\n\tfor(i = 1; i <=n && !failed; i++) {\n\t\tfor(x = 1; x <=n && !failed; x++) {\n\t\t\tfor(y = 1; y <=n && !failed; y++) {\n\t\t\t\tfailed = friend(i, x) && friend(x, y) && !friend(x, y)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (failed)\n\t\tprint(\"NO\")\n\telse\n\t\tprint(\"YES\")\n}\n"}, {"source_code": "// Polyfill for NodeJS\nif (undefined == readline) {\n\tvar rLines = require('fs').readFileSync(\"/dev/stdin\", \"utf8\").split(\"\\n\"), \n\t\trIndex = 0,\n\t\treadline = function() {\n\t\t\trIndex ++\n\t\t\treturn rLines[rIndex - 1]\n\t\t}\n}\nif (undefined == print) {\n\tvar print = console.log\n}\n\n// Useful Read functions\nvar int = function() {\n\treturn parseInt(readline())\n}\n\nvar ints = function() {\n\treturn readline().split(' ')\n\t\t.map(function(x) {\n\t\t\treturn parseInt(x)\n\t\t})\n}\n\n// The answer\n\nvar ns = ints(),\n\tn = ns[0],\n\tm = ns[1]\n\tmem = [],\n\ti = 0,\n\tx = 0,\n\ty = 0,\n\tpos = [],\n\tfriend = function(x, y) {\n\t\treturn x < y ? (mem[x][y] !== undefined) : (mem[y][x] !== undefined) \n\t},\n\tfailed = false\n\nif (m == 0) {\n\tprint(\"YES\")\n} else {\n\tfor(i = 0; i <=n; i++) {\n\t\tmem[i] = {}\n\t}\n\n\tfor(i = 0; i < m; i++) {\n\t\tpos = ints()\n\t\tif (pos[0] < pos[1]) {\n\t\t\tx = pos[0]\n\t\t\ty = pos[1]\n\t\t} else {\n\t\t\tx = pos[1]\n\t\t\ty = pos[0]\n\t\t}\n\t\tmem[x][y] = true\n\t}\n\n\ti = 1\n\twhile (i <= n && !failed) {\n\t\tfor (x in mem[i]) {\n\t\t\tfor(y in mem[x]) {\n\t\t\t\tif (! friend(i, y)) {\n\t\t\t\t\tfailed = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (failed)\n\t\t\t\tbreak\n\t\t}\n\t\ti ++\n\t}\n\n\tif (failed)\n\t\tprint(\"NO\")\n\telse\n\t\tprint(\"YES\")\n}\n"}], "src_uid": "1173d89dd3af27b46e579cdeb2cfdfe5"} {"nl": {"description": "Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string $$$s$$$, you have to delete minimum number of characters from this string so that it becomes good.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.", "output_spec": "In the first line, print one integer $$$k$$$ ($$$0 \\le k \\le n$$$) — the minimum number of characters you have to delete from $$$s$$$ to make it good. In the second line, print the resulting string $$$s$$$. If it is empty, you may leave the second line blank, or not print it at all.", "sample_inputs": ["4\ngood", "4\naabc", "3\naaa"], "sample_outputs": ["0\ngood", "2\nab", "3"], "notes": null}, "positive_code": [{"source_code": "'use strict';\n\nfunction main() {\n let n = parseInt(next());\n let s = next();\n let stack = [], i = 0, res = '';\n for(i = 0; i < n; i++) {\n if((!stack.length) || s[i] != stack[stack.length-1] || stack.length % 2 == 0) {\n stack.push(s[i]);\n }\n }\n if(stack.length%2) stack.pop();\n res = stack.join('');\n println(n-res.length+'\\n'+res);\n}\n\n//process.stdin.resume();\nprocess.stdin.setEncoding('ascii');\n\nlet input = '';\nprocess.stdin.on('data', (chunk) => input += chunk);\n\n// next: reads next value from input.\nlet inputCursor = 0;\nlet next = () => {\n return inputCursor < input.length ? input[inputCursor++] : ''; \n};\n\n//print: print one or more space seperated values.\nlet print = (...data) => {\n for(let i = 0; i < data.length; i++) {\n process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));\n }\n};\n\n//println: print one or more space seperated values then a line feed.\nlet println = (...data) => {\n print(...data);\n print('\\n');\n};\n\n//after the the input is read.\nprocess.stdin.on('end', () => {\n input = input.trim().split(/[\\s]+/);\n main();\n});\n"}, {"source_code": "'use strict';\n\nfunction main() {\n let n = parseInt(next());\n let s = next();\n let i = 0;\n \n let res = '';\n let ereased = 0;\n for(i = 0; i < n; i++) {\n if(i == n-1 || s[i+1] !== s[i]) {\n res += s[i];\n } else {\n let j = i+1;\n while(j < n && s[j] === s[i]) {\n j++;\n }\n j--;\n if((i-ereased)%2 == 0) {\n res += s[i];\n ereased += j-i;\n } else {\n res += s[i]+''+s[i];\n ereased += j-i-1;\n }\n i = j;\n }\n }\n\n if(res.length%2) {\n println(n-res.length+1);\n println(res.substr(0, res.length-1));\n } else {\n println(n-res.length);\n println(res.substr(0, res.length));\n }\n}\n\n//process.stdin.resume();\nprocess.stdin.setEncoding('ascii');\n\nlet input = '';\nprocess.stdin.on('data', (chunk) => input += chunk);\n\n// next: reads next value from input.\nlet inputCursor = 0;\nlet next = () => {\n return inputCursor < input.length ? input[inputCursor++] : ''; \n};\n\n//print: print one or more space seperated values.\nlet print = (...data) => {\n for(let i = 0; i < data.length; i++) {\n process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));\n }\n};\n\n//println: print one or more space seperated values then a line feed.\nlet println = (...data) => {\n print(...data);\n print('\\n');\n};\n\n//after the the input is read.\nprocess.stdin.on('end', () => {\n input = input.trim().split(/[\\s]+/);\n main();\n});\n"}, {"source_code": "'use strict';\n\nfunction main() {\n let n = parseInt(next());\n let s = next(), res = '';\n let i = 0, j = 0, ereased = 0;\n for(i = 0; i < n; i++) {\n if(i == n-1 || s[i+1] !== s[i]) {\n res += s[i];\n } else {\n j = i+1;\n while(j < n && s[j] === s[i]) {\n j++;\n }\n j--;\n if((i-ereased)%2) {\n res += s[i]+s[i];\n ereased += j-i-1;\n } else {\n res += s[i];\n ereased += j-i;\n }\n i = j;\n }\n }\n\n println(n-res.length+res.length%2);\n println(res.substr(0, res.length-res.length%2));\n}\n\n//process.stdin.resume();\nprocess.stdin.setEncoding('ascii');\n\nlet input = '';\nprocess.stdin.on('data', (chunk) => input += chunk);\n\n// next: reads next value from input.\nlet inputCursor = 0;\nlet next = () => {\n return inputCursor < input.length ? input[inputCursor++] : ''; \n};\n\n//print: print one or more space seperated values.\nlet print = (...data) => {\n for(let i = 0; i < data.length; i++) {\n process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));\n }\n};\n\n//println: print one or more space seperated values then a line feed.\nlet println = (...data) => {\n print(...data);\n print('\\n');\n};\n\n//after the the input is read.\nprocess.stdin.on('end', () => {\n input = input.trim().split(/[\\s]+/);\n main();\n});\n"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var a = read.arr();\n var res = [a[0]];\n var length = 0;\n for(var i = 1; i < n; i++) {\n if(length % 2) {\n res.push(a[i]);\n length++;\n }\n else {\n if(res[length] !== a[i]) {\n res.push(a[i]);\n length++;\n }\n }\n }\n length += 1;\n if(length % 2) {\n length -=1;\n res.pop();\n }\n\n print(n - length);\n print(res.join(''));\n}());"}], "negative_code": [{"source_code": "'use strict';\n\nfunction main() {\n let n = parseInt(next());\n let s = next();\n let i = 0;\n \n let res = '';\n let ereased = 0;\n for(i = 0; i < n; i++) {\n if(i == n-1 || s[i+1] !== s[i]) {\n res += s[i];\n } else {\n let j = i+1;\n while(j < n && s[j] === s[i]) {\n j++;\n }\n j--;\n if((i-ereased)%2 == 0) {\n res += s[i];\n ereased += j-i;\n } else {\n res += s[i]+''+s[i];\n ereased += j-i-1;\n }\n i = j;\n }\n }\n\n if(res.length%2) {\n println(n-res.length+1);\n println(s.substr(0, res.length-1));\n } else {\n println(n-res.length);\n println(s.substr(0, res.length));\n }\n}\n\n//process.stdin.resume();\nprocess.stdin.setEncoding('ascii');\n\nlet input = '';\nprocess.stdin.on('data', (chunk) => input += chunk);\n\n// next: reads next value from input.\nlet inputCursor = 0;\nlet next = () => {\n return inputCursor < input.length ? input[inputCursor++] : ''; \n};\n\n//print: print one or more space seperated values.\nlet print = (...data) => {\n for(let i = 0; i < data.length; i++) {\n process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));\n }\n};\n\n//println: print one or more space seperated values then a line feed.\nlet println = (...data) => {\n print(...data);\n print('\\n');\n};\n\n//after the the input is read.\nprocess.stdin.on('end', () => {\n input = input.trim().split(/[\\s]+/);\n main();\n});\n"}], "src_uid": "c11d67f223eb49c6e8315e2c88dd680d"} {"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 ≤ k ≤ n ≤ 106) — the number of segments and the value of k. The next n lines contain two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109) each — 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 — the smallest number of segments. Next m lines contain two integers aj, bj (aj ≤ bj) — 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": "!function(n){function __webpack_require__(e){if(r[e])return r[e].exports;var t=r[e]={exports:{},id:e,loaded:!1};return n[e].call(t.exports,t,t.exports,__webpack_require__),t.loaded=!0,t.exports}var r={};return __webpack_require__.m=n,__webpack_require__.c=r,__webpack_require__.p=\"\",__webpack_require__(0)}([function(n,r,e){n.exports=e(1)},function(n,r){\"use strict\";function solve(){function calculate(n,r,e){e.sort(function(n,r){return r-n});for(var t=[],u=null,l=Math.floor(e[0]/9),a=0,o=0,i=0,p=0,_=null,c=null,s=null,f=e.length,v=0;f>v;v++)_=e.pop(),c=Math.floor(_/9),s=_%9,0>s&&(s+=9),l===c?0===s?++p:1===s?++o:++i:(a+=o-i,null==u?a>=r?u=l:a+p+i>=r&&t.push([l,l]):r>a&&(t.push([u,l]),u=null),l=c,p=0,o=0,i=0,0===s?++p:1===s?++o:++i);return e=[],a+=o-i,null==u?a+p+i>=r&&t.push([l,l]):r>a&&t.push([u,l]),t}function datainp(){var t=function parseint(n){return parseInt(n)},u=readline().split(\" \").map(t);n=u[0],r=u[1];var l=null,a=null;e=new Array(2*n);for(var o=0,i=null,p=0;n>p;p++)i=readline().split(\" \"),l=parseInt(i[0]),a=parseInt(i[1]),l===a?e[o++]=9*l:(e[o++]=9*l+1,e[o++]=9*a+2);e.length=o}function resout(n){var r=n.length;print(r),print(n.map(function(n){return n.join(\" \")}).join(\"\\n\"))}var n=null,r=null,e=null;datainp();var t=calculate(n,r,e);resout(t)}solve()}]);"}], "negative_code": [{"source_code": "!function(r){function __webpack_require__(n){if(e[n])return e[n].exports;var u=e[n]={exports:{},id:n,loaded:!1};return r[n].call(u.exports,u,u.exports,__webpack_require__),u.loaded=!0,u.exports}var e={};return __webpack_require__.m=r,__webpack_require__.c=e,__webpack_require__.p=\"\",__webpack_require__(0)}([function(r,e,n){r.exports=n(1)},function(r,e){\"use strict\";function solve(r,e,n){function calculate(r,e,n){for(var u=null,t=null,l=null,a=new Array(2*r),o=0,_=0;r>_;_++)l=n[_],u=l[0],t=l[1],u===t?a[o++]=9*u:(a[o++]=9*u+1,a[o++]=9*t+2);a.length=o,a.sort(function(r,e){return r-e});var i=[];u=null;for(var p=Math.floor(a[0]/9),c=0,s=0,f=null,v=null,h=null,w=a.length,_=0;w>_;_++)f=a[_],v=Math.floor(f/9),p===v?(h=f%9,0>h&&(h+=9),2===h&&(h=-1),c+=h,0===h&&++s):(null==u?c>=e?u=p:c+s>=e&&i.push([p,p]):e>c&&(i.push([u,p]),u=null),p=v,h=f%9,0>h&&(h+=9),2===h&&(h=-1),c+=h,0===h&&++s);return null==u?c+s>=e&&i.push([p,p]):i.push([u,p]),i}function resout(r){var e=r.length;print(e),print(r.map(function(r){return r.join(\" \")}).join(\"\\n\"))}var u=calculate(r,e,n);resout(u)}for(var n=function parseint(r){return parseInt(r)},u=readline().split(\" \").map(n),t=u[0],l=u[1],a=new Array(t),o=0;t>o;o++)a[o]=readline().split(\" \").map(n);solve(t,l,a)}]);"}, {"source_code": "!function(r){function __webpack_require__(n){if(e[n])return e[n].exports;var t=e[n]={exports:{},id:n,loaded:!1};return r[n].call(t.exports,t,t.exports,__webpack_require__),t.loaded=!0,t.exports}var e={};return __webpack_require__.m=r,__webpack_require__.c=e,__webpack_require__.p=\"\",__webpack_require__(0)}([function(r,e,n){r.exports=n(1)},function(r,e){\"use strict\";function solve(r,e,n){function calculate(r,e,n){for(var t=null,u=null,l=null,a=new Array(2*r),o=0,_=0;r>_;_++)l=n[_],t=l[0],u=l[1],t===u?a[o++]=9*t:(a[o++]=9*t+1,a[o++]=9*u+2);a.length=o,a.sort(function(r,e){return r-e});var i=[];t=null;for(var p=Math.floor(a[0]/9),c=0,s=0,f=0,h=0,v=null,w=null,x=null,d=a.length,_=0;d>_;_++)v=a[_],w=Math.floor(v/9),x=v%9,0>x&&(x+=9),p===w?0===x?++h:1===x?++s:++f:(c+=s-f,null==t?c>=e?t=p:c+h+Math.max(0,f-s)>=e&&i.push([p,p]):e>c&&(i.push([t,p]),t=null),p=w,h=0,s=0,f=0,0===x?++h:1===x?++s:++f);return c+=s-f,null==t?c+h+Math.max(0,f-s)>=e&&i.push([p,p]):e>c&&i.push([t,p]),i}function resout(r){var e=r.length;print(e),print(r.map(function(r){return r.join(\" \")}).join(\"\\n\"))}var t=calculate(r,e,n);resout(t)}for(var n=function parseint(r){return parseInt(r)},t=readline().split(\" \").map(n),u=t[0],l=t[1],a=new Array(u),o=0;u>o;o++)a[o]=readline().split(\" \").map(n);solve(u,l,a)}]);"}], "src_uid": "eafd37afb15f9f9d31c2a16a32f17763"} {"nl": {"description": "Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.", "input_spec": "The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.", "output_spec": "Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.", "sample_inputs": ["2 2\n1 0\n1 1\n1 1", "4 5\n0 0 1 0 1\n0 1 1 1 0\n1 0 1 0 1\n1 1 1 1 1\n2 3"], "sample_outputs": ["0", "2"], "notes": "NoteIn the second example the upper left square is (1,1) and the lower right is (3,2)."}, "positive_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nlet N = lll[0]\nlet M = lll[1]\n\nlet s = []\nwhile (lll = readline()) {\n s.push(lll.split(' ').map(v => parseInt(v)))\n}\n\nlet ab = s.pop()\nlet A = ab[0]\nlet B = ab[1]\n\nlet min = Infinity\n\nfor (let y = 0; y <= N - A; y++) {\n for (let x = 0; x <= M - B; x++) {\n let ts = 0\n d: for (let dy = 0; dy < A; dy++) {\n for (let dx = 0; dx < B; dx++) {\n if (s[y + dy][x + dx] == 1) ts++\n if (ts >= min) break d\n }\n }\n if (ts < min) min = ts\n }\n}\n\nfor (let y = 0; y <= N - B; y++) {\n for (let x = 0; x <= M - A; x++) {\n let ts = 0\n d: for (let dy = 0; dy < B; dy++) {\n for (let dx = 0; dx < A; dx++) {\n if (s[y + dy][x + dx] == 1) ts++\n if (ts >= min) break d\n }\n }\n if (ts < min) min = ts\n }\n}\n\nprint(min)"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar calculateTrees = function (cont, startRow, endRow, startCol, endCol) {\n let ans = 0;\n for (let i = startRow; i < endRow; i++)\n for (let j = startCol; j < endCol; j++)\n ans += cont[i][j];\n\n //console.log(\" startRow=%d endRow=%d startCol=%d endCol=%d ans=%d\",startRow, endRow, startCol, endCol,ans);\n return ans;\n}\n\nvar indicator = 0, N, M, temp, cont = [], HouseX, HouseY;\nrl.on('line', (input) => {\n if (indicator == 0) {\n temp = input.split(\" \").map(item => parseInt(item));\n N = temp[0];\n M = temp[1];\n indicator++;\n }\n else if (indicator <= N) {\n cont.push(input.split(\" \").map(item => parseInt(item)));\n indicator++;\n }\n else {\n temp = input.split(\" \").map(item => parseInt(item));\n HouseX = temp[0];\n HouseY = temp[1];\n }\n}).on('close', () => {\n let ans = N * M, helper;\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < M; j++) {\n if (i + HouseX <= N && j + HouseY <= M) {\n helper = calculateTrees(cont, i, i + HouseX, j, j + HouseY);\n if (ans > helper)\n ans = helper;\n }\n if (i + HouseY <= N && j + HouseX <= M) {\n helper = calculateTrees(cont, i, i + HouseY, j, j + HouseX);\n if (ans > helper)\n ans = helper;\n }\n }\n }\n console.log(ans);\n});"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar calculateTrees = (cont, startRow, endRow, startCloumn, endColumn) => {\n let ans = 0;\n for (let i = startRow; i < endRow; i++)\n for (let j = startCloumn; j < endColumn; j++)\n if (cont[i][j] == 1)\n ans += cont[i][j];\n return ans;\n}\nvar N, M, cont = [], houseX, houseY, indicator = 0, temp = [];\nrl.on('line', (input) => {\n if (indicator == 0) {\n temp = input.split(' ').map(item => parseInt(item));\n N = temp[0], M = temp[1];\n indicator++;\n } else if (indicator <= N) {\n cont.push(input.split(' ').map(item => parseInt(item)));\n indicator++;\n } else {\n temp = input.split(' ').map(item => parseInt(item));\n houseX = temp[0], houseY = temp[1];\n }\n}).on(\"close\", () => {\n let ans = N * M, helper;\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < M; j++) {\n if (i + houseX <= N && j + houseY <= M) {\n helper = calculateTrees(cont, i, i + houseX, j, j + houseY);\n if (ans > helper)\n ans = helper;\n }\n if (i + houseY <= N && j + houseX <= M) {\n helper = calculateTrees(cont, i, i + houseY, j, j + houseX);\n if (ans > helper)\n ans = helper;\n }\n }\n }\n console.log(ans);\n});"}], "negative_code": [{"source_code": "var getArr = function() {\n\treturn readline().split(' ').map(function (a) {\n\t\treturn parseInt(a);\n\t})\n};\n\nvar getTree = function(arr, x, y, a, b) {\n\tvar res = 0;\n\tfor (var i = 0; i < a; i++) {\n\t\tfor (var j = 0; j < b; j++) {\n\t\t\tres += arr[x + i][y + j];\n\t\t}\n\t}\n\treturn res;\n};\n\nvar data = [];\nvar input;\n\ninput = getArr();\nvar m = input[0];\nvar n = input[1];\nfor (var k = 0; k < m; k++) {\n\tdata.push(getArr());\n}\ninput = getArr();\nvar a = input[0];\nvar b = input[1];\n\nvar min = getTree(data, 0, 0, a, b);\nfor (var i = 0; i < m - a + 1; i++) {\n\tfor (var j = 0; j < n - b + 1; j++) {\n\t\tmin = Math.min(min, getTree(data, i, j, a, b));\n\t}\n}\n\nprint(min);"}], "src_uid": "1771741663a5236a0aa0551548f4aadd"} {"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 × m. 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 ≤ n ≤ 1000; 2 ≤ m ≤ 1000). Next n lines each contain m characters — 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 — 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": "print(function(n, m){\n\tvar a=[];\n\tfor(var i=0; i a-b );\n\tvar count = 0;\n\tfor (var i=0; i a-b );\n\tvar count = 0;\n\tfor (var i=0; i= n) ans = a[n-1];\nelse {\n for(var i=0;i ans) ans = tmp;\n }\n for(var i=2*n-2*k;i ans) ans = a[i];\n }\n}\nprint(ans);"}], "negative_code": [], "src_uid": "7324428d9e6d808f55ad4f3217046455"} {"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 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), 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 — 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": "var n = +readline(), a = readline().split(\" \").map(Number);\nvar x = 0, bool = [], proof;\n\nfor(var i = 0; i < n; i++){\n\tbool[i] = true;\n}\n\nfor(var i = 0; ;i++){\n\tproof = true;\n\n\tfor(var j = 0; j < n; j++){\n\t\tif(a[j] <= x){\n\t\t\tif(bool[j]){\n\t\t\t\tx++;\n\t\t\t\tbool[j] = false;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tproof = false;\n\t\t}\n\t}\n\n\tif(proof){\n\t\twrite(i);\n\t\tbreak;\n\t}\n\n\ta = a.reverse();\n\tbool = bool.reverse();\n}"}, {"source_code": "/******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n\n\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar List = __webpack_require__(1);\n\tvar n = List.map(parseInt, readline().split(' '))[0];\n\tvar a = List.map(parseInt, readline().split(' '));\n\tvar level = 0;\n\tvar changes = 0;\n\tvar i = 0;\n\tvar di = 1;\n\twhile (true) {\n\t while (i >= 0 && i < n) {\n\t if (a[i] <= level) {\n\t level++;\n\t a[i] = n + 1;\n\t }\n\t i += di;\n\t }\n\t if (level == n)\n\t break;\n\t i -= di;\n\t di = -di;\n\t changes++;\n\t}\n\tprint(changes);\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar Prelude_1 = __webpack_require__(2);\n\tfunction add(xs, ys) {\n\t return xs.concat(ys);\n\t}\n\texports.add = add;\n\tfunction head(xs) {\n\t return xs[0];\n\t}\n\texports.head = head;\n\tfunction last(xs) {\n\t return xs[xs.length - 1];\n\t}\n\texports.last = last;\n\tfunction tail(xs) {\n\t return xs.slice(1);\n\t}\n\texports.tail = tail;\n\tfunction init(xs) {\n\t return xs.slice(0, xs.length - 1);\n\t}\n\texports.init = init;\n\tfunction map(f, xs) {\n\t var result = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t result[i] = f(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.map = map;\n\tfunction reverse(xs) {\n\t return xs.slice().reverse();\n\t}\n\texports.reverse = reverse;\n\tfunction intersperse(x, xs) {\n\t if (xs.length == 0) {\n\t return [];\n\t }\n\t var result = new Array(xs.length + xs.length - 1);\n\t for (var i = 0; i + 1 < xs.length; i++) {\n\t result[i + i] = xs[i];\n\t result[i + i + 1] = x;\n\t }\n\t result[result.length - 1] = xs[xs.length - 1];\n\t return result;\n\t}\n\texports.intersperse = intersperse;\n\tfunction intercalate(xs, xss) {\n\t return concat(intersperse(xs, xss));\n\t}\n\texports.intercalate = intercalate;\n\tfunction foldl(f, initial, xs) {\n\t var result = initial;\n\t for (var i = 0; i < xs.length; i++) {\n\t result = f(result, xs[i]);\n\t }\n\t return result;\n\t}\n\texports.foldl = foldl;\n\tfunction foldr(f, initial, xs) {\n\t var result = initial;\n\t for (var i = xs.length - 1; i >= 0; i--) {\n\t result = f(xs[i], result);\n\t }\n\t return result;\n\t}\n\texports.foldr = foldr;\n\tfunction concat(xss) {\n\t var total = sum(map(function (xs) { return xs.length; }, xss));\n\t var result = new Array(total);\n\t var m = 0;\n\t for (var i = 0; i < xss.length; i++) {\n\t var xs = xss[i];\n\t for (var j = 0; j < xs.length; j++) {\n\t result[m++] = xs[j];\n\t }\n\t }\n\t return result;\n\t}\n\texports.concat = concat;\n\tfunction sum(xs) {\n\t var result = 0;\n\t for (var i = 0; i < xs.length; i++) {\n\t result += xs[i];\n\t }\n\t return result;\n\t}\n\texports.sum = sum;\n\tfunction product(xs) {\n\t var result = 1;\n\t for (var i = 0; i < xs.length; i++) {\n\t result *= xs[i];\n\t }\n\t return result;\n\t}\n\texports.product = product;\n\tfunction sort(xs, compare) {\n\t return copy(xs).sort(compare);\n\t}\n\texports.sort = sort;\n\tfunction sortInPlace(xs, compare) {\n\t xs.sort(compare);\n\t return xs;\n\t}\n\texports.sortInPlace = sortInPlace;\n\tfunction maximumInRange(xs, s, e) {\n\t var result = xs[s];\n\t for (var i = s + 1; i <= e; i++) {\n\t if (result < xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.maximumInRange = maximumInRange;\n\tfunction maximum(xs) {\n\t return maximumInRange(xs, 0, xs.length - 1);\n\t}\n\texports.maximum = maximum;\n\tfunction maximumInRangeWith(xs, s, e, f) {\n\t var result = f(xs[s]);\n\t for (var i = s + 1; i <= e; i++) {\n\t var candidate = f(xs[i]);\n\t if (result < candidate)\n\t result = candidate;\n\t }\n\t return result;\n\t}\n\texports.maximumInRangeWith = maximumInRangeWith;\n\tfunction maximumWith(xs, f) {\n\t return maximumInRangeWith(xs, 0, xs.length - 1, f);\n\t}\n\texports.maximumWith = maximumWith;\n\tfunction minimumInRange(xs, s, e) {\n\t var result = xs[s];\n\t for (var i = s + 1; i <= e; i++) {\n\t if (result > xs[i])\n\t result = xs[i];\n\t }\n\t return result;\n\t}\n\texports.minimumInRange = minimumInRange;\n\tfunction minimum(xs) {\n\t return minimumInRange(xs, 0, xs.length - 1);\n\t}\n\texports.minimum = minimum;\n\tfunction minimumInRangeWith(xs, s, e, f) {\n\t var result = f(xs[s]);\n\t for (var i = s + 1; i <= e; i++) {\n\t var candidate = f(xs[i]);\n\t if (result > candidate)\n\t result = candidate;\n\t }\n\t return result;\n\t}\n\texports.minimumInRangeWith = minimumInRangeWith;\n\tfunction minimumWith(xs, f) {\n\t return minimumInRangeWith(xs, 0, xs.length - 1, f);\n\t}\n\texports.minimumWith = minimumWith;\n\tfunction replicate(n, x) {\n\t var result = new Array(n);\n\t for (var i = 0; i < result.length; i++) {\n\t result[i] = x;\n\t }\n\t return result;\n\t}\n\texports.replicate = replicate;\n\tfunction take(n, xs) {\n\t return xs.slice(0, n);\n\t}\n\texports.take = take;\n\tfunction drop(n, xs) {\n\t return xs.slice(n);\n\t}\n\texports.drop = drop;\n\tfunction splitAt(n, xs) {\n\t return [take(n, xs), drop(n, xs)];\n\t}\n\texports.splitAt = splitAt;\n\tfunction takeWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(0, i);\n\t }\n\t }\n\t return xs.slice();\n\t}\n\texports.takeWhile = takeWhile;\n\tfunction dropWhile(f, xs) {\n\t for (var i = 0; i < xs.length; i++) {\n\t if (!f(xs[i])) {\n\t return xs.slice(i);\n\t }\n\t }\n\t return [];\n\t}\n\texports.dropWhile = dropWhile;\n\tfunction group(xs) {\n\t if (xs.length == 0)\n\t return [];\n\t var result = [];\n\t var last = [xs[0]];\n\t for (var i = 1; i < xs.length; i++) {\n\t if (last[0] === xs[i]) {\n\t last.push(xs[i]);\n\t }\n\t else {\n\t result.push(last);\n\t last = [xs[i]];\n\t }\n\t }\n\t result.push(last);\n\t return result;\n\t}\n\texports.group = group;\n\tfunction nub(xs) {\n\t if (xs.length == 0)\n\t return [];\n\t var result = [];\n\t result.push(xs[0]);\n\t for (var i = 1; i < xs.length; i++) {\n\t if (xs[i] !== xs[i - 1]) {\n\t result.push(xs[i]);\n\t }\n\t }\n\t return result;\n\t}\n\texports.nub = nub;\n\tfunction filter(f, xs) {\n\t var result = [];\n\t for (var i = 0; i < xs.length; i++) {\n\t if (f(xs[i]))\n\t result.push(xs[i]);\n\t }\n\t return result;\n\t}\n\texports.filter = filter;\n\tfunction zip(xs, ys) {\n\t var n = Prelude_1.min(xs.length, ys.length);\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = [xs[i], ys[i]];\n\t }\n\t return result;\n\t}\n\texports.zip = zip;\n\tfunction unzip(xs) {\n\t var r1 = new Array(xs.length);\n\t var r2 = new Array(xs.length);\n\t for (var i = 0; i < xs.length; i++) {\n\t r1[i] = xs[i][0];\n\t r2[i] = xs[i][1];\n\t }\n\t return [r1, r2];\n\t}\n\texports.unzip = unzip;\n\tfunction range(from, to) {\n\t var result = Array(to - from + 1);\n\t for (var i = from; i <= to; i++) {\n\t result[i - from] = i;\n\t }\n\t return result;\n\t}\n\texports.range = range;\n\tfunction copy(xs) {\n\t return xs.slice(0);\n\t}\n\texports.copy = copy;\n\tfunction apply_permutation(p, xs) {\n\t var n = xs.length;\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = xs[p[i]];\n\t }\n\t return result;\n\t}\n\texports.apply_permutation = apply_permutation;\n\tfunction next_permutation(p) {\n\t var n = p.length;\n\t if (n < 2)\n\t return null;\n\t var r = copy(p);\n\t var k = n - 2;\n\t for (; k >= 0 && r[k] >= r[k + 1]; k--)\n\t ;\n\t if (k < 0)\n\t return null;\n\t for (var i = k + 1, j = n - 1; i < j; i++, j--) {\n\t var t_1 = r[i];\n\t r[i] = r[j];\n\t r[j] = t_1;\n\t }\n\t var next = k + 1;\n\t for (; r[next] <= r[k]; next++)\n\t ;\n\t var t = r[k];\n\t r[k] = r[next];\n\t r[next] = t;\n\t return r;\n\t}\n\texports.next_permutation = next_permutation;\n\tfunction create(n, value) {\n\t return replicate(n, value);\n\t}\n\texports.create = create;\n\tfunction createWith(n, f) {\n\t var result = new Array(n);\n\t for (var i = 0; i < n; i++) {\n\t result[i] = f(i);\n\t }\n\t return result;\n\t}\n\texports.createWith = createWith;\n\tfunction create2D(n1, n2, value) {\n\t return map(function (_) { return replicate(n2, value); }, replicate(n1, 0));\n\t}\n\texports.create2D = create2D;\n\tfunction create2DWith(n1, n2, f) {\n\t var result = new Array(n1);\n\t for (var i = 0; i < n1; i++) {\n\t result[i] = new Array(n2);\n\t for (var j = 0; j < n2; j++) {\n\t result[i][j] = f(i, j);\n\t }\n\t }\n\t return result;\n\t}\n\texports.create2DWith = create2DWith;\n\n\n/***/ },\n/* 2 */\n/***/ function(module, exports) {\n\n\tfunction min(a, b) {\n\t return a < b ? a : b;\n\t}\n\texports.min = min;\n\tfunction max(a, b) {\n\t return a < b ? b : a;\n\t}\n\texports.max = max;\n\tfunction curry(f) {\n\t return function (x) { return function (y) { return f(x, y); }; };\n\t}\n\texports.curry = curry;\n\tfunction uncurry(f) {\n\t return function (x, y) { return f(x)(y); };\n\t}\n\texports.uncurry = uncurry;\n\tfunction id(x) {\n\t return x;\n\t}\n\texports.id = id;\n\tfunction constant(x) {\n\t return function (_) { return x; };\n\t}\n\texports.constant = constant;\n\tfunction flip(f) {\n\t return function (y) { return function (x) { return f(x)(y); }; };\n\t}\n\texports.flip = flip;\n\tfunction flip2(f) {\n\t return function (y, x) { return f(x, y); };\n\t}\n\texports.flip2 = flip2;\n\tfunction compose(g, f) {\n\t return function (x) { return g(f(x)); };\n\t}\n\texports.compose = compose;\n\tfunction gcd(a, b) {\n\t var r = a % b;\n\t while (r !== 0) {\n\t a = b;\n\t b = r;\n\t r = a % b;\n\t }\n\t return b;\n\t}\n\texports.gcd = gcd;\n\n\n/***/ }\n/******/ ]);"}, {"source_code": "'use strict';\n\n/*let input = `\n7\n0 3 1 0 5 2 6\n`.trim().split('\\n');\nfunction print(output) {\n\tconsole.log(output);\n}\nfunction readline() {\n\treturn input.shift();\n}\n*/\n//code\n\nvar n = Number(readline());\nvar coveredComputers = [],\n directionChanges = 0,\n i = 0,\n direction = 1;\nvar infoRequired = readline().split(' ').map(Number);\n\nwhile (coveredComputers.length != n) {\n\tif (i >= n || i < 0) {\n\t\tdirection *= -1;\n\t\tdirectionChanges++;\n\t\ti += direction * 2;\n\t}\n\tif (coveredComputers.indexOf(i) === -1) {\n\t\tif (infoRequired[i] <= coveredComputers.length) {\n\t\t\tcoveredComputers.push(i);\n\t\t}\n\t}\n\ti += direction;\n}\nprint(directionChanges);\n"}, {"source_code": "n = readline();\na = readline().split(\" \").map(Number);\n\nanswer = -1;\nhacked = 0;\n\nwhile (hacked < n) {\n\tanswer += 1;\n\tif (answer % 2 == 0) {\n\t\t// right\n\t\tfor (var i = 0; i < a.length; i++) {\n\t\t\tif (a[i] <= hacked && a[i] != -1) {\n\t\t\t\ta[i] = -1;\n\t\t\t\thacked += 1;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (var i = a.length-1; i >= 0; --i) {\n\t\t\tif (a[i] <= hacked && a[i] != -1) {\n\t\t\t\ta[i] = -1;\n\t\t\t\thacked += 1;\n\t\t\t}\t\n\t\t}\n\t}\n\n}\n\nwrite(answer);"}], "negative_code": [], "src_uid": "9374728643a1ddbe2200a4a125beef26"} {"nl": {"description": "You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \\ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2\\le n\\le 2\\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\\le u,v\\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree.", "output_spec": "In the first line print two integers  — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \\ldots, w_n$$$ ($$$1\\le w_i\\le 10^9$$$)  — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any.", "sample_inputs": ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"], "sample_outputs": ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"], "notes": "NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment."}, "positive_code": [{"source_code": "const fs=require('fs')\r\nconst input=fs\r\n .readFileSync(0,'utf-8')\r\n .split('\\n')\r\n .map(line=>line.split(' ').map(Number))\r\nmain(input)\r\n\r\nfunction main(input) {\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(2, 2)\r\n console.log(`1 1`)\r\n return [2, 2, [1, 1]]\r\n }\r\n const g = new Array(n).fill(0).map(() => new Set())\r\n const p = new Array(n).fill(-1)\r\n const d = []\r\n const root = 0 //Math.floor(Math.random() * n)\r\n for (let i = 1; i < n; i++) {\r\n const [u, v] = input[i]\r\n g[u - 1].add(v - 1)\r\n g[v - 1].add(u - 1)\r\n }\r\n let queue = [[root, 0]],\r\n st = []\r\n st[root] = 1\r\n for (let [node, depth] of queue) {\r\n if (!d[depth]) d[depth] = new Set()\r\n d[depth].add(node)\r\n for (let child of g[node]) {\r\n if (st[child]) continue\r\n queue.push([child, depth + 1])\r\n p[child] = node\r\n st[child] = 1\r\n }\r\n }\r\n\r\n const dp = new Array(n).fill(0).map((_, i) => [\r\n [0, 1],\r\n [1, i === root ? 0 : 1],\r\n ]),\r\n dp1 = new Array(n).fill(0).map(() => [])\r\n for (let i = d.length - 1; i > 0; i--) {\r\n for (let node of d[i]) {\r\n const cur = dp[node],\r\n parent = dp[p[node]]\r\n\r\n for (let state of [0, 1]) {\r\n dp1[node][state] = state ^ 1\r\n if (state) {\r\n let [[count0, sum0]] = cur\r\n parent[1][0] += count0\r\n parent[1][1] += sum0 + 1\r\n } else {\r\n let [[count0, sum0], [count1, sum1]] = cur\r\n if (count0 < count1 || (count0 === count1 && sum0 > sum1)) {\r\n count0 = count1\r\n sum0 = sum1\r\n } else {\r\n dp1[node][state] = 0\r\n }\r\n parent[0][0] += count0\r\n parent[0][1] += sum0\r\n }\r\n }\r\n }\r\n }\r\n\r\n const isGood = []\r\n const [root0, root1] = dp[0]\r\n isGood[root] = root1[0] > root0[0] || (root1[0] === root0[0] && root1[1] < root0[1]) ? 1 : 0\r\n queue = [root]\r\n st = []\r\n st[root] = 1\r\n for (let node of queue) {\r\n for (let child of g[node]) {\r\n if (st[child]) continue\r\n st[child] = 1\r\n isGood[child] = dp1[child][isGood[node]]\r\n queue.push(child)\r\n }\r\n }\r\n let res = new Array(n).fill(0)\r\n for (let i = 0; i < n; i++) {\r\n if (isGood[i] === 0) {\r\n res[i] = 1\r\n for (let node of g[i]) {\r\n if (isGood[node] === 1) res[node]++\r\n }\r\n }\r\n }\r\n const [max, sum] = dp[root][isGood[root]]\r\n console.log(max, sum)\r\n console.log(res.join(' '))\r\n return [max, sum, res]\r\n}"}, {"source_code": "const readline = require('readline')\r\nconst rl = readline.createInterface({\r\n output: process.stdout,\r\n input: process.stdin,\r\n})\r\nconst input = []\r\nrl.on('line', line => input.push(line.split(' ').map(Number)))\r\nrl.on('close', () => {\r\n main(input)\r\n})\r\n\r\nfunction main(input) {\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(2, 2)\r\n console.log(`1 1`)\r\n return [2, 2, [1, 1]]\r\n }\r\n const g = new Array(n).fill(0).map(() => new Set())\r\n const p = new Array(n).fill(-1)\r\n const d = []\r\n const root = 0 //Math.floor(Math.random() * n)\r\n for (let i = 1; i < n; i++) {\r\n const [u, v] = input[i]\r\n g[u - 1].add(v - 1)\r\n g[v - 1].add(u - 1)\r\n }\r\n let queue = [[root, 0]],\r\n st = []\r\n st[root] = 1\r\n for (let [node, depth] of queue) {\r\n if (!d[depth]) d[depth] = new Set()\r\n d[depth].add(node)\r\n for (let child of g[node]) {\r\n if (st[child]) continue\r\n queue.push([child, depth + 1])\r\n p[child] = node\r\n st[child] = 1\r\n }\r\n }\r\n\r\n const dp = new Array(n).fill(0).map((_, i) => [\r\n [0, 1],\r\n [1, i === root ? 0 : 1],\r\n ]),\r\n dp1 = new Array(n).fill(0).map(() => [])\r\n for (let i = d.length - 1; i > 0; i--) {\r\n for (let node of d[i]) {\r\n const cur = dp[node],\r\n parent = dp[p[node]]\r\n\r\n for (let state of [0, 1]) {\r\n dp1[node][state] = state ^ 1\r\n if (state) {\r\n let [[count0, sum0]] = cur\r\n parent[1][0] += count0\r\n parent[1][1] += sum0 + 1\r\n } else {\r\n let [[count0, sum0], [count1, sum1]] = cur\r\n if (count0 < count1 || (count0 === count1 && sum0 > sum1)) {\r\n count0 = count1\r\n sum0 = sum1\r\n } else {\r\n dp1[node][state] = 0\r\n }\r\n parent[0][0] += count0\r\n parent[0][1] += sum0\r\n }\r\n }\r\n }\r\n }\r\n\r\n const isGood = []\r\n const [root0, root1] = dp[0]\r\n isGood[root] = root1[0] > root0[0] || (root1[0] === root0[0] && root1[1] < root0[1]) ? 1 : 0\r\n queue = [root]\r\n st = []\r\n st[root] = 1\r\n for (let node of queue) {\r\n for (let child of g[node]) {\r\n if (st[child]) continue\r\n st[child] = 1\r\n isGood[child] = dp1[child][isGood[node]]\r\n queue.push(child)\r\n }\r\n }\r\n let res = new Array(n).fill(0)\r\n for (let i = 0; i < n; i++) {\r\n if (isGood[i] === 0) {\r\n res[i] = 1\r\n for (let node of g[i]) {\r\n if (isGood[node] === 1) res[node]++\r\n }\r\n }\r\n }\r\n const [max, sum] = dp[root][isGood[root]]\r\n console.log(max, sum)\r\n console.log(res.join(' '))\r\n return [max, sum, res]\r\n}"}], "negative_code": [{"source_code": "const readline = require('readline')\r\nconst rl = readline.createInterface({\r\n output: process.stdout,\r\n input: process.stdin,\r\n})\r\nconst input = []\r\nrl.on('line', line => input.push(line.split(' ').map(Number)))\r\nrl.on('close', () => {\r\n main(input)\r\n})\r\n\r\nfunction main(input) {\r\n function debug(str) {\r\n console.log(str)\r\n }\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(2, 2)\r\n console.log('1 1')\r\n return [2, 2, [1, 1]]\r\n }\r\n debug('构建图')\r\n const g = new Array(n).fill(0).map(() => new Set()),\r\n d = new Array(n).fill(0)\r\n const add = (i, j) => {\r\n g[i].add(j)\r\n d[j]++\r\n }\r\n for (let i = 1; i < n; i++) {\r\n const [u, v] = input[i]\r\n add(u - 1, v - 1)\r\n add(v - 1, u - 1)\r\n }\r\n\r\n debug('查找 root')\r\n let root = -1\r\n for (let i = 0, max = Infinity; i < n; i++) {\r\n if (d[i] < max) {\r\n max = d[i]\r\n root = i\r\n }\r\n }\r\n\r\n debug('构建树')\r\n const tree = new Array(n).fill(0).map(() => new Set()),\r\n st = []\r\n let queue = [root]\r\n st[root] = 1\r\n for (let root of queue) {\r\n for (let child of g[root]) {\r\n if (st[child]) continue\r\n st[child] = 1\r\n queue.push(child)\r\n tree[root].add(child)\r\n }\r\n }\r\n\r\n debug('查找最多好顶点数')\r\n const cache = new Array(n).fill(0).map(() => [])\r\n const dfs = (i, isGood) => {\r\n if (cache[i][isGood]) return cache[i][isGood]\r\n let state = isGood ^ 1\r\n let res = isGood ^ 1,\r\n sum = i === root ? 0 : 1\r\n for (let child of tree[i]) {\r\n const [r1, s1] = dfs(child, isGood ^ 1)\r\n res += r1\r\n sum += s1\r\n if (state) sum++\r\n }\r\n\r\n if (!isGood) {\r\n let max = 0,\r\n sum2 = 1\r\n for (let child of tree[i]) {\r\n const [r1, s1] = dfs(child, isGood)\r\n max += r1\r\n sum2 += s1\r\n }\r\n if (res < max) {\r\n res = max\r\n sum = sum2\r\n state = 0\r\n } else if (res === max && sum >= sum2) {\r\n sum = sum2\r\n state = 0\r\n }\r\n }\r\n\r\n cache[i][isGood] = [res, sum, state]\r\n return [res, sum]\r\n }\r\n\r\n dfs(root, 0)\r\n\r\n debug('对所有点进行分类')\r\n const colors = new Array(n).fill(0)\r\n const dfs2 = (node, state) => {\r\n colors[node] = cache[node][state][2]\r\n for (let child of tree[node]) {\r\n dfs2(child, colors[node])\r\n }\r\n }\r\n dfs2(root, 0)\r\n\r\n debug('统计两种情况总数')\r\n let s0 = 0,\r\n s1 = 0\r\n for (let i = 0; i < n; i++) {\r\n if (colors[i] === 0) s0++\r\n else s1++\r\n }\r\n let min = s0 > s1 ? 1 : 0\r\n let res = new Array(n).fill(0)\r\n for (let i = 0; i < n; i++) {\r\n if (colors[i] === min) {\r\n res[i] = 1\r\n for (let j of g[i]) {\r\n if (colors[j] === 0) continue\r\n res[j] += 1\r\n }\r\n }\r\n }\r\n\r\n debug('计算最小权重和')\r\n let sum = 0\r\n for (let i = 0; i < n; i++) {\r\n sum += res[i]\r\n }\r\n\r\n console.log(s1, sum)\r\n console.log(res.join(' '))\r\n return [s1, sum, res]\r\n}"}, {"source_code": "const readline = require('readline')\r\nconst rl = readline.createInterface({\r\n output: process.stdout,\r\n input: process.stdin,\r\n})\r\nconst input = []\r\nrl.on('line', line => input.push(line.split(' ').map(Number)))\r\nrl.on('close', () => {\r\n main(input)\r\n})\r\nfunction main(input){\r\n console.log(input)\r\n}"}, {"source_code": "const readline = require('readline')\r\nconst rl = readline.createInterface({\r\n output: process.stdout,\r\n input: process.stdin,\r\n})\r\nconst input = []\r\nrl.on('data', line => input.push(line.split(' ').map(Number)))\r\nrl.on('close', () => {\r\n main(input)\r\n})\r\n\r\nfunction main(input){\r\n console.log(input)\r\n}"}, {"source_code": "const fs = require('fs')\r\nconst input = fs\r\n .readFileSync(0, 'utf-8')\r\n .split('\\n')\r\n .map((line) => line.split(' ').map(Number))\r\nmain(input)\r\n \r\nfunction main(input) {\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(2, 2)\r\n console.log('1 1')\r\n return [2, 2, [1, 1]]\r\n }\r\n \r\n const g = new Array(n).fill(0).map(() => new Set()),\r\n d = new Array(n).fill(0)\r\n const add = (i, j) => {\r\n g[i].add(j)\r\n d[j]++\r\n }\r\n console.log(input,g,d)\r\n \r\n}"}, {"source_code": "const fs = require('fs')\r\nconst input = fs\r\n .readFileSync(0, 'utf-8')\r\n .split('\\n')\r\n .map((line) => line.split(' ').map(Number))\r\nmain(input)\r\nfunction main(input) {\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(2, 2)\r\n console.log('1 1')\r\n return [2, 2, [1, 1]]\r\n }\r\n \r\n const g = new Array(n).fill(0).map(() => new Set()),\r\n d = new Array(n).fill(0)\r\n const add = (i, j) => {\r\n g[i].add(j)\r\n d[j]++\r\n }\r\n \r\n}"}, {"source_code": "const fs = require('fs')\r\nconst input = fs\r\n .readFileSync(0, 'utf-8')\r\n .split('\\n')\r\n .map((line) => line.split(' ').map(Number))\r\nmain(input)\r\nfunction main(input) {\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(2, 2)\r\n console.log('1 1')\r\n return [2, 2, [1, 1]]\r\n }\r\n}"}, {"source_code": "const fs = require('fs')\r\nconst input = fs\r\n .readFileSync(0, 'utf-8')\r\n .split('\\n')\r\n .map((line) => line.split(' ').map(Number))\r\nmain(input)\r\nfunction main(input) {\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(`2 2\\n1 1`)\r\n return\r\n }\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = []\r\n let idx = 0\r\n const add = (i, j) => ((e[idx] = j), (ne[idx] = h[i]), (h[i] = idx++))\r\n for (let i = 1; i < input.length; i++) {\r\n const [u, v] = input[i]\r\n add(u - 1, v - 1)\r\n add(v - 1, u - 1)\r\n }\r\n const colors = []\r\n const dfs = (i, color) => {\r\n if (colors[i]) return\r\n colors[i] = color\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k]\r\n dfs(j, 3 - color)\r\n }\r\n }\r\n dfs(0, 1)\r\n let s1 = 0,\r\n s2 = 0\r\n for (let num of colors) {\r\n if (num === 1) s1++\r\n else if (num === 2) s2++\r\n }\r\n if (s1 === s2) {\r\n console.log(`${s1} ${s1 + s2}`)\r\n console.log(new Array(n).fill(1).join(' '))\r\n return\r\n }\r\n\r\n const lt = s1 > s2 ? 2 : 1\r\n const res = new Array(n).fill(0)\r\n for (let i = 0; i < colors.length; i++) {\r\n if (colors[i] === lt) {\r\n res[i] = 1\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k]\r\n res[j] += 1\r\n }\r\n }\r\n }\r\n let sum = 0\r\n for (let i = 0; i < res.length; i++) sum += res[i]\r\n console.log(`${s1 > s2 ? s1 : s2} ${sum}`)\r\n console.log(res.join(' '))\r\n}"}, {"source_code": "const fs = require('fs')\r\nconst input = fs\r\n .readFileSync(0, 'utf-8')\r\n .split('\\n')\r\n .map((line) => line.split(' ').map(Number))\r\nmain(input)\r\nfunction main(input) {\r\n const n = input[0][0]\r\n if (n === 2) {\r\n console.log(`2 2\\n1 1`)\r\n return\r\n }\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = []\r\n let idx = 0\r\n const add = (i, j) => ((e[idx] = j), (ne[idx] = h[i]), (h[i] = idx++))\r\n for (let i = 1; i < input.length; i++) {\r\n const [u, v] = input[i]\r\n add(u - 1, v - 1)\r\n add(v - 1, u - 1)\r\n }\r\n const colors = []\r\n const dfs = (i, color) => {\r\n if (colors[i]) return\r\n colors[i] = color\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k]\r\n dfs(j, 3 - color)\r\n }\r\n }\r\n dfs(0, 1)\r\n let s1 = 0,\r\n s2 = 0\r\n for (let num of colors) {\r\n if (num === 1) s1++\r\n else if (num === 2) s2++\r\n }\r\n const lt = s1 > s2 ? 2 : 1\r\n const res = new Array(n).fill(0)\r\n for (let i = 0; i < colors.length; i++) {\r\n if (colors[i] === lt) {\r\n res[i] = 1\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k]\r\n res[j] += 1\r\n }\r\n }\r\n }\r\n let sum = 0\r\n for (let i = 0; i < res.length; i++) sum += res[i]\r\n console.log(`${s1 > s2 ? s1 : s2} ${sum}`)\r\n console.log(res.join(' '))\r\n}"}, {"source_code": "const fs = require('fs')\r\nconst input = fs\r\n .readFileSync(0, 'utf-8')\r\n .split('\\n')\r\n .map((line) => line.split(' ').map(Number))\r\nmain(input)\r\nfunction main(input) {\r\n const n = input[0][0]\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = []\r\n let idx = 0\r\n const add = (i, j) => ((e[idx] = j), (ne[idx] = h[i]), (h[i] = idx++))\r\n for (let i = 1; i < input.length; i++) {\r\n const [u, v] = input[i]\r\n add(u - 1, v - 1)\r\n add(v - 1, u - 1)\r\n }\r\n const colors = []\r\n const dfs = (i, color) => {\r\n if (colors[i]) return\r\n colors[i] = color\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k]\r\n dfs(j, 3 - color)\r\n }\r\n }\r\n dfs(0, 1)\r\n let s1 = 0,\r\n s2 = 0\r\n for (let num of colors) {\r\n if (num === 1) s1++\r\n else if (num === 2) s2++\r\n }\r\n const lt = s1 > s2 ? 2 : 1\r\n const res = new Array(n).fill(0)\r\n for (let i = 0; i < colors.length; i++) {\r\n if (colors[i] === lt) {\r\n res[i] = 1\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k]\r\n res[j] += 1\r\n }\r\n }\r\n }\r\n let sum = 0\r\n for (let i = 0; i < res.length; i++) sum += res[i]\r\n console.log(`${s1 > s2 ? s1 : s2} ${sum}`)\r\n console.log(res.join(' '))\r\n}"}], "src_uid": "dc3848faf577c5a49273020a14b343e1"} {"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$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \\leq k \\leq n \\leq 40$$$) — 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": "/**\r\n * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools\r\n *\r\n * To modify the template, go to Preferences -> Editor -> File and Code Templates -> Other\r\n */\r\n\r\n// Write your solution here\r\nconst {EOL} = require(\"os\");\r\n\r\nfunction board({n, k}) {\r\n return Array.from({length: n}, (_, i) =>\r\n Array.from({length: n}, (_, j) => i % 2 === 0 && j % 2 === 0 && i === j && ((i / 2) + 1) <= k ? 'R' : '.').join('')\r\n ).join('\\n');\r\n}\r\n\r\nfunction solution({n, k}) {\r\n return Math.ceil(n / 2) < k ? -1 : board({n, k});\r\n}\r\n\r\nfunction parse(input) {\r\n const [n, k] = input.shift().split(' ').map(Number);\r\n return {n, k};\r\n}\r\n\r\nlet lines = '';\r\n\r\nprocess.stdin.on('data', data => lines += data);\r\n\r\nprocess.stdin.on('end', () => {\r\n const input = lines.split(EOL);\r\n const number_of_test_cases = Number(input.shift());\r\n for (let _ = 0; _ < number_of_test_cases; _ += 1) {\r\n console.log(solution(parse(input)));\r\n }\r\n});"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nconst readInt = async function(){\r\n return parseInt(await getLine());\r\n}\r\n\r\nconst readIntArray = async function() {\r\n return (await getLine()).split(' ').map(num => parseInt(num));\r\n}\r\n\r\nlet solve = async () => {\r\n const nsc = await readInt();\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const [n,k] = await readIntArray();\r\n if (k > Math.floor(n + 1) / 2) {\r\n console.log(-1);\r\n } else {\r\n const a = new Array(n);\r\n let nrooks = 0;\r\n for(let i = 0; i < n; i++) {\r\n for(let j = 0; j < n; j++)\r\n if (i===j && i % 2===0 && nrooks < k) {\r\n a[j] = 'R';\r\n nrooks++;\r\n }\r\n else\r\n a[j] = '.';\r\n console.log(a.join(''));\r\n }\r\n }\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet [n, k] = nl.nums();\n\t\tif ((2 * k - 1) <= n) {\n\t\t\tlet s = [];\n\t\t\tfor(let x = 0; x < n; x++){\n\t\t\t\tfor(let y = 0; y < n; y++){\n\t\t\t\t\tif (x === y && x % 2 === 0 && k > 0){\n\t\t\t\t\t\ts.push(\"R\");\n\t\t\t\t\t\tk--;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ts.push(\".\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (x != n-1) {\n\t\t\t\t\ts.push('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t\tans.push(s.join(''));\n\t\t} else {\n\t\t\t\tans.push('-1');\n\t\t}\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "let _inputLines;\r\nlet _lineNumber = 0;\r\nlet inputReader = _inputReader();\r\n\r\nfunction _main() {\r\n _inputLines = _inputData\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n let t = inputReader.readNumber();\r\n\r\n function solve() {\r\n let [n, k] = inputReader.readNumberArray();\r\n let v = [];\r\n for (let i = 0; i < n; i++) {\r\n v[i] = new Array(n);\r\n for (let j = 0; j < n; j++) v[i][j] = \".\";\r\n }\r\n\r\n let possibleRooks = Math.ceil(n / 2);\r\n if (k > possibleRooks) {\r\n console.log(-1);\r\n return;\r\n }\r\n let i = 0,\r\n j = 0;\r\n while (k > 0) {\r\n v[i][j] = \"R\";\r\n i += 2;\r\n j += 2;\r\n k -= 1;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n let string = \"\";\r\n for (let j = 0; j < n; j++) {\r\n string += v[i][j];\r\n }\r\n console.log(string);\r\n }\r\n }\r\n\r\n while (t--) {\r\n solve();\r\n }\r\n}\r\n\r\nvar _inputData = \"\";\r\nfunction cacheInput(data) {\r\n _inputData += data;\r\n}\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf8\");\r\nprocess.stdin.on(\"data\", cacheInput).on(\"end\", _main);\r\n\r\nfunction _inputReader() {\r\n function readNumber() {\r\n return Number(_inputLines[_lineNumber++]);\r\n }\r\n\r\n function readNumberArray() {\r\n return _inputLines[_lineNumber++].split(\" \").map((val) => Number(val));\r\n }\r\n\r\n return {\r\n readNumber,\r\n readNumberArray,\r\n };\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, k)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k) {\n if (k > Math.ceil(n / 2)) return -1\n\n const grid = []\n for (let i = 0; i < n; i++) {\n grid[i] = []\n for (let j = 0; j < n; j++) {\n grid[i][j] = '.'\n }\n }\n for (let i = 0; i < k; i++) {\n grid[2 * i][2 * i] = 'R'\n }\n return grid.map(r => r.join('')).join('\\n')\n}\n"}], "negative_code": [{"source_code": "const {EOL} = require(\"os\");\r\n\r\nfunction board({n, k}) {\r\n return Array.from({length: n}, (_, i) =>\r\n Array.from({length: n}, (_, j) => i%2 === 0 && j%2 === 0 && i === j && i <= k? 'R': '.').join('')\r\n ).join('\\n');\r\n}\r\n\r\nfunction solution({n, k}) {\r\n return Math.ceil(n/2) < k ? -1 : board({n, k});\r\n}\r\n\r\nfunction parse(input) {\r\n const [n, k] = input.shift().split(' ').map(Number);\r\n return {n, k};\r\n}\r\n\r\nlet lines = '';\r\n\r\nprocess.stdin.on('data', data => lines += data);\r\n\r\nprocess.stdin.on('end', () => {\r\n const input = lines.split(EOL);\r\n const number_of_test_cases = Number(input.shift());\r\n for (let _ = 0; _ < number_of_test_cases; _ += 1) {\r\n console.log(solution(parse(input)));\r\n }\r\n});"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nconst readInt = async function(){\r\n return parseInt(await getLine());\r\n}\r\n\r\nconst readIntArray = async function() {\r\n return (await getLine()).split(' ').map(num => parseInt(num));\r\n}\r\n\r\nlet solve = async () => {\r\n const nsc = await readInt();\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const [n,k] = await readIntArray();\r\n if (k > Math.floor(n + 1) / 2) {\r\n console.log(-1);\r\n } else {\r\n const a = new Array(n);\r\n for(let i = 0; i < n; i++) {\r\n for(let j = 0; j < n; j++)\r\n if (i===j && i % 2===0)\r\n a[j] = 'R';\r\n else\r\n a[j] = '.';\r\n console.log(a.join(''));\r\n }\r\n }\r\n }\r\n}\r\n\r\nsolve();\r\n"}], "src_uid": "d5549c0627c236d82541a67ccbe7977d"} {"nl": {"description": "Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted $$$n$$$ windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $$$n$$$ windows. If there are multiple answers, you can print any of them.Here are some examples: if Monocarp has counted $$$30$$$ windows, there could have been $$$2$$$ three-room apartments, $$$2$$$ five-room apartments and $$$2$$$ seven-room apartments, since $$$2 \\cdot 3 + 2 \\cdot 5 + 2 \\cdot 7 = 30$$$; if Monocarp has counted $$$67$$$ windows, there could have been $$$7$$$ three-room apartments, $$$5$$$ five-room apartments and $$$3$$$ seven-room apartments, since $$$7 \\cdot 3 + 5 \\cdot 5 + 3 \\cdot 7 = 67$$$; if Monocarp has counted $$$4$$$ windows, he should have mistaken since no building with the aforementioned layout can have $$$4$$$ windows. ", "input_spec": "Th first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) — the number of windows in the building.", "output_spec": "For each test case, if a building with the new layout and the given number of windows just can't exist, print $$$-1$$$. Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.", "sample_inputs": ["4\n30\n67\n4\n14"], "sample_outputs": ["2 2 2\n7 5 3\n-1\n0 0 2"], "notes": null}, "positive_code": [{"source_code": "'use strict'; /*jslint node:true, browser:true, es6:true*/\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nconst print = console.log\nconst lines = []\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nlet mem = new Map();\nfunction query(n){\n if (n<0)\n return;\n if (n==0)\n return [0, 0, 0];\n if (mem.has(n))\n return mem.get(n);\n for (let [i, d] of [3, 5, 7].entries())\n {\n let res = query(n-d);\n if (!res)\n continue;\n res = res.slice(0);\n res[i]++;\n mem.set(n, res);\n return res;\n }\n mem.set(n, null);\n}\n\nfunction main() {\n var q = +readline();\n while (q--)\n {\n var n = +readline();\n let res = query(n);\n if (res)\n print(res.join(' '));\n else\n print(-1);\n }\n}\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet isFirst = true;\nreadline.on('line', line => {\n if(isFirst) return isFirst = false;\n const variant = getCombination(+line);\n const map = {3:0,5:0,7:0}\n if(variant) {\n variant.forEach(num => map[num]++);\n console.log(`${map[3]} ${map[5]} ${map[7]}`);\n } else {\n console.log(-1);\n }\n \n});\n\n\n\nfunction getCombination(total, acc = []) {\n if(total === 0) return acc;\n if(total < 0) return null;\n let possible = null;\n for(let num of [3,5,7]) {\n const variant = getCombination(total - num, [...acc, num]);\n if(variant) {\n possible = variant;\n break;\n }\n }\n\n return possible;\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n let num = +readLine();\n let [a, b, c] = [0, 0, 0];\n\n if (num === 1 || num === 2 || num === 4) {\n console.log(-1);\n continue;\n } else {\n if (num % 3 == 0) {\n console.log(`${Math.floor(num / 3)} ${b} ${c}`);\n continue;\n } else if (num % 5 == 0) {\n console.log(`${a} ${Math.floor(num / 5)} ${c}`);\n continue;\n } else if (num % 7 == 0) {\n console.log(`${a} ${b} ${Math.floor(num / 7)}`);\n continue;\n } else {\n while (num) {\n if (num % 3 === 0) {\n a = Math.floor(num / 3);\n break;\n }\n b++;\n num -= 5;\n }\n console.log(`${a} ${b} ${c}`);\n continue;\n }\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n})\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n})\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 1;\n let i = 1;\n while (i <= testCases) {\n // let a = data[i].trim().split(' ').map(Number);\n const n = data[i] * 1;\n if (n % 7 === 0) console.log('0 0 ' + n / 7);\n else if (n % 5 === 0) console.log('0 ' + n / 5 + ' 0');\n else if(n % 3 === 0) console.log(n / 3 + ' 0 0');\n else if (n % 10 === 7) console.log('0 ' + (n - 7) / 5 + ' 1');\n else if (n % 10 === 3 || n % 10 === 8) console.log('1 ' + (n - 3) / 5 + ' 0');\n else if (n > 2 && n % 10 === 2) console.log('4 ' + (n - 12) / 5 + ' 0');\n else if (n % 10 === 6 || n % 10 === 9) console.log((n % 10) / 3 + ' ' + (n - (n % 10)) / 5 + ' 0');\n // else if (n > 8 && n % 10 === 8) console.log('6 ' + (n - 18) / 5 + ' 0');\n else if (n > 1 && n % 10 === 1) console.log('2 ' + (n - 6) / 5 + ' 0');\n else if (n > 14 && n % 10 === 4) console.log('8 ' + (n - 24) / 5 + ' 0');\n else console.log(-1);\n // const k = a[1];\n // let s = data[i + 1].trim().split(' ');\n \n i += 1;\n }\n}"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i - a] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n a = a || 0;\n b = b || (this.length - 1);\n let prev = a;\n for (let i = a; i <= b; i++) {\n if (i == b || fn(this[i], this[i + 1], i, this)) {\n arr.push(this.slice(prev, i + 1));\n prev = i + 1;\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nfunction inv(b, m) {\n for (var a = m, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + m) % m;\n}\n\n// let MOD = 1e9 + 7\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nasync function main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math,\n bi = BigInt, rand = n => Math.random() * n | 0;\n\n let f = Arr(1e3 + 1, i => []);\n f[0] = [0, 0, 0]\n For(1, 1e3, i => {\n if (i >= 3 && f[i - 3].length) { f[i] = [...f[i - 3]]; f[i][0]++ }\n if (i >= 5 && f[i - 5].length) { f[i] = [...f[i - 5]]; f[i][1]++ }\n if (i >= 7 && f[i - 7].length) { f[i] = [...f[i - 7]]; f[i][2]++ }\n })\n\n let t = $()\n while (t--) {\n let n = $()\n if (f[n].length) {\n log(f[n].join(' '))\n } else {\n log(-1)\n }\n }\n}\n"}, {"source_code": "const { createInterface } = require('readline')\n\nconst f = (it, obj) => {\n if (it === 0) return true\n if (it < 0) return\n obj.a++\n if (f(it - 7, obj)) return true; else obj.a--\n obj.b++\n if (f(it - 5, obj)) return true; else obj.b--\n obj.c++\n if (f(it - 3, obj)) return true; else obj.c--\n}\n\nlet count = -1\ncreateInterface(process.stdin, process.stdout).on('line', q => {\n if (count === 0) return\n if (count === -1) {\n count = +q\n return\n } else count--\n const obj = { a: 0, b: 0, c: 0 }\n if (f(+q, obj)) console.log(obj.c, obj.b, obj.a)\n else console.log('-1')\n if (!count) process.exit()\n})\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let a = 0;\n let b = 0;\n let c = 0;\n let isFound = false;\n for(let i = 0; i <= Math.floor(n/3); i++){\n if(isFound)\n break;\n if(3*i > n)\n break;\n else if(3*i === n){\n a = i;\n isFound = true;\n break;\n }\n for(let j = 0; j <= Math.floor(n/5); j++){\n if(isFound)\n break;\n if(3*i + 5*j > n)\n break;\n else if(3*i + 5*j === n){\n a = i; b = j;\n isFound = true;\n break;\n }\n for(let k = 0; k <= Math.floor(n/7); k++){\n if(3*i + 5*j + 7*k === n){\n a = i; b = j; c = k;\n isFound = true;\n break;\n }else if(3*i + 5*j + 7*k > n){\n break;\n }\n }\n }\n }\n\n if(isFound)\n console.log(a,b,c)\n else\n console.log(-1);\n }\n}\n"}, {"source_code": "var inputs = parseInt(readline());\nfor (var i = 0; i < inputs; i++) {\n var totalWindows = parseInt(readline());\n var rooms = [0, 0, 0];\n if (totalWindows < 3 || totalWindows === 4) {\n print(\"-1\");\n continue;\n } else {\n var isCompvared = false;\n\n if (totalWindows % 3 === 0) {\n rooms[0] = totalWindows / 3;\n print(rooms[0] + \" \" + rooms[1] + \" \" + rooms[2]);\n continue;\n }\n if (totalWindows % 5 === 0) {\n rooms[1] = totalWindows / 5;\n print(rooms[0] + \" \" + rooms[1] + \" \" + rooms[2]);\n continue;\n }\n if (totalWindows % 7 === 0) {\n rooms[2] = totalWindows / 7;\n print(rooms[0] + \" \" + rooms[1] + \" \" + rooms[2]);\n continue;\n }\n for (var j = Math.floor(totalWindows / 3); j >= 0; j--) {\n var leftOverWindows = totalWindows - 3 * j;\n\n if (leftOverWindows >= 5 && leftOverWindows % 5 === 0) {\n rooms = [j, leftOverWindows / 5, 0];\n isCompvared = true;\n break;\n } else if (leftOverWindows >= 7 && leftOverWindows % 7 === 0) {\n rooms = [j, 0, leftOverWindows / 7];\n isCompvared = true;\n break;\n } else if (leftOverWindows >= 8 && leftOverWindows % 8 === 0) {\n var total = leftOverWindows / 8;\n rooms = [j + total, total, 0];\n isCompvared = true;\n break;\n }\n }\n if (isCompvared) {\n print(rooms[0] + \" \" + rooms[1] + \" \" + rooms[2]);\n } else {\n print(\"-1\");\n }\n }\n}\n"}, {"source_code": "/*\n......descrition.....\n...................\nA. Number of Apartments\ntime limit per test1 second\nmemory limit per test256 megabytes\ninputstandard input\noutputstandard output\nRecently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.\n\nMonocarp went around the building and counted n windows. Now he is wondering, how many apartments of each type the building may have.\n\nUnfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has n windows. If there are multiple answers, you can print any of them.\n\nHere are some examples:\n\nif Monocarp has counted 30 windows, there could have been 2 three-room apartments, 2 five-room apartments and 2 seven-room apartments, since 2⋅3+2⋅5+2⋅7=30;\nif Monocarp has counted 67 windows, there could have been 7 three-room apartments, 5 five-room apartments and 3 seven-room apartments, since 7⋅3+5⋅5+3⋅7=67;\nif Monocarp has counted 4 windows, he should have mistaken since no building with the aforementioned layout can have 4 windows.\nInput\nTh first line contains one integer t (1≤t≤1000) — the number of test cases.\n\nThe only line of each test case contains one integer n (1≤n≤1000) — the number of windows in the building.\n\nOutput\nFor each test case, if a building with the new layout and the given number of windows just can't exist, print −1.\n\nOtherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.\n\nExample\ninputCopy\n4\n30\n67\n4\n14\noutputCopy\n2 2 2\n7 5 3\n-1\n0 0 2\n\nTrois tableua des multipliant de 3 et 5 et 7 et un boolean found \npuis chercher si existe dans chaque tableau et mettre found a true\npuis cherchhr si somme de valeurs entre chaque deux tableau et mettre found a true\nsi not found afficher -1\n*/\n\n\nvar testCasesNumber = readline();\nvar listOfWindowsNumber = [];\nvar valus0fX3 =[0,\t3,\t6,\t9,\t12,\t15,\t18,\t21,\t24,\t27,\t30,\t33,\t36,\t39,\t42,\t45,\t48,\t51,\t54,\t57,\t60,\t63,\t66,\t69,\t72,\t75,\t78,\t81,\t84,\t87,\t90,\t93,\t96,\t99,\t102,\t105,\t108,\t111,\t114,\t117,\t120,\t123,\t126,\t129,\t132,\t135,\t138,\t141,\t144,\t147,\t150,\t153,\t156,\t159,\t162,\t165,\t168,\t171,\t174,\t177,\t180,\t183,\t186,\t189,\t192,\t195,\t198,\t201,\t204,\t207,\t210,\t213,\t216,\t219,\t222,\t225,\t228,\t231,\t234,\t237,\t240,\t243,\t246,\t249,\t252,\t255,\t258,\t261,\t264,\t267,\t270,\t273,\t276,\t279,\t282,\t285,\t288,\t291,\t294,\t297,\t300,\t303,\t306,\t309,\t312,\t315,\t318,\t321,\t324,\t327,\t330,\t333,\t336,\t339,\t342,\t345,\t348,\t351,\t354,\t357,\t360,\t363,\t366,\t369,\t372,\t375,\t378,\t381,\t384,\t387,\t390,\t393,\t396,\t399,\t402,\t405,\t408,\t411,\t414,\t417,\t420,\t423,\t426,\t429,\t432,\t435,\t438,\t441,\t444,\t447,\t450,\t453,\t456,\t459,\t462,\t465,\t468,\t471,\t474,\t477,\t480,\t483,\t486,\t489,\t492,\t495,\t498,\t501,\t504,\t507,\t510,\t513,\t516,\t519,\t522,\t525,\t528,\t531,\t534,\t537,\t540,\t543,\t546,\t549,\t552,\t555,\t558,\t561,\t564,\t567,\t570,\t573,\t576,\t579,\t582,\t585,\t588,\t591,\t594,\t597,\t600,\t603,\t606,\t609,\t612,\t615,\t618,\t621,\t624,\t627,\t630,\t633,\t636,\t639,\t642,\t645,\t648,\t651,\t654,\t657,\t660,\t663,\t666,\t669,\t672,\t675,\t678,\t681,\t684,\t687,\t690,\t693,\t696,\t699,\t702,\t705,\t708,\t711,\t714,\t717,\t720,\t723,\t726,\t729,\t732,\t735,\t738,\t741,\t744,\t747,\t750,\t753,\t756,\t759,\t762,\t765,\t768,\t771,\t774,\t777,\t780,\t783,\t786,\t789,\t792,\t795,\t798,\t801,\t804,\t807,\t810,\t813,\t816,\t819,\t822,\t825,\t828,\t831,\t834,\t837,\t840,\t843,\t846,\t849,\t852,\t855,\t858,\t861,\t864,\t867,\t870,\t873,\t876,\t879,\t882,\t885,\t888,\t891,\t894,\t897,\t900,\t903,\t906,\t909,\t912,\t915,\t918,\t921,\t924,\t927,\t930,\t933,\t936,\t939,\t942,\t945,\t948,\t951,\t954,\t957,\t960,\t963,\t966,\t969,\t972,\t975,\t978,\t981,\t984,\t987,\t990,\t993,\t996,\t999];\nvar valus0fX5 =[0,\t5,\t10,\t15,\t20,\t25,\t30,\t35,\t40,\t45,\t50,\t55,\t60,\t65,\t70,\t75,\t80,\t85,\t90,\t95,\t100,\t105,\t110,\t115,\t120,\t125,\t130,\t135,\t140,\t145,\t150,\t155,\t160,\t165,\t170,\t175,\t180,\t185,\t190,\t195,\t200,\t205,\t210,\t215,\t220,\t225,\t230,\t235,\t240,\t245,\t250,\t255,\t260,\t265,\t270,\t275,\t280,\t285,\t290,\t295,\t300,\t305,\t310,\t315,\t320,\t325,\t330,\t335,\t340,\t345,\t350,\t355,\t360,\t365,\t370,\t375,\t380,\t385,\t390,\t395,\t400,\t405,\t410,\t415,\t420,\t425,\t430,\t435,\t440,\t445,\t450,\t455,\t460,\t465,\t470,\t475,\t480,\t485,\t490,\t495,\t500,\t505,\t510,\t515,\t520,\t525,\t530,\t535,\t540,\t545,\t550,\t555,\t560,\t565,\t570,\t575,\t580,\t585,\t590,\t595,\t600,\t605,\t610,\t615,\t620,\t625,\t630,\t635,\t640,\t645,\t650,\t655,\t660,\t665,\t670,\t675,\t680,\t685,\t690,\t695,\t700,\t705,\t710,\t715,\t720,\t725,\t730,\t735,\t740,\t745,\t750,\t755,\t760,\t765,\t770,\t775,\t780,\t785,\t790,\t795,\t800,\t805,\t810,\t815,\t820,\t825,\t830,\t835,\t840,\t845,\t850,\t855,\t860,\t865,\t870,\t875,\t880,\t885,\t890,\t895,\t900,\t905,\t910,\t915,\t920,\t925,\t930,\t935,\t940,\t945,\t950,\t955,\t960,\t965,\t970,\t975,\t980,\t985,\t990,\t995,\t1000];\nvar valus0fX7 =[0,\t7,\t14,\t21,\t28,\t35,\t42,\t49,\t56,\t63,\t70,\t77,\t84,\t91,\t98,\t105,\t112,\t119,\t126,\t133,\t140,\t147,\t154,\t161,\t168,\t175,\t182,\t189,\t196,\t203,\t210,\t217,\t224,\t231,\t238,\t245,\t252,\t259,\t266,\t273,\t280,\t287,\t294,\t301,\t308,\t315,\t322,\t329,\t336,\t343,\t350,\t357,\t364,\t371,\t378,\t385,\t392,\t399,\t406,\t413,\t420,\t427,\t434,\t441,\t448,\t455,\t462,\t469,\t476,\t483,\t490,\t497,\t504,\t511,\t518,\t525,\t532,\t539,\t546,\t553,\t560,\t567,\t574,\t581,\t588,\t595,\t602,\t609,\t616,\t623,\t630,\t637,\t644,\t651,\t658,\t665,\t672,\t679,\t686,\t693,\t700,\t707,\t714,\t721,\t728,\t735,\t742,\t749,\t756,\t763,\t770,\t777,\t784,\t791,\t798,\t805,\t812,\t819,\t826,\t833,\t840,\t847,\t854,\t861,\t868,\t875,\t882,\t889,\t896,\t903,\t910,\t917,\t924,\t931,\t938,\t945,\t952,\t959,\t966,\t973,\t980,\t987,\t994];\n\n\n//Saisie des données\n\nfor (var i = 0; i < testCasesNumber; i++) {\n listOfWindowsNumber[i] = readline();\n }\n\nfor (var i = 0; i < testCasesNumber; i++) {\n var found=false;\n var number = parseInt(listOfWindowsNumber[i]);\n if (number==1 || number==2 || number==4)\n {\n print(-1);\n found=true;\n }\n if (valus0fX3.indexOf(number,0)!=-1) {\n print (number/3,0,0);\n found=true;\n }\n \n if ((valus0fX5.indexOf(number,0)!=-1) && (found == false)) {\n print (0,number/5,0);\n found=true;\n }\n \n if ((valus0fX7.indexOf(number,0)!=-1) && (found == false)) {\n print (0,0,number/7);\n found=true;\n }\n \n for(var t3 in valus0fX3){\n if (found==true){\n break;\n }\n for (var t5 in valus0fX5){\n if (number==t3*3+t5*5){\n print(t3,t5,0);\n found=true;\n break;\n }\n }\n }\n \n /* for(var t32 in valus0fX3){\n if (found==true){\n break;\n }\n for (var t7 in valus0fX7){\n if (number==t32*3+t7*7){\n print(t32,0,t7);\n found=true;\n break;\n }\n }\n }\n\n \n for(var t52 in valus0fX5){\n if (found==true){\n break;\n }\n for (var t72 in valus0fX7){\n if (number==t52*5+t72*7){\n print(0,t52,t72);\n found=true;\n break;\n }\n }\n } */\n/**/\n if (found==false){\n print(-1);\n}\n \n}\n"}], "negative_code": [{"source_code": "let mem = new Map();\nfunction query(n){\n if (n<0)\n return;\n if (n==0)\n return [0, 0, 0];\n if (mem.has(n))\n return mem.get(n);\n for (let [i, d] of [3, 5, 7].entries())\n {\n let res = query(n-d);\n if (!res)\n continue;\n res = res.slice(0);\n res[i]++;\n mem.set(n, res);\n return res;\n }\n mem.set(n, null);\n}\n\nfunction main() {\n var q = +readline();\n while (q--)\n {\n var n = +readline();\n let res = query(n);\n if (res)\n print(res.join(' '));\n else\n print(-1);\n }\n}\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nreadline.on('line', line => {\n const variant = getCombination(+line);\n const map = {3:0,5:0,7:0}\n if(variant) {\n variant.forEach(num => map[num]++);\n console.log(`${map[3]} ${map[5]} ${map[7]}`);\n } else {\n console.log(-1);\n }\n \n});\n\n\n\nfunction getCombination(total, acc = []) {\n if(total === 0) return acc;\n if(total < 0) return null;\n let possible = null;\n for(let num of [3,5,7]) {\n const variant = getCombination(total - num, [...acc, num]);\n if(variant) {\n possible = variant;\n break;\n }\n }\n\n return possible;\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const num = +readLine();\n const ans = [0, 0, 0];\n\n if (num % 3 === 0) {\n ans[0] = Math.floor(num / 3);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 3) % 5 === 0) {\n ans[0] = Math.floor(num / 3);\n ans[1] = Math.floor((num % 3) / 5);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 3) % 7 === 0) {\n ans[0] = Math.floor(num / 3);\n ans[2] = Math.floor((num % 3) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 5 === 0) {\n ans[1] = Math.floor(num / 5);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 5) % 3 === 0) {\n ans[1] = Math.floor(num / 5);\n ans[0] = Math.floor((num % 5) / 3);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 5) % 7 === 0) {\n ans[1] = Math.floor(num / 5);\n ans[2] = Math.floor((num % 5) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 7 === 0) {\n ans[2] = Math.floor(num / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 7) % 5 === 0) {\n ans[2] = Math.floor(num / 7);\n ans[1] = Math.floor((num % 7) / 5);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 7) % 3 === 0) {\n ans[2] = Math.floor(num / 7);\n ans[0] = Math.floor((num % 7) / 3);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 8 === 0) {\n ans[0] = Math.floor(num / 8);\n ans[1] = Math.floor(num / 8);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 8) % 7 === 0) {\n ans[0] = Math.floor(num / 8);\n ans[1] = Math.floor(num / 8);\n ans[2] = Math.floor((num % 8) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 10 === 0) {\n ans[0] = Math.floor(num / 10);\n ans[2] = Math.floor(num / 10);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 10) % 5 === 0) {\n ans[0] = Math.floor(num / 10);\n ans[1] = Math.floor((num % 10) / 5);\n ans[2] = Math.floor(num / 10);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 12 === 0) {\n ans[1] = Math.floor(num / 12);\n ans[2] = Math.floor(num / 12);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 12) % 3 === 0) {\n ans[0] = Math.floor((num % 12) / 3);\n ans[1] = Math.floor(num / 12);\n ans[2] = Math.floor(num / 12);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 15 === 0) {\n ans[0] = Math.floor(num / 15);\n ans[1] = Math.floor(num / 15);\n ans[2] = Math.floor(num / 15);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 15) % 3 === 0) {\n ans[0] = Math.floor(num / 15) + Math.floor((num % 15) / 3);\n ans[1] = Math.floor(num / 15);\n ans[2] = Math.floor(num / 15);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 15) % 5 === 0) {\n ans[0] = Math.floor(num / 15);\n ans[1] = Math.floor(num / 15) + Math.floor((num % 15) / 5);\n ans[2] = Math.floor(num / 15);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 15) % 7 === 0) {\n ans[0] = Math.floor(num / 15);\n ans[1] = Math.floor(num / 15);\n ans[2] = Math.floor(num / 15) + Math.floor((num % 15) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else {\n console.log(-1);\n continue;\n }\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const num = +readLine();\n const ans = [0, 0, 0];\n\n if (num % 3 === 0) {\n ans[0] = Math.floor(num / 3);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 3) % 5 === 0) {\n ans[0] = Math.floor(num / 3);\n ans[1] = Math.floor((num % 3) / 5);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 3) % 7 === 0) {\n ans[0] = Math.floor(num / 3);\n ans[2] = Math.floor((num % 3) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 5 === 0) {\n ans[1] = Math.floor(num / 5);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 5) % 3 === 0) {\n ans[1] = Math.floor(num / 5);\n ans[0] = Math.floor((num % 5) / 3);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 5) % 7 === 0) {\n ans[1] = Math.floor(num / 5);\n ans[2] = Math.floor((num % 5) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 7 === 0) {\n ans[2] = Math.floor(num / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 7) % 5 === 0) {\n ans[2] = Math.floor(num / 7);\n ans[1] = Math.floor((num % 7) / 5);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 7) % 3 === 0) {\n ans[2] = Math.floor(num / 7);\n ans[0] = Math.floor((num % 7) / 3);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 8 === 0) {\n ans[0] = Math.floor(num / 8);\n ans[1] = Math.floor(num / 8);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 8) % 3 === 0) {\n ans[0] = Math.floor((num % 8) / 3) + Math.floor(num / 8);\n ans[1] = Math.floor(num / 8);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 8) % 5 === 0) {\n ans[0] = Math.floor(num / 8);\n ans[1] = Math.floor((num % 8) / 5) + Math.floor(num / 8);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 8) % 7 === 0) {\n ans[0] = Math.floor(num / 8);\n ans[1] = Math.floor(num / 8);\n ans[2] = Math.floor((num % 8) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 10 === 0) {\n ans[0] = Math.floor(num / 10);\n ans[2] = Math.floor(num / 10);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 10) % 3 === 0) {\n ans[0] = Math.floor((num % 10) / 3) + Math.floor(num / 10);\n ans[2] = Math.floor(num / 10);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 10) % 7 === 0) {\n ans[0] = Math.floor(num / 10);\n ans[2] = Math.floor((num % 10) / 7) + Math.floor(num / 10);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 10) % 5 === 0) {\n ans[0] = Math.floor(num / 10);\n ans[1] = Math.floor((num % 10) / 5);\n ans[2] = Math.floor(num / 10);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 12 === 0) {\n ans[1] = Math.floor(num / 12);\n ans[2] = Math.floor(num / 12);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 12) % 5 === 0) {\n ans[1] = Math.floor((num % 12) / 5) + Math.floor(num / 12);\n ans[2] = Math.floor(num / 12);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 12) % 7 === 0) {\n ans[1] = Math.floor(num / 12);\n ans[2] = Math.floor((num % 12) / 7) + Math.floor(num / 12);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 12) % 3 === 0) {\n ans[0] = Math.floor((num % 12) / 3);\n ans[1] = Math.floor(num / 12);\n ans[2] = Math.floor(num / 12);\n console.log(ans.join(\" \"));\n continue;\n } else if (num % 15 === 0) {\n ans[0] = Math.floor(num / 15);\n ans[1] = Math.floor(num / 15);\n ans[2] = Math.floor(num / 15);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 15) % 3 === 0) {\n ans[0] = Math.floor(num / 15) + Math.floor((num % 15) / 3);\n ans[1] = Math.floor(num / 15);\n ans[2] = Math.floor(num / 15);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 15) % 5 === 0) {\n ans[0] = Math.floor(num / 15);\n ans[1] = Math.floor(num / 15) + Math.floor((num % 15) / 5);\n ans[2] = Math.floor(num / 15);\n console.log(ans.join(\" \"));\n continue;\n } else if ((num % 15) % 7 === 0) {\n ans[0] = Math.floor(num / 15);\n ans[1] = Math.floor(num / 15);\n ans[2] = Math.floor(num / 15) + Math.floor((num % 15) / 7);\n console.log(ans.join(\" \"));\n continue;\n } else {\n console.log(-1);\n continue;\n }\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n let num = +readLine();\n let [a, b, c] = [0, 0, 0];\n\n if (num === 1 || num === 2 || num === 4) {\n console.log(-1);\n continue;\n } else {\n while (num) {\n c++;\n num -= 7;\n if (num % 3 === 0) {\n a = Math.floor(num / 3);\n break;\n }\n }\n console.log(`${a} ${b} ${c}`);\n continue;\n }\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n let num = +readLine();\n let [a, b, c] = [0, 0, 0];\n\n if (num === 1 || num === 2 || num === 4) {\n console.log(-1);\n continue;\n } else {\n while (num) {\n if (num % 3 === 0) {\n a = Math.floor(num / 3);\n break;\n }\n c++;\n num -= 7;\n }\n console.log(`${a} ${b} ${c}`);\n continue;\n }\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n})\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n})\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 1;\n let i = 1;\n while (i <= testCases) {\n // let a = data[i].trim().split(' ').map(Number);\n const n = data[i] * 1;\n if (n % 7 === 0) console.log('0 0 ' + n / 7);\n else if (n % 5 === 0) console.log('0 ' + n / 5 + ' 0');\n else if(n % 3 === 0) console.log(n / 3 + ' 0 0');\n else if (n % 10 === 7) console.log('0 ' + (n - 7) / 5 + ' 1');\n else if (n % 10 === 3) console.log('1 ' + (n - 3) / 5 + ' 0');\n else if (n > 2 && n % 10 === 2) console.log('4 ' + (n - 12) / 5 + ' 0');\n else if (n % 10 === 6 || n % 10 === 9) console.log((n % 10) / 3 + ' ' + (n - (n % 10)) / 5 + ' 0');\n else if (n > 8 && n % 10 === 8) console.log('6 ' + (n - 18) / 5 + ' 0');\n else if (n > 11 && n % 10 === 1) console.log('7 ' + (n - 21) / 5 + ' 0');\n else if (n > 14 && n % 10 === 4) console.log('8 ' + (n - 24) / 5 + ' 0');\n else console.log(-1);\n // const k = a[1];\n // let s = data[i + 1].trim().split(' ');\n \n i += 1;\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n})\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n})\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 1;\n let i = 1;\n while (i <= testCases) {\n // let a = data[i].trim().split(' ').map(Number);\n const n = data[i] * 1;\n if (n % 7 === 0) console.log('0 0 ' + n / 7);\n else if (n % 5 === 0) console.log('0 ' + n / 5 + ' 0');\n else if(n % 3 === 0) console.log(n / 3 + ' 0 0');\n else if (n % 10 === 7) console.log('0 ' + (n - 7) / 5 + ' 1');\n else if (n % 10 === 3 || n % 10 === 8) console.log('1 ' + (n - 3) / 5 + ' 0');\n else if (n > 2 && n % 10 === 2) console.log('4 ' + (n - 12) / 5 + ' 0');\n else if (n % 10 === 6 || n % 10 === 9) console.log((n % 10) / 3 + ' ' + (n - (n % 10)) / 5 + ' 0');\n // else if (n > 8 && n % 10 === 8) console.log('6 ' + (n - 18) / 5 + ' 0');\n else if (n > 11 && n % 10 === 1) console.log('7 ' + (n - 21) / 5 + ' 0');\n else if (n > 14 && n % 10 === 4) console.log('8 ' + (n - 24) / 5 + ' 0');\n else console.log(-1);\n // const k = a[1];\n // let s = data[i + 1].trim().split(' ');\n \n i += 1;\n }\n}"}, {"source_code": "/* eslint-disable @typescript-eslint/no-var-requires */\nconst { createInterface } = require('readline')\n\nconst f = (it, obj) => {\n if (it === 0) return true\n if (it < 0) return\n obj.a++\n if (f(it - 7, obj)) return true; else obj.a--\n obj.b++\n if (f(it - 5, obj)) return true; else obj.b--\n obj.c++\n if (f(it - 3, obj)) return true; else obj.c--\n}\n\nlet count = -1\ncreateInterface(process.stdin, process.stdout).on('line', q => {\n if (count === 0) return\n if (count === -1) {\n count = +q\n return\n } else count--\n const obj = { a: 0, b: 0, c: 0 }\n if (f(+q, obj)) console.log(obj.a, obj.b, obj.c)\n else console.log('-1')\n if (!count) process.exit()\n})\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let a = 0;\n let b = 0;\n let c = 0;\n let isFound = false;\n for(let i = 0; i <= Math.floor(n/3); i++){\n if(3*i > n)\n break;\n else if(3*i === n){\n a = i;\n isFound = true;\n break;\n }\n for(let j = 0; j <= Math.floor(n/5); j++){\n if(3*i + 5*j > n)\n break;\n else if(3*i + 5*j === n){\n a = i; b = j;\n isFound = true;\n break;\n }\n for(let k = 0; k <= Math.floor(n/7); k++){\n if(3*i + 5*j + 7*k === n){\n a = i; b = j; c = k;\n isFound = true;\n break;\n }else if(3*i + 5*j + 7*k > n){\n break;\n }\n }\n }\n }\n\n if(isFound)\n console.log(a,b,c)\n else\n console.log(-1);\n }\n}\n"}, {"source_code": "var inputs = parseInt(readline());\nfor (var i = 0; i < inputs; i++) {\n var totalWindows = parseInt(readline());\n var rooms = [0, 0, 0];\n if (totalWindows < 3 || totalWindows === 4) {\n print(\"-1\");\n continue;\n } else {\n var isCompvared = false;\n\n if (totalWindows % 3 === 0) {\n rooms[0] = totalWindows / 3;\n print(rooms[0] + \" \" + rooms[1] + \" \" + rooms[2]);\n continue;\n }\n for (var j = Math.floor(totalWindows / 3); j >= 0; j--) {\n var leftOverWindows = totalWindows - 3 * j;\n\n if (leftOverWindows > 5 && leftOverWindows % 5 === 0) {\n rooms = [j, leftOverWindows / 5, 0];\n isCompvared = true;\n break;\n } else if (leftOverWindows > 7 && leftOverWindows % 7 === 0) {\n rooms = [j, 0, leftOverWindows / 7];\n isCompvared = true;\n break;\n } else if (leftOverWindows > 8 && leftOverWindows % 8 === 0) {\n var total = leftOverWindows / 8;\n rooms = [j + total, total, 0];\n isCompvared = true;\n break;\n }\n }\n if (isCompvared) {\n print(rooms[0] + \" \" + rooms[1] + \" \" + rooms[2]);\n } else {\n print(\"-1\");\n }\n }\n}\n"}, {"source_code": "/*\n......descrition.....\n...................\nA. Number of Apartments\ntime limit per test1 second\nmemory limit per test256 megabytes\ninputstandard input\noutputstandard output\nRecently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.\n\nMonocarp went around the building and counted n windows. Now he is wondering, how many apartments of each type the building may have.\n\nUnfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has n windows. If there are multiple answers, you can print any of them.\n\nHere are some examples:\n\nif Monocarp has counted 30 windows, there could have been 2 three-room apartments, 2 five-room apartments and 2 seven-room apartments, since 2⋅3+2⋅5+2⋅7=30;\nif Monocarp has counted 67 windows, there could have been 7 three-room apartments, 5 five-room apartments and 3 seven-room apartments, since 7⋅3+5⋅5+3⋅7=67;\nif Monocarp has counted 4 windows, he should have mistaken since no building with the aforementioned layout can have 4 windows.\nInput\nTh first line contains one integer t (1≤t≤1000) — the number of test cases.\n\nThe only line of each test case contains one integer n (1≤n≤1000) — the number of windows in the building.\n\nOutput\nFor each test case, if a building with the new layout and the given number of windows just can't exist, print −1.\n\nOtherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.\n\nExample\ninputCopy\n4\n30\n67\n4\n14\noutputCopy\n2 2 2\n7 5 3\n-1\n0 0 2 */\n\n\nvar testCasesNumber = readline();\nvar listOfWindowsNumber = [];\n\n//Saisie des données\n\nfor (var i = 0; i < testCasesNumber; i++) {\n listOfWindowsNumber[i] = readline();\n }\nvar resultx =[];\nvar resulty =[];\nvar resultz =[];\nvar k=0;\nfor (var i = 0; i < testCasesNumber; i++) {\n var number = parseInt(listOfWindowsNumber[i]);\n for(var x = 0; x < 334; x++){\n for(var y= 0; y < 201; y++){\n for(var z = 0;z < 143; z++){\n if ((x * 3 + y * 5 + z * 7)>number){break;}\n if (number == (x * 3 + y * 5 + z * 7)) { \n resultx.push(x);\n resulty.push(y);\n resultz.push(z);\n k++;\n \n }\n }\n }\n }\nif (k==0) {\n print(-1);}\n else {\n print(resultx[k-1],\" \",resulty[k-1], \" \", resultz[k-1]);\n \n }\n}\n"}, {"source_code": "/*\n......descrition.....\n...................\nA. Number of Apartments\ntime limit per test1 second\nmemory limit per test256 megabytes\ninputstandard input\noutputstandard output\nRecently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.\n\nMonocarp went around the building and counted n windows. Now he is wondering, how many apartments of each type the building may have.\n\nUnfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has n windows. If there are multiple answers, you can print any of them.\n\nHere are some examples:\n\nif Monocarp has counted 30 windows, there could have been 2 three-room apartments, 2 five-room apartments and 2 seven-room apartments, since 2⋅3+2⋅5+2⋅7=30;\nif Monocarp has counted 67 windows, there could have been 7 three-room apartments, 5 five-room apartments and 3 seven-room apartments, since 7⋅3+5⋅5+3⋅7=67;\nif Monocarp has counted 4 windows, he should have mistaken since no building with the aforementioned layout can have 4 windows.\nInput\nTh first line contains one integer t (1≤t≤1000) — the number of test cases.\n\nThe only line of each test case contains one integer n (1≤n≤1000) — the number of windows in the building.\n\nOutput\nFor each test case, if a building with the new layout and the given number of windows just can't exist, print −1.\n\nOtherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.\n\nExample\ninputCopy\n4\n30\n67\n4\n14\noutputCopy\n2 2 2\n7 5 3\n-1\n0 0 2\n\nTrois tableua des multipliant de 3 et 5 et 7 et un boolean found \npuis chercher si existe dans chaque tableau et mettre found a true\npuis cherchhr si somme de valeurs entre chaque deux tableau et mettre found a true\nsi not found afficher -1\n*/\n\n\nvar testCasesNumber = readline();\nvar listOfWindowsNumber = [];\nvar valus0fX3 =[0,\t3,\t6,\t9,\t12,\t15,\t18,\t21,\t24,\t27,\t30,\t33,\t36,\t39,\t42,\t45,\t48,\t51,\t54,\t57,\t60,\t63,\t66,\t69,\t72,\t75,\t78,\t81,\t84,\t87,\t90,\t93,\t96,\t99,\t102,\t105,\t108,\t111,\t114,\t117,\t120,\t123,\t126,\t129,\t132,\t135,\t138,\t141,\t144,\t147,\t150,\t153,\t156,\t159,\t162,\t165,\t168,\t171,\t174,\t177,\t180,\t183,\t186,\t189,\t192,\t195,\t198,\t201,\t204,\t207,\t210,\t213,\t216,\t219,\t222,\t225,\t228,\t231,\t234,\t237,\t240,\t243,\t246,\t249,\t252,\t255,\t258,\t261,\t264,\t267,\t270,\t273,\t276,\t279,\t282,\t285,\t288,\t291,\t294,\t297,\t300,\t303,\t306,\t309,\t312,\t315,\t318,\t321,\t324,\t327,\t330,\t333,\t336,\t339,\t342,\t345,\t348,\t351,\t354,\t357,\t360,\t363,\t366,\t369,\t372,\t375,\t378,\t381,\t384,\t387,\t390,\t393,\t396,\t399,\t402,\t405,\t408,\t411,\t414,\t417,\t420,\t423,\t426,\t429,\t432,\t435,\t438,\t441,\t444,\t447,\t450,\t453,\t456,\t459,\t462,\t465,\t468,\t471,\t474,\t477,\t480,\t483,\t486,\t489,\t492,\t495,\t498,\t501,\t504,\t507,\t510,\t513,\t516,\t519,\t522,\t525,\t528,\t531,\t534,\t537,\t540,\t543,\t546,\t549,\t552,\t555,\t558,\t561,\t564,\t567,\t570,\t573,\t576,\t579,\t582,\t585,\t588,\t591,\t594,\t597,\t600,\t603,\t606,\t609,\t612,\t615,\t618,\t621,\t624,\t627,\t630,\t633,\t636,\t639,\t642,\t645,\t648,\t651,\t654,\t657,\t660,\t663,\t666,\t669,\t672,\t675,\t678,\t681,\t684,\t687,\t690,\t693,\t696,\t699,\t702,\t705,\t708,\t711,\t714,\t717,\t720,\t723,\t726,\t729,\t732,\t735,\t738,\t741,\t744,\t747,\t750,\t753,\t756,\t759,\t762,\t765,\t768,\t771,\t774,\t777,\t780,\t783,\t786,\t789,\t792,\t795,\t798,\t801,\t804,\t807,\t810,\t813,\t816,\t819,\t822,\t825,\t828,\t831,\t834,\t837,\t840,\t843,\t846,\t849,\t852,\t855,\t858,\t861,\t864,\t867,\t870,\t873,\t876,\t879,\t882,\t885,\t888,\t891,\t894,\t897,\t900,\t903,\t906,\t909,\t912,\t915,\t918,\t921,\t924,\t927,\t930,\t933,\t936,\t939,\t942,\t945,\t948,\t951,\t954,\t957,\t960,\t963,\t966,\t969,\t972,\t975,\t978,\t981,\t984,\t987,\t990,\t993,\t996,\t999];\nvar valus0fX5 =[0,\t5,\t10,\t15,\t20,\t25,\t30,\t35,\t40,\t45,\t50,\t55,\t60,\t65,\t70,\t75,\t80,\t85,\t90,\t95,\t100,\t105,\t110,\t115,\t120,\t125,\t130,\t135,\t140,\t145,\t150,\t155,\t160,\t165,\t170,\t175,\t180,\t185,\t190,\t195,\t200,\t205,\t210,\t215,\t220,\t225,\t230,\t235,\t240,\t245,\t250,\t255,\t260,\t265,\t270,\t275,\t280,\t285,\t290,\t295,\t300,\t305,\t310,\t315,\t320,\t325,\t330,\t335,\t340,\t345,\t350,\t355,\t360,\t365,\t370,\t375,\t380,\t385,\t390,\t395,\t400,\t405,\t410,\t415,\t420,\t425,\t430,\t435,\t440,\t445,\t450,\t455,\t460,\t465,\t470,\t475,\t480,\t485,\t490,\t495,\t500,\t505,\t510,\t515,\t520,\t525,\t530,\t535,\t540,\t545,\t550,\t555,\t560,\t565,\t570,\t575,\t580,\t585,\t590,\t595,\t600,\t605,\t610,\t615,\t620,\t625,\t630,\t635,\t640,\t645,\t650,\t655,\t660,\t665,\t670,\t675,\t680,\t685,\t690,\t695,\t700,\t705,\t710,\t715,\t720,\t725,\t730,\t735,\t740,\t745,\t750,\t755,\t760,\t765,\t770,\t775,\t780,\t785,\t790,\t795,\t800,\t805,\t810,\t815,\t820,\t825,\t830,\t835,\t840,\t845,\t850,\t855,\t860,\t865,\t870,\t875,\t880,\t885,\t890,\t895,\t900,\t905,\t910,\t915,\t920,\t925,\t930,\t935,\t940,\t945,\t950,\t955,\t960,\t965,\t970,\t975,\t980,\t985,\t990,\t995,\t1000];\nvar valus0fX7 =[0,\t7,\t14,\t21,\t28,\t35,\t42,\t49,\t56,\t63,\t70,\t77,\t84,\t91,\t98,\t105,\t112,\t119,\t126,\t133,\t140,\t147,\t154,\t161,\t168,\t175,\t182,\t189,\t196,\t203,\t210,\t217,\t224,\t231,\t238,\t245,\t252,\t259,\t266,\t273,\t280,\t287,\t294,\t301,\t308,\t315,\t322,\t329,\t336,\t343,\t350,\t357,\t364,\t371,\t378,\t385,\t392,\t399,\t406,\t413,\t420,\t427,\t434,\t441,\t448,\t455,\t462,\t469,\t476,\t483,\t490,\t497,\t504,\t511,\t518,\t525,\t532,\t539,\t546,\t553,\t560,\t567,\t574,\t581,\t588,\t595,\t602,\t609,\t616,\t623,\t630,\t637,\t644,\t651,\t658,\t665,\t672,\t679,\t686,\t693,\t700,\t707,\t714,\t721,\t728,\t735,\t742,\t749,\t756,\t763,\t770,\t777,\t784,\t791,\t798,\t805,\t812,\t819,\t826,\t833,\t840,\t847,\t854,\t861,\t868,\t875,\t882,\t889,\t896,\t903,\t910,\t917,\t924,\t931,\t938,\t945,\t952,\t959,\t966,\t973,\t980,\t987,\t994];\n\n\n//Saisie des données\n\nfor (var i = 0; i < testCasesNumber; i++) {\n listOfWindowsNumber[i] = readline();\n }\n\nfor (var i = 0; i < testCasesNumber; i++) {\n var found=false;\n var number = parseInt(listOfWindowsNumber[i]);\n if (valus0fX3.indexOf(number,0)!=-1) {\n print (number/3,0,0);\n found=true;\n }\n \n if ((valus0fX5.indexOf(number,0)!=-1) && (found == false)) {\n print (0,number/5,0);\n found=true;\n }\n \n if ((valus0fX7.indexOf(number,0)!=-1) && (found == false)) {\n print (0,0,number/7);\n found=true;\n }\n \n for(var t3 in valus0fX3){\n if (found==true){\n break;\n }\n for (var t5 in valus0fX5){\n if (number==t3*3+t5*5){\n print(t3,t5,0);\n found=true;\n break;\n }\n }\n }\n \n for(var t32 in valus0fX3){\n if (found==true){\n break;\n }\n for (var t7 in valus0fX7){\n if (number==t32*3+t7*7){\n print(t32,0,t7);\n found=true;\n break;\n }\n }\n }\n\n \n for(var t52 in valus0fX5){\n if (found==true){\n break;\n }\n for (var t72 in valus0fX7){\n if (number==t52*5+t72*7){\n print(0,t52,t72);\n found=true;\n break;\n }\n }\n }\n/**/\n if (found==false){\n print(-1,\"inexistant\");\n}\n \n}\n"}], "src_uid": "b43dee2f223c869a35b1b11ceb9d2b6b"} {"nl": {"description": "Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input. ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)  — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$0 \\leq c_i \\leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.", "sample_inputs": ["5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3"], "sample_outputs": ["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"], "notes": "NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\\color{blue}{1},1,0,1]$$$; $$$B_2=[\\color{blue}{1},\\color{blue}{1},0,1]$$$; $$$B_3=[\\color{blue}{0},\\color{blue}{1},\\color{blue}{1},1]$$$; $$$B_4=[\\color{blue}{0},\\color{blue}{1},\\color{blue}{1},\\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nclass SegTree {\r\n constructor(nums = [], n = nums.length - 1) {\r\n this.nums = nums;\r\n this.n = n;\r\n this.root = this._newNode(0, n);\r\n this._build(this.root);\r\n this.update = this._update.bind(this, this.root);\r\n this.query = this._query.bind(this, this.root);\r\n }\r\n _newNode(l, r, val = 0, left = null, right = null) {\r\n return {\r\n val,\r\n l,\r\n r,\r\n left,\r\n right,\r\n add: 0\r\n };\r\n }\r\n _down(node) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n for (let child of [left, right]) {\r\n child.add += node.add;\r\n child.val += node.add * (child.r - child.l + 1);\r\n }\r\n node.add = 0;\r\n }\r\n _up(node) {\r\n const {\r\n left,\r\n right\r\n } = node;\r\n if (!left || !right) return;\r\n node.val = left.val + right.val;\r\n }\r\n _build(node = this.root) {\r\n const {\r\n l,\r\n r\r\n } = node;\r\n if (l === r) {\r\n var _this$nums$l;\r\n node.val = (_this$nums$l = this.nums[l]) !== null && _this$nums$l !== void 0 ? _this$nums$l : 0;\r\n return;\r\n }\r\n const mid = Math.floor((l + r) / 2);\r\n node.left = this._newNode(l, mid);\r\n node.right = this._newNode(mid + 1, r);\r\n this._build(node.left);\r\n this._build(node.right);\r\n node.val = node.left.val + node.right.val;\r\n }\r\n _update(node, x, y, z) {\r\n if (!node) return;\r\n const {\r\n l,\r\n r\r\n } = node;\r\n if (l === x && r === y) {\r\n node.add += z;\r\n node.val += z * (r - l + 1);\r\n return;\r\n }\r\n this._down(node);\r\n const mid = Math.floor((l + r) / 2);\r\n if (y <= mid) this._update(node.left, x, y, z);else if (x > mid) this._update(node.right, x, y, z);else this._update(node.left, x, mid, z), this._update(node.right, mid + 1, y, z);\r\n this._up(node);\r\n }\r\n _query(node, x, y) {\r\n if (y < x) return 0;\r\n if (!node) return 0;\r\n const {\r\n l,\r\n r\r\n } = node;\r\n if (l === x && r === y) return node.val;\r\n this._down(node);\r\n let res = 0,\r\n mid = Math.floor((l + r) / 2);\r\n if (y <= mid) res = this._query(node.left, x, y);else if (x > mid) res = this._query(node.right, x, y);else res = this._query(node.left, x, mid) + this._query(node.right, mid + 1, y);\r\n this._up(node);\r\n return res;\r\n }\r\n}\r\nfunction solve(n, a) {\r\n let res = new Array(n).fill(0),\r\n one = a.reduce((a, b) => a + b, 0) / n;\r\n const segTree = new SegTree(a);\r\n for (let i = n - 1; i >= 0; i--) {\r\n const cur = segTree.query(i, i);\r\n segTree.update(i - one + 1, i - 1, -1);\r\n if (cur === i + 1) {\r\n res[i] = 1;\r\n one--;\r\n }\r\n }\r\n console.log(res.join(' '));\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const c = (await read()).split(' ').map(Number);\r\n solve(n, c);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const n = +lines[l++]\r\n const arr = lines[l++].trim().split(' ').map(Number)\r\n output[i] = solve(n, arr)\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(n, arr) {\r\n let one = arr.reduce((s, x) => s + x, 0) / n\r\n let zero = n - one\r\n const last = Array(n).fill(n) // row of the first zero for each column\r\n for (let i = 0; i < zero; i++) {\r\n last[i] = n - 1\r\n }\r\n// console.log(one, zero, last)\r\n const ans = Array(n)\r\n for (let i = arr.length - 1; i >= 0; i--) {\r\n const a = i + 1 // if ans[i] = 1\r\n let b = (last[i] - 1) - (i + 1) + 1 // at least contains how many 1s\r\n if (i + 1 >= n) {\r\n b = 0\r\n }\r\n // console.log('sb', a, b, last[i])\r\n // const b = n - last[i]\r\n if (a + b === arr[i]) {\r\n ans[i] = 1\r\n } else {\r\n ans[i] = 0\r\n zero--\r\n last[zero] = i\r\n // console.log(zero, i)\r\n }\r\n }\r\n return ans.join(' ')\r\n}\r\n"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\n\n\nconst calc = (n, c)=>{\n if (n === 1) {\n if (c[0] === 0) return '0';\n else return '1';\n }\n if (c[n - 1] === 0) {\n return new Array(n).fill(0).join(' ');\n }\n\n let result = new Array(n).fill(1);\n\n let sum = 0;\n for (let i = 0; i < n; i++) {\n sum += c[i];\n }\n let ones = Math.round(sum / n);\n \n let idx = 0;\n while (idx < n && c[idx] === 0) {\n result[idx++] = 0;\n }\n\n while (idx < n) {\n if (result[idx] === 1) {\n if (c[idx] < n) result[c[idx]] = 0;\n } else {\n if (c[idx] + idx < n) result[c[idx] + idx] = 0;\n }\n idx++;\n }\n\n\n return result.join(' ');\n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let n = +readline();\n let c = ra();\n console.log(`${calc(n, c)}`);\n }\n}\n\n\n\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n let res = new Array(n).fill(0),\r\n sum = 0;\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (a[i] - sum >= i + 1) {\r\n res[i] = 1;\r\n sum++;\r\n } else {\r\n sum = 0;\r\n }\r\n }\r\n console.log(res.join(' '));\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const c = (await read()).split(' ').map(Number);\r\n solve(n, c);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n let res = new Array(n).fill(0),\r\n sum = 0;\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (a[i] - sum >= i + 1) {\r\n res[i] = 1;\r\n sum++;\r\n } else {\r\n sum = Math.max(0, sum - 1);\r\n }\r\n }\r\n console.log(res.join(' '));\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const c = (await read()).split(' ').map(Number);\r\n solve(n, c);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a) {\r\n let res = [],\r\n one = a.reduce((a, b) => a + b, 0) / n,\r\n p = new Array(n).fill(0),\r\n cur = 0;\r\n for (let i = 0; i < n; i++) {\r\n cur += p[i];\r\n res[i] = a[i] > cur ? 1 : 0;\r\n if (res[i]) {\r\n one--;\r\n const add = one - (a[i] - cur - (i + 1));\r\n p[i + 1] += 1;\r\n p[n - one - 1] += add;\r\n p[n - one] -= add;\r\n }\r\n }\r\n console.log(res.join(' '));\r\n}\r\n\r\nasync function main(read) {\r\n const t = Number(await read());\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n const c = (await read()).split(' ').map(Number);\r\n solve(n, c);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n let one = arr.reduce((s, x) => s + x, 0) / n\n let zero = n - one\n const last = Array(n).fill(n) // row of the last zero for each column\n for (let i = 0; i < zero; i++) {\n last[i] = n - 1\n }\n// console.log(one, zero)\n const ans = Array(n)\n for (let i = arr.length - 1; i >= 0; i--) {\n // const a = i + 1 // if ans[i] = 1\n // const b = Math.max(0, Math.min(zero, i + 1) - (i + 1)) // at least contains how many 1s\n // console.log('sb', a, b)\n const b = n - last[i]\n if (n - b === arr[i]) {\n ans[i] = 1\n } else {\n ans[i] = 0\n zero--\n last[zero] = i\n }\n }\n return ans.join(' ')\n}\n"}], "src_uid": "9dc1bee4e53ced89d827826f2d83dabf"} {"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 ≤ n ≤ 2·105, 2 ≤ m ≤ 10) — the number of books in the bookstore and the number of genres. The second line contains a sequence a1, a2, ..., an, where ai (1 ≤ ai ≤ m) 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 — the number of ways in which Jack can choose books. It is guaranteed that the answer doesn't exceed the value 2·109.", "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": "var summaryBooks = readline().split(' ')[0];\nvar array = readline().split(' ');\nvar categories = {};\nvar combinations = 0;\n\nfor (var i = 0; i < array.length; i++){\n if (categories[array[i]] === undefined)\n categories[array[i]] = 1;\n else\n categories[array[i]]++;\n}\n\nfor (category in categories){\n summaryBooks -= categories[category];\n combinations += categories[category]*summaryBooks;\n}\n\nprint(combinations);"}, {"source_code": "// O(n) time complexity, O(m) additional memory.\nvar input = readline().split(\" \").map(i => +i);\nvar n = input[0];\nvar m = input[1];\nvar genreHistogram = new Array(m).fill(0);\nfor (var ai of readline().split(\" \").map(i => +i)) {\n ++genreHistogram[ai - 1];\n}\nvar possibilities = 0;\nfor (var mh of genreHistogram) {\n // Each book within current genre can be combined with any book from any other genre.\n possibilities += mh * (n - mh);\n}\n// We took all pairs into account twice.\npossibilities /= 2;\nwrite(possibilities + \"\\n\");"}, {"source_code": "// O(n) time complexity, O(m) additional memory.\nvar input = readline().split(\" \").map(i => +i);\nvar n = input[0];\nvar m = input[1];\nvar genreHistogram = new Array(m).fill(0);\nfor (var ai of readline().split(\" \").map(i => +i)) {\n ++genreHistogram[ai - 1];\n}\nvar possibilities = 0;\nfor (var mh of genreHistogram) {\n // Each book within current genre can be combined with any book from any other genre.\n possibilities += mh * (n - mh);\n}\n// We took all pairs into account twice.\npossibilities /= 2;\nwrite(possibilities + \"\\n\");\n"}], "negative_code": [{"source_code": "var summaryBooks = readline().split(' ')[0];\nvar array = readline().split(' ');\nvar categories = {};\nvar combinations = 0;\n\nfor (var i = 0; i < array.length; i++){\n if (categories[i] === undefined)\n categories[i] = 1;\n else\n categories[i]++;\n}\n\nfor (category in categories){\n summaryBooks -= category;\n combinations += category*summaryBooks;\n}\n\nprint(combinations);"}], "src_uid": "e2ff228091ca476926b8e905f1bc8dff"} {"nl": {"description": "As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...", "input_spec": "The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z).", "output_spec": "Output YES if the string s contains heidi as a subsequence and NO otherwise.", "sample_inputs": ["abcheaibcdi", "hiedi"], "sample_outputs": ["YES", "NO"], "notes": "NoteA string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p."}, "positive_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nconst word = 'heidi';\n\nrl.on('line', (str) => {\n const matrix = new Array(word.length).fill(0).map(x => new Array(str.length).fill(0));\n\n for (let i = 0; i < word.length; i++) {\n for (let j = 0; j < str.length; j++) {\n if (word[i] === str[j]) {\n const prevDiagonal = matrix[i - 1] && matrix[i - 1][j - 1] || 0;\n matrix[i][j] = prevDiagonal + 1;\n }\n else {\n const prevRow = matrix[i - 1] && matrix[i - 1][j] || 0;\n const prevCell = matrix[i][j - 1] || 0;\n matrix[i][j] = Math.max(prevRow, prevCell);\n }\n }\n }\n\n if (matrix[matrix.length - 1][matrix[0].length - 1] === word.length) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n\n c++;\n});\n"}, {"source_code": "\nfunction solve(){\n\tvar fake = readline();\n\tif(fake.length>5){\n\t\tvar h = fake.indexOf(\"h\");\n\t\tif(h!= -1){\n\t\t\tvar e = fake.indexOf(\"e\", h+1);\n\t\t\tif (e!= -1){\n\t\t\t\tvar i = fake.indexOf(\"i\", e+1);\n\t\t\t\tif (i!= -1){\n\t\t\t\t\tvar d = fake.indexOf(\"d\", i+1);\n\t\t\t\t\tif(d!= -1){\n\t\t\t\t\t\tif (i != -1){\n\t\t\t\t\t\t\tvar i2 = fake.indexOf(\"i\", d+1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif((h!=-1 && e!= -1 && i !=-1 && d != -1 && i2 !=-1) && (h {\n const matrix = new Array(word.length).fill(0).map(x => new Array(str.length).fill(0));\n\n for (let i = 0; i < word.length; i++) {\n for (let j = 0; j < str.length; j++) {\n const prevRow = matrix[i - 1] && matrix[i - 1][j] || 0;\n const prevCell = matrix[i][j - 1] || 0;\n\n if (word[i] === str[j]) {\n const prevDiagonal = matrix[i - 1] && matrix[i - 1][j - 1] || 0;\n matrix[i][j] = Math.max(prevRow, prevCell, prevDiagonal) + 1;\n }\n else {\n matrix[i][j] = Math.max(prevRow, prevCell);\n }\n }\n }\n\n if (matrix[matrix.length - 1][matrix[0].length - 1] === word.length) {\n console.log('YES');\n }\n else {\n console.log('NO');\n }\n\n c++;\n});\n"}, {"source_code": "\nfunction solve(){\n\tvar fake = readline();\n\tif(fake.length>5){\n\t\tvar h = fake.indexOf(\"h\");\n\t\tvar e = fake.indexOf(\"e\");\n\t\tvar i = fake.indexOf(\"i\");\n\t\tvar d = fake.indexOf(\"d\");\n\t\tif (i != -1){\n\t\t\tvar i2 = fake.indexOf(\"i\", i+1);\n\t\t}\n\t\t\n\t\tif((h!=-1 && e!= -1 && i !=-1 && d != -1 && i2 !=-1) && (h {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nlet n;\r\nlet b;\r\nlet p;\r\nlet root;\r\nfunction solve() {\r\n const dist = af(n + 1).fill(INIT);\r\n dist[root] = 0;\r\n if (p[1] != root) {\r\n return false;\r\n }\r\n const edge = af(n + 1); // edge to parent\r\n edge[root] = 0;\r\n let tot = 1; // total distance to node\r\n for (let i = 2; i <= n; i++) {\r\n let u = p[i];\r\n if (dist[b[u]] == INIT) {\r\n return false;\r\n }\r\n edge[u] = tot - dist[b[u]];\r\n dist[u] = tot;\r\n tot++;\r\n }\r\n for (let i = 1; i <= n; i++) {\r\n printf(\"%d \", edge[i]);\r\n }\r\n printf(\"\\n\");\r\n return true;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n b = af(n + 1);\r\n for (let i = 1; i <= n; i++) {\r\n b[i] = nextInt();\r\n if (b[i] == i) {\r\n root = i;\r\n }\r\n }\r\n p = af(n + 1);\r\n for (let i = 1; i <= n; i++) {\r\n p[i] = nextInt();\r\n }\r\n if (!solve()) {\r\n printf(\"-1\\n\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst b = rna();\r\n\t\tconst p = rna();\r\n\r\n\t\tlet root;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tif (b[i] == i+1) {\r\n\t\t\t\troot = i;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst done = new Map();\r\n\t\tdone.set(root, 0);\r\n\r\n\t\tlet ans = [];\r\n\t\tans[root] = 0;\r\n\r\n\t\tlet mxpth = 0;\r\n\t\tfor (let v of p) {\r\n\t\t\tv--;\r\n\t\t\tif (v == root) {\r\n\t\t\t\tif (mxpth > 0) {\r\n\t\t\t\t\tans = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tlet u = b[v]; u--;\r\n\t\t\tif (done.has(u)) {\r\n\t\t\t\tconst pthl = done.get(u);\r\n\t\t\t\tif (pthl+1 > mxpth) {\r\n\t\t\t\t\tans[v] = 1;\r\n\t\t\t\t\tmxpth = pthl+ans[v];\r\n\t\t\t\t\tdone.set(v, mxpth);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tans[v] = mxpth-pthl+1;\r\n\t\t\t\t\tmxpth = pthl+ans[v];\r\n\t\t\t\t\tdone.set(v, mxpth);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tans = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const ps = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, ps, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, ps, arr) {\n ps.unshift(0)\n //\n const ans = Array(n + 1).fill(-1)\n const dist = Array(n + 1).fill(-1)\n let now = 0\n if (ps[arr[0]] !== arr[0]) return -1\n ans[arr[0]] = 0\n dist[arr[0]] = now\n for (let i = 1; i < arr.length; i++) {\n now++\n const x = arr[i]\n const p = ps[x]\n if (p === x) return -1\n if (dist[p] < 0) return -1\n dist[x] = now\n ans[x] = dist[x] - dist[p]\n if (ans[x] <= 0) return -1\n }\n ans.shift()\n return ans.join(' ')\n}\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = cb=>readline().split(' ').map(cb||(a=>+a))\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst calc = (testN)=>{\n // READING:\n let [n] = ra();\n let B = ra(a=>a-1);\n let P = ra(a=>a-1);\n LT({n, B, P});\n // PROCESSING:\n if (B[P[0]]!=P[0])\n return -1;\n let dist = new Array(n).fill(-1);\n dist[P[0]] = 0;\n for (let i=1; i {\r\n return string.trim();\r\n });\r\n let t = inputReader.readNumber();\r\n\r\n function solve() {\r\n // let n = inputReader.readNumber();\r\n // let b= inputReader.readNumberArray();\r\n // let p = inputReader.readNumberArray();\r\n // b.unshift(-1);\r\n // let root = -1;\r\n\r\n // b.forEach((element, ind, arr) => {\r\n // if(element == ind) root = element;\r\n // });\r\n\r\n // dist = new Array(n + 1).fill(-1);\r\n // dist[root] = 0;\r\n\r\n // if(p[0] != root) {\r\n // console.log(-1);\r\n // return;\r\n // }\r\n\r\n // p.every((element, ind, arr) => {\r\n // if(b[element] == -1) {\r\n // return false;\r\n // }\r\n // if(element == root) dist[ind] = 0;\r\n // else dist[element] = dist[ind - 1] + 1;\r\n // });\r\n\r\n // let w = b.map((x, ind, arr) => {\r\n // if(ind > 0)\r\n // return dist[x] - dist[ind];\r\n // });\r\n\r\n // let ans = w.join(\" \").trim();\r\n // console.log(ans);\r\n\r\n let n = inputReader.readNumber();\r\n let b = inputReader.readNumberArray();\r\n let p = inputReader.readNumberArray();\r\n b.unshift(-Infinity);\r\n p.unshift(-Infinity);\r\n let dist = new Array(n + 1).fill(-1);\r\n let root = -1;\r\n b.forEach((x, ind, arr) => {\r\n if (x == ind) root = x;\r\n });\r\n\r\n if (p[1] != root) {\r\n console.log(-1);\r\n return;\r\n }\r\n\r\n dist[root] = 0;\r\n for (let i = 2; i <= n; i++) {\r\n if (dist[b[p[i]]] == -1) {\r\n console.log(-1);\r\n return;\r\n }\r\n dist[p[i]] = dist[p[i - 1]] + 1;\r\n }\r\n\r\n let w = dist.map((x, i, a) => {\r\n if (i > 0) return x - dist[b[i]];\r\n });\r\n\r\n let ans = w.join(\" \").trim();\r\n console.log(ans);\r\n }\r\n\r\n while (t--) {\r\n solve();\r\n }\r\n}\r\n\r\nvar _inputData = \"\";\r\nfunction cacheInput(data) {\r\n _inputData += data;\r\n}\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf8\");\r\nprocess.stdin.on(\"data\", cacheInput).on(\"end\", _main);\r\n\r\nfunction _inputReader() {\r\n function readNumber() {\r\n return Number(_inputLines[_lineNumber++]);\r\n }\r\n\r\n function readNumberArray() {\r\n return _inputLines[_lineNumber++].split(\" \").map((val) => Number(val));\r\n }\r\n\r\n return {\r\n readNumber,\r\n readNumberArray,\r\n };\r\n}\r\n"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst b = rna();\r\n\t\tconst p = rna();\r\n\r\n\t\tlet root;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tif (b[i] == i+1) {\r\n\t\t\t\troot = i;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst done = new Map();\r\n\t\tdone.set(root, 0);\r\n\r\n\t\tlet ans = [];\r\n\t\tans[root] = 0;\r\n\r\n\t\tlet mxpth = 0;\r\n\t\tfor (let v of p) {\r\n\t\t\tv--;\r\n\t\t\tif (v == root) continue;\r\n\t\t\tlet u = b[v]; u--;\r\n\t\t\tif (done.has(u)) {\r\n\t\t\t\tconst pthl = done.get(u);\r\n\t\t\t\tif (pthl+1 > mxpth) {\r\n\t\t\t\t\tans[v] = 1;\r\n\t\t\t\t\tmxpth = pthl+ans[v];\r\n\t\t\t\t\tdone.set(v, mxpth);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tans[v] = mxpth-pthl+1;\r\n\t\t\t\t\tmxpth = pthl+ans[v];\r\n\t\t\t\t\tdone.set(v, mxpth);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tans = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "4b512c39e71e34064c820958dde9f4a1"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ integers.You want to make all elements of $$$a$$$ equal to zero by doing the following operation exactly three times: Select a segment, for each number in this segment we can add a multiple of $$$len$$$ to it, where $$$len$$$ is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of $$$a$$$ equal to zero.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$): the number of elements of the array. The second line contains $$$n$$$ elements of an array $$$a$$$ separated by spaces: $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$).", "output_spec": "The output should contain six lines representing three operations. For each operation, print two lines: The first line contains two integers $$$l$$$, $$$r$$$ ($$$1 \\le l \\le r \\le n$$$): the bounds of the selected segment. The second line contains $$$r-l+1$$$ integers $$$b_l, b_{l+1}, \\dots, b_r$$$ ($$$-10^{18} \\le b_i \\le 10^{18}$$$): the numbers to add to $$$a_l, a_{l+1}, \\ldots, a_r$$$, respectively; $$$b_i$$$ should be divisible by $$$r - l + 1$$$.", "sample_inputs": ["4\n1 3 2 4"], "sample_outputs": ["1 1 \n-1\n3 4\n4 2\n2 4\n-3 -6 -6"], "notes": null}, "positive_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let n = pi(readline());\n let a = ti(readline().split(' '));\n if(n === 1){\n console.log(1,1);\n console.log(-1*a[0]);\n console.log(1,1);\n console.log(0);\n console.log(1,1);\n console.log(0);\n return;\n }\n let res = '';\n console.log(1,n);\n for(let i = 0; i < n; i++){\n res = `${res}${-1*n*a[i]} `;\n }\n console.log(res.trim());\n console.log(2,n);\n res = '';\n for(let i = 1; i < n; i++){\n res = `${res}${(n-1)*a[i]} `;\n }\n console.log(res.trim());\n console.log(1,1);\n console.log((n-1)*a[0]);\n}"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn, init) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);\n if (b < a) return [];\n let arr = Array(b - a + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return mid;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n let sub = [];\n a = a || 0;\n b = b || (this.length - 1);\n for (let i = a; i <= b; i++) {\n sub.push(this[i])\n if (fn(this[i], i, this)) {\n arr.push(sub);\n sub = [];\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nlet MOD = 998244353\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + MOD) % MOD;\n}\n\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let n = $(), a = $(n), x\n if (n == 1) {\n log(`1 1\\n${-a[0]}\\n1 1\\n0\\n1 1\\n0`);\n return;\n }\n out.push(`1 ${n - 1}`);\n out.push(Arr(n - 1, i => (x = (n - 1) * a[i], a[i] += x, x)).join(' '))\n out.push(`${n} ${n}`);\n out.push(a[n - 1] ? (x = n - a[n - 1] % n, a[n - 1] += x, x) : 0)\n out.push(`1 ${n}`);\n out.push(Arr(n, i => -a[i]).join(' '))\n log(out.join('\\n'))\n}\n"}], "negative_code": [{"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn, init) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);\n if (b < a) return [];\n let arr = Array(b - a + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return mid;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n let sub = [];\n a = a || 0;\n b = b || (this.length - 1);\n for (let i = a; i <= b; i++) {\n sub.push(this[i])\n if (fn(this[i], i, this)) {\n arr.push(sub);\n sub = [];\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nlet MOD = 998244353\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + MOD) % MOD;\n}\n\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let n = $(), a = $(n), x\n if (n == 1) {\n log(`1 1\\n${-a[0]}\\n1 1\\n0\\n1 1\\n0`);\n return;\n }\n out.push(`1 ${n - 1}`);\n out.push(Arr(n - 1, i => (x = (n - 1) * a[i], a[i] += x, x)).join(' '))\n out.push(`${n} ${n}`);\n out.push(a[n - 1] ? (x = n - n % a[n - 1], a[n - 1] += x, x) : 0)\n out.push(`1 ${n}`);\n out.push(Arr(n, i => -a[i]).join(' '))\n log(out.join('\\n'))\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let n = pi(readline());\n let a = ti(readline().split(' '));\n let res = '';\n console.log(1,n);\n for(let i = 0; i < n; i++){\n res = `${res}${-1*n*a[i]} `;\n }\n console.log(res.trim());\n console.log(2,n);\n res = '';\n for(let i = 1; i < n; i++){\n res = `${res}${(n-1)*a[i]} `;\n }\n console.log(res.trim());\n console.log(1);\n console.log((n-1)*a[0]);\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let n = pi(readline());\n let a = ti(readline().split(' '));\n let res = '';\n console.log(1,n);\n for(let i = 0; i < n; i++){\n res = `${res}${-1*n*a[i]} `;\n }\n console.log(res.trim());\n console.log(2,n);\n res = '';\n for(let i = 1; i < n; i++){\n res = `${res}${(n-1)*a[i]} `;\n }\n console.log(res.trim());\n console.log(1,1);\n console.log((n-1)*a[0]);\n}"}], "src_uid": "d15a758cfdd7a627822fe8be7db4f60b"} {"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$$$) — the number of displays. The second line contains $$$n$$$ integers $$$s_1, s_2, \\ldots, s_n$$$ ($$$1 \\le s_i \\le 10^9$$$) — 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$$$) — 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 — 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": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\nconst INF = Number.MAX_SAFE_INTEGER\n\nmain()\n\nfunction main() {\n const n = getInt()\n const arr = getInts()\n const cost = getInts()\n\n let ans = INF\n for (let i = 1; i < n; ++i) {\n let l = INF\n let r = INF\n for (let j = i - 1; j >= 0; --j) {\n if (arr[j] < arr[i]) {\n l = Math.min(l, cost[j])\n }\n }\n\n for (let j = i + 1; j < n; ++j) {\n if (arr[j] > arr[i]) {\n r = Math.min(r, cost[j])\n }\n }\n\n ans = Math.min(ans, l + r + cost[i])\n }\n print(ans === INF ? -1 : ans)\n}"}], "negative_code": [], "src_uid": "4a48b828e35efa065668703edc22bf9b"} {"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, a2, ..., an.Your task is to paint a cardiogram by given sequence ai.", "input_spec": "The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.", "output_spec": "Print max |yi - yj| 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 « / » (slash), « \\ » (backslash), « » (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": ["/ \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 /"], "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": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tdata = tokenizeIntegers(readline()),\n\t\tlevel = 0, minLevel = 0, maxLevel = 0, direction = 1,\n\t\tlength = 0;\n\tfor (var i = 0; i < n; ++i) {\n\t\tlevel += direction*(data[i]-1);\n\t\tminLevel = Math.min(minLevel, level);\n\t\tmaxLevel = Math.max(maxLevel, level);\n\t\tdirection *= -1;\n\t\tlength += data[i];\n\t}\n\tvar height = maxLevel - minLevel + 1;\n\tvar g = new Array(height);\n\tfor (var r = 0; r < height; ++r) {\n\t\tg[r] = new Array(length);\n\t\tfor (var c = 0; c < length; ++c) {\n\t\t\tg[r][c] = ' ';\n\t\t}\n\t}\n\tvar r = height-1+minLevel, c = 0, direction = -1, ch = '/',\n\t\topposite = { \"\\\\\": \"/\", \"/\": \"\\\\\" };\n\tfor (var i = 0; i < n; ++i) {\n\t\tvar d = data[i];\n\t\tg[r][c++] = ch;\n\t\tfor (var j = 1; j < d; ++j) {\n\t\t\tr += direction;\n\t\t\tg[r][c++] = ch;\n\t\t}\n\t\tdirection *= -1;\n\t\tch = opposite[ch];\n\t}\n\tvar lines = [];\n\tfor (var r = 0; r < height; ++r) {\n\t\tlines.push(g[r].join(''));\n\t}\n\tprint(lines.join('\\n'));\n}\n\nmain();\n"}], "negative_code": [], "src_uid": "76285a60c21538db17d268a5e06c2270"} {"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$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$) — the number of wheels. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$0 \\leq a_i \\leq 9$$$) — 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}$$$ — 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  — 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": "const main = (input) => {\r\n input = input.split('\\n')\r\n\r\n const t = parseInt(input[0])\r\n let cnt = 0\r\n for (let i = 0; i < t; i++) {\r\n const n = parseInt(input[1 + cnt + 2 * i])\r\n const a = input[1 + cnt + 2 * i + 1].split(' ').map((x) => parseInt(x))\r\n\r\n let ans = [...a]\r\n for (let j = 0; j < n; j++) {\r\n const [_, b] = input[1 + cnt + 2 * i + 2 + j].trim().split(' ')\r\n const d = Array.from(b).reduce(\r\n (prev, current) => prev + (current === 'U' ? -1 : 1),\r\n 0\r\n )\r\n ans[j] += d\r\n ans[j] %= 10\r\n ans[j] += 10\r\n ans[j] %= 10\r\n }\r\n console.log(ans.map((x) => String(x)).join(' '))\r\n\r\n cnt += n\r\n }\r\n}\r\n\r\nmain(require('fs').readFileSync(0).toString())"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var c = readLine();\r\n let arr = [];\r\n while (b--) {\r\n arr.push(readLine());\r\n }\r\n var res = solveMeFirst(arr, c);\r\n let out = \"\";\r\n if (res) {\r\n for (let i = 0; i < res.length; i++) {\r\n out += res[i] + \" \";\r\n }\r\n console.log(out);\r\n }\r\n }\r\n}\r\nfunction solveMeFirst(arr, str) {\r\n str = str.split(\" \");\r\n for (let i = 0; i < arr.length; i++) {\r\n let cnt = 0;\r\n for (let j = 2; j < arr[i].length; j++) {\r\n if (arr[i][j] === \"D\") {\r\n cnt++;\r\n }\r\n if (arr[i][j] === \"U\") {\r\n cnt--;\r\n }\r\n }\r\n str[i] = +str[i];\r\n str[i] += cnt;\r\n if (str[i] < 0) {\r\n let temp = str[i] / 10;\r\n str[i] = Math.round((temp + 1) * 10);\r\n }\r\n str[i] %= 10;\r\n }\r\n return str;\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "function Solution() {\n let t = 0;\n const N = Number(lines[t++]);\n const R = [];\n for (let i = 0; i < N; i++) {\n const n = Number(lines[t++]);\n const initArr = lines[t++].split(' ').map((item) => Number(item));\n for (let j = 0; j < n; j++) {\n const [numStr, str] = lines[t++].split(' ');\n const num = Number(numStr);\n for (let z = 0; z < num; z++) {\n if (str[z] === 'D') initArr[j] = (initArr[j] + 1) % 10;\n else initArr[j] = (initArr[j] - 1 + 10) % 10;\n }\n }\n R.push(initArr.join(' '));\n }\n return R.join('\\n');\n}\n\nconst readline = require('readline')\n \nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n console.log(Solution());\n});"}, {"source_code": "function Solution() {\n let t = 0;\n const N = Number(lines[t++]);\n const R = [];\n for (let i = 0; i < N; i++) {\n const n = Number(lines[t++]);\n const initArr = lines[t++].split(' ').map((item) => Number(item));\n const res = [];\n for (let j = 0; j < n; j++) {\n const [numStr, str] = lines[t++].split(' ');\n const num = Number(numStr);\n let count = 0;\n for (let z = 0; z < num; z++) {\n if (str[z] === 'D') count += 1;\n else count -=1;\n }\n const target = initArr[j] + count;\n res[j] = target >= 0 ? target % 10 : (target % 10 + 10) % 10;\n }\n R.push(res.join(' '));\n }\n return R.join('\\n');\n}\n\nconst readline = require('readline')\n \nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n console.log(Solution());\n});"}, {"source_code": "const rdline = require('readline');\r\n\r\nconst rl = rdline.createInterface({\r\n input: process.stdin\r\n});\r\n\r\nlet lines = [];\r\nrl.on('line', (line) => {\r\n lines.push(line);\r\n}).on('close', () => {\r\n // input in lines\r\n solve();\r\n});\r\n\r\nlet line = 0;\r\nconst readline = () => lines[line++];\r\n\r\nsolve = () => {\r\n var t = parseInt(readline());\r\n for (let i = 0; i < t; i++) {\r\n var m = [];\r\n var n = parseInt(readline());\r\n var s = readline().split().join().replace(/\\s/g, '');\r\n for (var j = 0; j < n; j++) {\r\n var z = parseInt(s[j]);\r\n var b = readline();\r\n var p = b.split(' ')[1];\r\n for (let k = 0; k < p.length; k++) {\r\n if (p[k] === 'U') {\r\n if (z === 0) {\r\n z = 9;\r\n } else {\r\n z--;\r\n } \r\n }\r\n if (p[k] === 'D') {\r\n if (z === 9) {\r\n z = 0;\r\n } else {\r\n z++;\r\n }\r\n }\r\n }\r\n m[j] = z;\r\n }\r\n console.log(m.join(' '));\r\n }\r\n}"}, {"source_code": "\r\n\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var tests = parseInt(readline());\r\n for (let t = 0;t < tests; ++t) {\r\n let n = parseInt(readline());\r\n let s = readline().split(' ');\r\n \r\n let data = Array(n);\r\n let res = [];\r\n for (let i = 0; i < n;++i) {\r\n res.push(parseInt(s[i]));\r\n data[i] = readline().split(' ');\r\n }\r\n for (let i = 0; i < n;++i) {\r\n for (let j = 0;j < data[i][1].length; ++j) {\r\n if (data[i][1].charAt(j) === 'U') {\r\n res[i] = (res[i]-1+10)%10;\r\n } else if (data[i][1].charAt(j) === 'D') {\r\n res[i] = (res[i]+1+10)%10;\r\n }\r\n }\r\n }\r\n var ress = res.join(' ').toString();\r\n console.log(ress);\r\n }\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n const move = lines.slice(l, l + n).map(str => str.trim().split(' '))\n l += n\n output[i] = solve(n, arr, move)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr, move) {\n return arr.map((x, i) => {\n move[i] = move[i][1]\n for (let j = 0; j < move[i].length; j++) {\n const d = move[i][j] === 'D' ? -1 : 1\n x -= d\n }\n x = x % 10\n x = (x + 10) % 10\n return x\n }).join(' ')\n}\n"}, {"source_code": "// https://stackoverflow.com/questions/20086849/how-to-read-from-stdin-line-by-line-in-node\r\n// // cat .\\input.txt | node .\\script.js\r\n'use strict';\r\nlet data = ''; // raw\r\nlet inputs = ''; // iterator\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n};\r\nconst update = (v, dir) => {\r\n if (dir == 'D') {\r\n if (v == 9) return 0\r\n return v + 1\r\n }\r\n if (dir == 'U') {\r\n if (v == 0) return 9\r\n return v - 1\r\n }\r\n}\r\nasync function main(read) {\r\n try {\r\n let tasks = parseInt(await read())\r\n let result = []\r\n let current_combination = null\r\n for (let i = 0; i < tasks; i++) {\r\n const sub_length = parseInt(await read())\r\n current_combination = (await read()).split(' ').map(Number)\r\n for (let j = 0; j < sub_length; j++) {\r\n const element = (await read());\r\n const [num, content] = element.split(' ')\r\n for (let k = 0; k < content.length; k++) {\r\n const element = content[k];\r\n current_combination[j] = update(current_combination[j], element)\r\n }\r\n }\r\n result[i] = current_combination.join(' ')\r\n }\r\n return result.join('\\n')\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => data += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = data.split('\\n').values();\r\n const result = await main(read);\r\n // console.log(result)\r\n process.stdout.write(result);\r\n});\r\n\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n \r\n_input = \"\";\r\nprocess.stdin.on(\"data\", function (input) {\r\n _input += input; \r\n});\r\n \r\nprocess.stdin.on(\"end\", function () {\r\n processData(_input);\r\n});\r\n \r\nfunction processData(input) {\r\n const lines = input.split(\"\\n\");\r\n let startLine = 1;\r\n for (let i = 1; i <= lines[0]; i++) {\r\n startLine = processTC(lines, startLine);\r\n }\r\n}\r\n \r\nfunction processTC(lines, startLine) {\r\n const n = Number(lines[startLine]);\r\n const seq = lines[startLine+1].split(\" \").map(x => Number(x));\r\n let str = \"\";\r\n for (let i = 0; i < n; i++) {\r\n const num = startLine+2+i;\r\n const [stepsN, steps] = lines[num].split(\" \");\r\n const res = getInitialDigit(seq[i], steps, stepsN);\r\n str += res + \" \";\r\n }\r\n console.log(str.trim());\r\n return startLine+(n+2);\r\n}\r\n\r\nfunction getInitialDigit(num, steps, n) {\r\n for (let i = 0; i < n; i++) {\r\n const diff = steps.charAt(i) === \"U\" ? -1 : 1;\r\n num=num+diff;\r\n if (num===10) num = 0;\r\n if (num===-1) num = 9;\r\n }\r\n return num;\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split('\\n')\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let times = parseInt(readline());\r\n for (let i = 0; i < times; i++) {\r\n let cellNumber = parseInt(readline());\r\n let cellFinal = readline()\r\n .split(' ')\r\n .map((number) => {\r\n return parseInt(number);\r\n });\r\n for (let j = 0; j < cellNumber; j++) {\r\n let counter = 0;\r\n let [len, str] = readline().split(' ');\r\n for (let char of str) {\r\n counter += char === 'D' ? 1 : -1;\r\n }\r\n cellFinal[j] = (cellFinal[j] + (counter % 10)) % 10;\r\n if (cellFinal[j] < 0) {\r\n cellFinal[j] += 10;\r\n }\r\n }\r\n console.log(...cellFinal);\r\n }\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr1 = [];\r\n for (let i = 0; i < n; i++) {\r\n arr1.push(readline().trim().split(\" \"));\r\n }\r\n for (let i = 0; i < n; i++) {\r\n let x = arr1[i][1];\r\n for (let j = 0; j < x.length; j++) {\r\n if (x[j] === \"U\") {\r\n if (arr[i] === 0) arr[i] = 9;\r\n else arr[i] = (arr[i] - 1) % 10;\r\n } else arr[i] = (arr[i] + 1) % 10;\r\n }\r\n }\r\n let res = \"\";\r\n for (let i = 0; i < n; i++) res += arr[i] + \" \";\r\n console.log(res);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n// console.log(input)\r\nvar T = readline();\r\n// var inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n var n = readline()//.split(' ').map((x) => parseInt(x));\r\n var a = readline().split(' ').map((x) => parseInt(x));\r\n var ans = [];\r\n for(var i=0;i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n const mapVal = char => char === 'D' ? -1 : 1;\r\n const n = Number(readline());\r\n const digits = readline().split(' ').map(Number);\r\n let seq = new Array(n);\r\n for (let i = 0; i < n; i++) {\r\n seq[i] = readline().split(' ')[1];\r\n seq[i] = (digits[i] - seq[i].split('').map(mapVal).reduce((a, b) => a + b, 0) + 100) % 10;\r\n }\r\n\r\n let res = seq.map(String).join(' ');\r\n output(res);\r\n }\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tvar c = nextInt();\r\n\t\t\tvar cy = next();\r\n\t\t\tfor(var j = 0; j < c; j++){\r\n\t\t\t\tif(cy[j] == \"U\"){\r\n\t\t\t\t\tlist[i]--;\r\n\t\t\t\t}else{\r\n\t\t\t\t\tlist[i]++;\r\n\t\t\t\t}\r\n\t\t\t\tlist[i] += 10;\r\n\t\t\t\tlist[i] %= 10;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(myconv(list, 8));\r\n\t}\r\n}\r\n"}, {"source_code": "var t = parseInt(readline());\r\n \r\nfor (var i = 0; i < t; i++) {\r\n var n = parseInt(readline());\r\n var seq = readline().split(\" \");\r\n \r\n for (var j = 0; j < n; j++) {\r\n var str = readline().split(\" \");\r\n \r\n for (var k = 0; k < str[0]; k++) {\r\n if (str[1][k] === \"D\") {\r\n seq[j]++;\r\n } else if (str[1][k] === \"U\") {\r\n seq[j]--;\r\n }\r\n }\r\n\r\n seq[j] = (seq[j] + 10) % 10;\r\n }\r\n \r\n print(seq.join(\" \"));\r\n}"}, {"source_code": "var limit = parseInt(readline());\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var wheels = parseInt(readline());\r\n var caseArray = readline().split(\" \");\r\n var result = \"\";\r\n for (var j = 0; j < wheels; j++)\r\n {\r\n var current = readline().split(\" \");\r\n var value = parseInt(caseArray[j]);\r\n for (var k = 0; k < parseInt(current[0]); k++)\r\n {\r\n if (current[1][k] == 'D')\r\n {\r\n if (value === 9) value = 0; else value++;\r\n }\r\n else if (value === 0) value = 9; else value--;\r\n }\r\n result += `${value} `;\r\n }\r\n print(result);\r\n}"}, {"source_code": "T = readline()\r\n\r\nwhile(T--){\r\n n = readline()\r\n x = readline().split(' ')\r\n\r\n for(j=0;j +t);\r\n for(var k = 0; k < t1; k++){\r\n var t3 = readline().split(' ');\r\n nums.push(t3[1])\r\n }\r\n print(Cypher(t2,nums));\r\n \r\n}\r\n \r\nfunction Cypher(nums,arr){\r\n\r\n var res = [];\r\n for(var i = 0; i=0; j--){\r\n if(k[j] == 'D'){\r\n if(n==9)n=0;\r\n else n++;\r\n }else{\r\n if(n==0)n=9;\r\n else n--;\r\n }\r\n }\r\n return n;\r\n}\r\n\r\nvar test = readline()\r\n\r\nfor(var i=0; i parseInt(x));\r\n var ans = [];\r\n for (var i =0; i < n; i++) {\r\n var line = readline().split(' ');\r\n var seq = line[1];\r\n var f = a[i];\r\n for (var j = seq.length-1; j >= 0; j--) {\r\n if (seq[j] == 'D') {\r\n f = (f + 1)%10;\r\n } else {\r\n f = f-1;\r\n if (f < 0) {\r\n f = 9;\r\n }\r\n }\r\n }\r\n ans.push(f);\r\n }\r\n print(ans.join(' '));\r\n }"}], "negative_code": [{"source_code": "const main = (input) => {\r\n input = input.split('\\n')\r\n\r\n const t = parseInt(input[0])\r\n let cnt = 0\r\n for (let i = 0; i < t; i++) {\r\n const n = parseInt(input[1 + cnt + 2 * i])\r\n const a = input[1 + cnt + 2 * i + 1].split(' ').map((x) => parseInt(x))\r\n\r\n let ans = [...a]\r\n for (let j = 0; j < n; j++) {\r\n const [_, b] = input[1 + cnt + 2 * i + 2 + j].split(' ')\r\n console.log('b:', b)\r\n const d = Array.from(b).reduce(\r\n (prev, current) => prev + (current === 'U' ? -1 : 1),\r\n 0\r\n )\r\n console.log('d:', d)\r\n ans[j] += d\r\n ans[j] %= 10\r\n ans[j] += 10\r\n ans[j] %= 10\r\n }\r\n console.log(ans.map((x) => String(x)).join(' '))\r\n\r\n cnt += n\r\n }\r\n}\r\n\r\nmain(require('fs').readFileSync(0).toString())"}, {"source_code": "const main = (input) => {\r\n input = input.split('\\n')\r\n\r\n const t = parseInt(input[0])\r\n let cnt = 0\r\n for (let i = 0; i < t; i++) {\r\n const n = parseInt(input[1 + cnt + 2 * i])\r\n const a = input[1 + cnt + 2 * i + 1].split(' ').map((x) => parseInt(x))\r\n\r\n let ans = [...a]\r\n console.log('ans:', ans)\r\n for (let j = 0; j < n; j++) {\r\n const [_, b] = input[1 + cnt + 2 * i + 2 + j].split(' ')\r\n const d = Array.from(b).reduce(\r\n (prev, current) => prev + (current === 'U' ? -1 : 1),\r\n 0\r\n )\r\n console.log('d:', d)\r\n ans[j] += d\r\n ans[j] %= 10\r\n ans[j] += 10\r\n ans[j] %= 10\r\n }\r\n console.log(ans.map((x) => String(x)).join(' '))\r\n\r\n cnt += n\r\n }\r\n}\r\n\r\nmain(require('fs').readFileSync(0).toString())"}, {"source_code": "const main = (input) => {\r\n input = input.split('\\n')\r\n\r\n const t = parseInt(input[0])\r\n let cnt = 0\r\n for (let i = 0; i < t; i++) {\r\n const n = parseInt(input[1 + cnt + 2 * i])\r\n const a = input[1 + cnt + 2 * i + 1].split(' ').map((x) => parseInt(x))\r\n\r\n let ans = [...a]\r\n for (let j = 0; j < n; j++) {\r\n const [_, b] = input[1 + cnt + 2 * i + 2 + j].split(' ')\r\n const d = Array.from(b).reduce(\r\n (prev, current) => prev + (current === 'U' ? -1 : 1),\r\n 0\r\n )\r\n ans[j] += d\r\n ans[j] += 10\r\n ans[j] %= 10\r\n }\r\n console.log(ans.map((x) => String(x)).join(' '))\r\n\r\n cnt += n\r\n }\r\n}\r\n\r\nmain(require('fs').readFileSync(0).toString())"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var c = readLine();\r\n let arr = [];\r\n while (b--) {\r\n arr.push(readLine());\r\n }\r\n var res = solveMeFirst(arr, c);\r\n let out = \"\";\r\n if (res) {\r\n for (let i = 0; i < res.length; i++) {\r\n out += res[i] + \" \";\r\n }\r\n console.log(out);\r\n }\r\n }\r\n}\r\nfunction solveMeFirst(arr, str) {\r\n str = str.split(\" \");\r\n for (let i = 0; i < arr.length; i++) {\r\n let cnt = 0;\r\n for (let j = 2; j < arr[i].length; j++) {\r\n if (arr[i][j] === \"D\") {\r\n cnt++;\r\n }\r\n if (arr[i][j] === \"U\") {\r\n cnt--;\r\n }\r\n }\r\n str[i] = +str[i];\r\n str[i] += cnt;\r\n if (str[i] < 0) {\r\n let temp = str[i] / 10;\r\n str[i] = (temp + 1) * 10;\r\n }\r\n str[i] %= 10;\r\n }\r\n return str;\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.on(\"SIGINT\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var c = readLine();\r\n let arr = [];\r\n while (b--) {\r\n arr.push(readLine());\r\n }\r\n var res = solveMeFirst(arr, c);\r\n let out = \"\";\r\n if (res) {\r\n for (let i = 0; i < res.length; i++) {\r\n out += res[i] + \" \";\r\n }\r\n console.log(out);\r\n }\r\n }\r\n}\r\nfunction solveMeFirst(arr, str) {\r\n str = str.split(\" \");\r\n for (let i = 0; i < arr.length; i++) {\r\n let cnt = 0;\r\n for (let j = 2; j < arr[i].length; j++) {\r\n if (arr[i][j] === \"D\") {\r\n cnt++;\r\n }\r\n if (arr[i][j] === \"U\") {\r\n cnt--;\r\n }\r\n }\r\n str[i] = +str[i];\r\n str[i] += cnt;\r\n if (str[i] < 0) {\r\n let temp = str[i] / 10;\r\n str[i] = (temp + 1) * 10;\r\n }\r\n str[i] %= 10;\r\n }\r\n return str;\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction swap(arr, i, j) {\r\n let temp = arr[i];\r\n arr[i] = arr[j];\r\n arr[j] = temp;\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var c = readLine();\r\n let arr = [];\r\n while (b--) {\r\n arr.push(readLine());\r\n }\r\n var res = solveMeFirst(arr, c);\r\n let out = \"\";\r\n if (res) {\r\n for (let i = 0; i < res.length; i++) {\r\n out += res[i] + \" \";\r\n }\r\n console.log(out);\r\n }\r\n }\r\n}\r\nfunction solveMeFirst(arr, str) {\r\n str = str.split(\" \");\r\n for (let i = 0; i < arr.length; i++) {\r\n for (let j = 2; j < arr[i].length; j++) {\r\n if (arr[i][j] === \"D\") {\r\n if (str[i] == \"9\") str[i] = 0;\r\n else str[i]++;\r\n }\r\n if (arr[i][j] === \"U\") {\r\n if (str[i] == \"0\") str[i] = 9;\r\n else str[i] = Math.abs(str[i] - 1);\r\n }\r\n }\r\n }\r\n return str;\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\n\r\nvar input_stdin = \"\";\r\nvar input_stdin_array = \"\";\r\nvar input_currentline = 0;\r\n\r\nprocess.stdin.on(\"data\", function (data) {\r\n input_stdin += data;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n input_stdin_array = input_stdin.split(\"\\n\");\r\n // console.log(input_stdin_array);\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return input_stdin_array[input_currentline++];\r\n}\r\n\r\nfunction swap(arr, i, j) {\r\n let temp = arr[i];\r\n arr[i] = arr[j];\r\n arr[j] = temp;\r\n}\r\n\r\nfunction main() {\r\n var a = readLine();\r\n while (a--) {\r\n var b = readLine();\r\n var c = readLine();\r\n let arr = [];\r\n while (b--) {\r\n arr.push(readLine());\r\n }\r\n var res = solveMeFirst(arr, c);\r\n let out = \"\";\r\n if (res) {\r\n for (let i = 0; i < res.length; i++) {\r\n out += res[i] + \" \";\r\n }\r\n console.log(out);\r\n }\r\n }\r\n}\r\nfunction solveMeFirst(arr, str) {\r\n str = str.split(\" \");\r\n for (let i = 0; i < arr.length; i++) {\r\n for (let j = 2; j < arr[i].length; j++) {\r\n if (arr[i][j] === \"D\") {\r\n str[i]++;\r\n }\r\n if (arr[i][j] === \"U\") {\r\n if (str[i] == \"0\") str[i] = 9;\r\n else str[i] = Math.abs(str[i] - 1);\r\n }\r\n }\r\n str[i] = str[i] % 10;\r\n }\r\n return str;\r\n}\r\n\r\n// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));\r\n// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));\r\n"}, {"source_code": "var t = parseInt(readline());\r\n \r\nfor (var i = 0; i < t; i++) {\r\n var n = parseInt(readline());\r\n var seq = readline().split(\" \");\r\n \r\n for (var j = 0; j < n; j++) {\r\n var str = readline().split(\" \");\r\n \r\n for (var k = 0; k < str[0]; k++) {\r\n if (str[1][k] === \"D\") {\r\n seq[j]++;\r\n } else if (str[1][k] === \"U\") {\r\n seq[j]--;\r\n }\r\n }\r\n \r\n seq[j] %= 10;\r\n }\r\n \r\n print(seq);\r\n}"}, {"source_code": "var t = parseInt(readline());\r\n \r\nfor (var i = 0; i < t; i++) {\r\n var n = parseInt(readline());\r\n var seq = readline().split(\" \");\r\n \r\n for (var j = 0; j < n; j++) {\r\n var str = readline().split(\" \");\r\n \r\n for (var k = 0; k < str[0]; k++) {\r\n if (str[1][k] === \"D\") {\r\n seq[n]++;\r\n } else if (str[1][k] === \"U\") {\r\n seq[n]--;\r\n }\r\n }\r\n \r\n seq[j] %= 10;\r\n }\r\n \r\n print(seq);\r\n}"}, {"source_code": "var t = parseInt(readline());\r\n\r\nfor (var i = 0; i < t; i++) {\r\n var n = parseInt(readline());\r\n var seq = readline().split(\" \");\r\n \r\n for (var j = 0; j < n; j++) {\r\n var str = readline().split(\" \");\r\n \r\n for (var k = 0; k < str[0]; k++) {\r\n if (str[1][k] === \"D\") {\r\n seq[n]++;\r\n } else if (str[1][k] === \"U\") {\r\n seq[n]--;\r\n }\r\n }\r\n \r\n seq[n] %= 10;\r\n }\r\n \r\n print(seq);\r\n}\r\n"}, {"source_code": "T = readline()\r\n\r\nwhile(T--){\r\n n = readline()\r\n x = readline().split(' ')\r\n\r\n for(j=0;j +t);\r\n for(var k = 0; k < t1; k++){\r\n var t3 = readline().split(' ');\r\n nums.push(t3[1])\r\n }\r\n print(Cypher(t2,nums));\r\n \r\n}\r\n \r\nfunction Cypher(nums,arr){\r\n\r\n var res = [];\r\n for(var i = 0; i {\n input += i\n})\n\n\nprocess.stdin.on('end', () => {\n input = input.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main()\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt() {\n return parseInt(input[ptr++])\n}\n\nfunction readString() {\n return input[ptr++]\n}\n\nfunction readStrings() {\n return input[ptr++].split(' ')\n}\n\nfunction readInts() {\n return input[ptr++].split(' ').map(a => parseInt(a))\n}\n\nfunction main() {\n let t = readInt()\n while(t--) {\n const [n, k] = readInts()\n const s = (\"#\" + readString()).split('')\n const half = Math.ceil(k / 2)\n let total = 0\n for(let i = 1; i <= half; i++) {\n const alpha = new Array(26).fill(0)\n let count = 0\n for(let j = i; j <= n; j+= k) {\n alpha[s[j].charCodeAt(0) - 97]++\n count++\n }\n if(k % 2 === 0 || i !== half) {\n for(let j = n - i + 1; j >= 1; j-= k) {\n alpha[s[j].charCodeAt(0) - 97]++\n count++\n }\n }\n total += count - Math.max(...alpha)\n // wr(alpha, count, Math.max(...alpha), i)\n }\n wr(total)\n }\n}\n"}, {"source_code": "for(var t=Number(readline());t;t--){\n var a = readline().trim().split(/\\s/).map(x=>Number(x));\n var s = readline();\n var n = a[0];\n var k = a[1];\n var c = n/k;\n var res = 0;\n const z = \"a\".charCodeAt();\n for(var i=0; i<(k&~1)/2; i++){\n var l = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];\n for(var j=0;j0?s+t:t,0,1,_i]);\n }\n else if(_t[5]>=0){\n t=st[_t[5]];\n t[3]+=a[n]=0){\n t=st[_t[5]];\n t[3]+=a[_t[1]]<_t[2]?_t[4]:_t[3];\n t[4]+=_t[4];\n st.pop();\n }\n else return _t[3];\n }\n}\nprint(dfs(0,-Infinity));"}, {"source_code": "var n=+readline(),a=readline().split(' '),i,b=new Array(n),t=[],j=0;\nfor(i=1;i=(v=s+t[i][1]))dfs(k,v);\n}\ndfs(0,0);\nprint(n-K);"}], "negative_code": [{"source_code": "var n=+readline(),a=readline().split(' '),k=0,i,b=new Array(n),t=[],j=0;\nfor(i=1;i {\n let i = 0, j = s.length - 1;\n let l = '', r = '', n = 0;\n while (i < j) {\n while (s[i] !== '(' && i < j) i++;\n while (s[j] !== ')' && i < j) j--;\n if (i !== j) { l = l + `${i++ + 1} `; r = `${j-- + 1} ` + r; n++; }\n }\n if (!n) return 0;\n return `1\\n${2*n}\\n${l + r}`;\n}\nprint(problem(readline()))\n"}, {"source_code": "var str = readline().split('');\nvar i = 0;\nvar j = str.length - 1;\nvar result = [];\nwhile (i < j) {\n if (str[i] === '(') {\n if (str[j] === ')') {\n result.push(i+1);\n result.push(j+1);\n i++;\n j--;\n }\n else {\n j--;\n }\n }\n else {\n i++;\n }\n}\nif (result.length) {\n result = result.sort((a,b) => a - b);\n print('1');\n print(result.length);\n print(result.join(' '));\n} else {\n print('0');\n}\n"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main(arr)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a, i) {\n if(i === undefined) return parseInt(a.shift())\n else return parseInt(a[i])\n}\n\nfunction readInts(a, i) {\n if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))\n else return arr[i].split(' ').map(a => parseInt(a))\n}\n\nfunction main(input) {\n const s = input[0]\n const len = s.length\n let i = 0, j = len - 1\n let ans = []\n while(i <= j) {\n if(s[i] === '(' && s[j] === ')') {\n ans.push(j + 1)\n ans.unshift(++i)\n j--\n }\n else if(s[i] !== '(') i++\n else if(s[j] !== ')') j--\n }\n if(ans.length === 0) wr(0)\n else {\n sort(ans)\n wr(1)\n wr(ans.length)\n wr(ans.join(' '))\n }\n}"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n\n\n\n\n\n function foo (str) {\n let k = 0;\n let aResult = [];\n let result = [];\n\n let lft = 0;\n let rght = str.length - 1;\n\n while (lft < rght) {\n if (str[lft] === '(') {\n while(lft < rght) {\n if (str[rght] === ')') {\n result.push(lft + 1);\n result.push(rght + 1);\n lft++;\n rght--;\n break;\n } else {\n rght--;\n }\n }\n\n } else {\n lft++\n }\n }\n\n result.sort((a, b) => a - b);\n\n if (result.length) {\n aResult[0] = result;\n k++;\n const resSet = new Set(result);\n const subStr = str.split('').filter((v, index) => !resSet.has(index + 1)).join('');\n const subRes = foo(subStr);\n\n if (subRes[0] !== 0) {\n k = k + subRes[0];\n aResult = aResult.concat(subRes[1])\n }\n }\n return [k, aResult];\n }\n\n let result = foo(lines[0]);\n console.log(result[0]);\n if (result[1].length) {\n let answer = '';\n result[1].forEach(v => answer += v.length + '\\n' + v.join(' ') + '\\n');\n console.log(answer);\n }\n})"}, {"source_code": "const processData = (lines) => {\n const str = lines[0]\n let refinedStr = str.slice(0)\n const ops = []\n let size = 0\n let index = []\n const left = []\n const right = []\n for (let j =0; j= 0 && leftCounter < left.length) {\n const leftPos = left[leftCounter]\n let rightPos = right[rightCounter]\n leftCounter++\n if (leftPos > rightPos) {\n break\n }\n acc.push(leftPos, rightPos)\n rightCounter--\n }\n if (acc.length > 0) {\n console.log(1)\n console.log(acc.length)\n console.log(acc.sort((a, b) => a - b).map(x => x+1).join(' '))\n } else {\n console.log(0)\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;it-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(p){if(o=i.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),i.default.writeFileSync(\"output.txt\",l),console.log(l),i.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{o=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function a(){return o[u++]}function f(){return a().split(\" \").map((t=>parseFloat(t)))}function c(){return a().split(\"\")}e.default={runMain:h,runEachTest:t=>{h((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:a,nextNumbers:f,nextBigNumbers:function(){return a().split(\" \").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r0?1:0),0!=n.length&&(i.default.puts(n.length),i.default.puts(n.sortAsc().join(\" \")))}))},129:t=>{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let s = io.readline()\n// let n = s.length\n// \n// let left = 0\n// let right = n - 1\n// \n// let toRemove = []\n// \n// while (left <= right) {\n// if (s[left] == \"(\" && s[right] == \")\") {\n// toRemove.push(left + 1)\n// toRemove.push(right + 1)\n// left++\n// right--\n// continue\n// }\n// \n// if (s[left] == \")\") {\n// left++\n// }\n// \n// if (s[right] == \"(\") {\n// right--\n// }\n// }\n// \n// io.puts(toRemove.length > 0 ? 1 : 0)\n// \n// if (toRemove.length == 0) {\n// return\n// }\n// \n// io.puts(toRemove.length)\n// \n// io.puts(toRemove.sortAsc().join(\" \"))\n// }\n// \n// // io.runEachTest(main)\n// io.runMain(main)"}], "negative_code": [{"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main(arr)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a, i) {\n if(i === undefined) return parseInt(a.shift())\n else return parseInt(a[i])\n}\n\nfunction readInts(a, i) {\n if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))\n else return arr[i].split(' ').map(a => parseInt(a))\n}\n\nfunction main(input) {\n const s = input[0]\n const len = s.length\n let i = 0, j = len - 1\n let ans = []\n while(i <= j) {\n if(s[i] === '(' && s[j] === ')') {\n ans.push(j + 1)\n ans.unshift(++i)\n j--\n }\n else if(s[i] !== '(') i++\n else if(s[j] !== ')') j--\n }\n if(ans.length === 0) wr(0)\n else {\n sort(ans)\n if(ans.length === s.length) wr(0)\n else {\n wr(1)\n wr(ans.length)\n wr(ans.join(' '))\n }\n }\n}"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main(arr)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a, i) {\n if(i === undefined) return parseInt(a.shift())\n else return parseInt(a[i])\n}\n\nfunction readInts(a, i) {\n if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))\n else return arr[i].split(' ').map(a => parseInt(a))\n}\n\nfunction main(input) {\n const s = input[0]\n const len = s.length\n let i = 0, j = len - 1\n let ans = []\n while(i <= j) {\n if(s[i] === '(' && s[j] === ')') {\n ans.push(j + 1)\n ans.unshift(++i)\n j--\n }\n else if(s[i] !== '(') i++\n else if(s[j] !== ')') j--\n }\n if(ans.length === 0) wr(0)\n else {\n sort(ans)\n if(ans.length === s.length) wr(-1)\n else {\n wr(1)\n wr(ans.length)\n wr(ans.join(' '))\n }\n }\n}"}, {"source_code": "\nprocess.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n main(arr)\n})\n\nfunction wr(...x) {\n console.log(...x)\n}\n\nfunction sort(a, inc = true) {\n if(inc) a.sort((a, b) => a - b)\n else a.sort((a, b) => b - a)\n}\n\nfunction readInt(a, i) {\n if(i === undefined) return parseInt(a.shift())\n else return parseInt(a[i])\n}\n\nfunction readInts(a, i) {\n if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))\n else return arr[i].split(' ').map(a => parseInt(a))\n}\n\nfunction main(input) {\n const s = input[0]\n const len = s.length\n let i = 0, j = len - 1\n let ans = []\n while(i <= j) {\n if(s[i] === '(' && s[j] === ')') {\n ans.push(j + 1)\n ans.unshift(++i)\n j--\n }\n else if(s[i] !== '(') i++\n else if(s[j] !== ')') j--\n }\n if(ans.length === 0) wr(0)\n else {\n sort(ans)\n if(ans.length === s.length) ans.pop()\n wr(1)\n wr(ans.length)\n wr(ans.join(' '))\n }\n}"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL);\n\n\n\n\n\n function foo (str) {\n let k = 0;\n let aResult = [];\n let result = [];\n\n let lft = 0;\n let rght = str.length - 1;\n\n while (lft < rght) {\n if (str[lft] === '(') {\n while(lft < rght) {\n if (str[rght] === ')') {\n result.push(lft + 1);\n result.push(rght + 1);\n lft++;\n rght--;\n break;\n } else {\n rght--;\n }\n }\n\n } else {\n lft++\n }\n }\n\n result.sort((a, b) => a - b);\n aResult[0] = result;\n\n if (result.length) {\n k++;\n const resSet = new Set(result);\n const subStr = str.split('').filter((v, index) => !resSet.has(index + 1)).join('');\n const subRes = foo(subStr);\n\n if (subRes[0] !== 0) {\n k = k + subRes[0];\n aResult = aResult.concat(subRes[1])\n }\n }\n return [k, aResult];\n }\n\n let result = foo(lines[0]);\n console.log(result[0]);\n if (result[1].length) {\n let answer = '';\n result[1].forEach(v => answer += v.length + '\\n' + v.join(' ') + '\\n');\n console.log(answer);\n }\n})"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;it-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(h){if(s=i.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),i.default.writeFileSync(\"output.txt\",l),console.log(l),i.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{o+=t})),process.stdin.on(\"end\",(e=>{s=o.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return s[u++]}function p(){return f().split(\" \").map((t=>parseFloat(t)))}function c(){return f().split(\"\")}e.default={runMain:a,runEachTest:t=>{a((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:f,nextNumbers:p,nextBigNumbers:function(){return f().split(\" \").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r=0;e--)\")\"==t[e]&&o++,r[e]=o;r=r.reverse();let s=Math.floor((t.length-1)/2),u=[e[s],r[s]].min();if(0==u)return void i.default.puts(0);i.default.puts(1),i.default.puts(2*u),n=u,o=u;for(let e=0;e=0&&(\")\"==t[e]&&(o--,l.push(e+1)),0!=o);--e);i.default.puts(l.reverse().join(\" \"))}))},129:t=>{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let s = io.readline()\n// \n// let nrOpen = Array(s.length).fill(0)\n// let nrClosed = Array(s.length).fill(0)\n// \n// let open = 0\n// \n// for (let i = 0; i < s.length; ++i) {\n// if (s[i] == \"(\") {\n// open++\n// }\n// nrOpen[i] = open\n// }\n// \n// let closed = 0\n// \n// for (let i = s.length - 1; i >= 0; i--) {\n// if (s[i] == \")\") {\n// closed++\n// }\n// nrClosed[i] = closed\n// }\n// \n// nrClosed = nrClosed.reverse()\n// \n// let i = Math.floor((s.length - 1) / 2)\n// \n// let v = [nrOpen[i], nrClosed[i]].min()\n// \n// if (v == 0) {\n// io.puts(0)\n// return\n// }\n// \n// io.puts(1)\n// io.puts(v * 2)\n// \n// open = v\n// closed = v\n// \n// for (let i = 0; i < s.length; ++i) {\n// if (s[i] == \"(\") {\n// open--\n// io.put(i + 1 + \" \")\n// }\n// if (open == 0) {\n// break\n// }\n// }\n// \n// let rev = []\n// \n// for (let i = s.length - 1; i >= 0; --i) {\n// if (s[i] == \")\") {\n// closed--\n// rev.push(i + 1)\n// }\n// if (closed == 0) {\n// break\n// }\n// }\n// \n// io.puts(rev.reverse().join(\" \"))\n// }\n// \n// // io.runEachTest(main)\n// io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;it-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(h){if(s=i.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),i.default.writeFileSync(\"output.txt\",l),console.log(l),i.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{o+=t})),process.stdin.on(\"end\",(e=>{s=o.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return s[u++]}function p(){return f().split(\" \").map((t=>parseFloat(t)))}function c(){return f().split(\"\")}e.default={runMain:a,runEachTest:t=>{a((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:f,nextNumbers:p,nextBigNumbers:function(){return f().split(\" \").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r=0;e--)\")\"==t[e]&&o++,r[e]=o;r=r.reverse();let s=Math.floor(t.length/2),u=[e[s],r[s]].min();if(0==u)return void i.default.puts(0);i.default.puts(1),i.default.puts(2*u),n=u,o=u;for(let e=0;e=0&&(\")\"==t[e]&&(o--,l.push(e+1)),0!=o);--e);i.default.puts(l.reverse().join(\" \"))}))},129:t=>{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let s = io.readline()\n// \n// let nrOpen = Array(s.length).fill(0)\n// let nrClosed = Array(s.length).fill(0)\n// \n// let open = 0\n// \n// for (let i = 0; i < s.length; ++i) {\n// if (s[i] == \"(\") {\n// open++\n// }\n// nrOpen[i] = open\n// }\n// \n// let closed = 0\n// \n// for (let i = s.length - 1; i >= 0; i--) {\n// if (s[i] == \")\") {\n// closed++\n// }\n// nrClosed[i] = closed\n// }\n// \n// nrClosed = nrClosed.reverse()\n// \n// let i = Math.floor(s.length / 2)\n// \n// let v = [nrOpen[i], nrClosed[i]].min()\n// \n// if (v == 0) {\n// io.puts(0)\n// return\n// }\n// \n// io.puts(1)\n// io.puts(v * 2)\n// \n// open = v\n// closed = v\n// \n// for (let i = 0; i < s.length; ++i) {\n// if (s[i] == \"(\") {\n// open--\n// io.put(i + 1 + \" \")\n// }\n// if (open == 0) {\n// break\n// }\n// }\n// \n// let rev = []\n// \n// for (let i = s.length - 1; i >= 0; --i) {\n// if (s[i] == \")\") {\n// closed--\n// rev.push(i + 1)\n// }\n// if (closed == 0) {\n// break\n// }\n// }\n// \n// io.puts(rev.reverse().join(\" \"))\n// }\n// \n// // io.runEachTest(main)\n// io.runMain(main)"}], "src_uid": "f78d04f699fc94103e5b08023949854d"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$. Both strings have length $$$n$$$ and consist of lowercase Latin letters. The characters in the strings are numbered from $$$1$$$ to $$$n$$$.You can successively perform the following move any number of times (possibly, zero): swap any two adjacent (neighboring) characters of $$$s$$$ (i.e. for any $$$i = \\{1, 2, \\dots, n - 1\\}$$$ you can swap $$$s_i$$$ and $$$s_{i + 1})$$$. You can't apply a move to the string $$$t$$$. The moves are applied to the string $$$s$$$ one after another.Your task is to obtain the string $$$t$$$ from the string $$$s$$$. Find any way to do it with at most $$$10^4$$$ such moves.You do not have to minimize the number of moves, just find any sequence of moves of length $$$10^4$$$ or less to transform $$$s$$$ into $$$t$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the input contains the string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "If it is impossible to obtain the string $$$t$$$ using moves, print \"-1\". Otherwise in the first line print one integer $$$k$$$ — the number of moves to transform $$$s$$$ to $$$t$$$. Note that $$$k$$$ must be an integer number between $$$0$$$ and $$$10^4$$$ inclusive. In the second line print $$$k$$$ integers $$$c_j$$$ ($$$1 \\le c_j < n$$$), where $$$c_j$$$ means that on the $$$j$$$-th move you swap characters $$$s_{c_j}$$$ and $$$s_{c_j + 1}$$$. If you do not need to apply any moves, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.", "sample_inputs": ["6\nabcdef\nabdfec", "4\nabcd\naccd"], "sample_outputs": ["4\n3 5 4 5", "-1"], "notes": "NoteIn the first example the string $$$s$$$ changes as follows: \"abcdef\" $$$\\rightarrow$$$ \"abdcef\" $$$\\rightarrow$$$ \"abdcfe\" $$$\\rightarrow$$$ \"abdfce\" $$$\\rightarrow$$$ \"abdfec\".In the second example there is no way to transform the string $$$s$$$ into the string $$$t$$$ through any allowed moves."}, "positive_code": [{"source_code": "\nfunction main() {\n const is = new Scanner();\n is.nextInt();\n const s = is.nextLine().split('');\n const t = is.nextLine().split('');\n const container = {};\n s.forEach((item) => {\n if (container[item] === undefined) {\n container[item] = 1;\n } else {\n container[item] += 1;\n }\n });\n t.forEach((item) => {\n if (container[item] !== undefined) {\n container[item] -= 1;\n }\n });\n let isPossible = true;\n for (const i in container) {\n if (container.hasOwnProperty(i)) {\n if (container[i] !== 0) {\n isPossible = false;\n break;\n }\n }\n }\n\n\n if (!isPossible) {\n console.log(-1);\n } else {\n let j;\n const swaps = [];\n t.forEach((item, i) => {\n if (item !== s[i]) {\n j = s.lastIndexOf(item);\n for (let k = j - 1; k !== i - 1; k -= 1) {\n [s[k], s[k + 1]] = [s[k + 1], s[k]];\n swaps.push(k + 1);\n }\n }\n });\n console.log(swaps.length);\n if (swaps.length) {\n console.log(swaps.join(' '));\n }\n }\n}\n\n\n/*\n * Api Scanner\n */\nclass Scanner {\n constructor() {\n this.index = 0;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n\n nextLine() {\n return this.lines[this.index++].trim(); // eslint-disable-line\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray(fn) {\n const array = this.nextLine().split(' ');\n return fn === String ? array : array.map(fn);\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (input) => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}, {"source_code": "function main() {\n n = readInt()\n s = Array.from(readLine())\n t = Array.from(readLine())\n res = []\n for (i=0; ii; j--){\n [s[j], s[j-1]]= [s[j-1], s[j]]\n res.push(j)\n }\n }\n }\n }\n print(res.length)\n print(res.join(\" \"))\n}\n\nconst TESTCASES = false\n/* NodeJS Footer by @satyamcse and @shivam1420*/\nvar readline = require('readline');\nprocess.stdin.setEncoding('utf-8');\nvar rl = readline.createInterface({input: process.stdin, output: process.stdout});\nvar inp = \"\";\nrl.on('line' , v => inp += v+\"\\n\");\nrl.on('close', () => {\n inp = inp.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n if (TESTCASES){\n const cnt = readInt()\n for (let i = 0; i a - b)\n else a.sort((a, b) => b - a)\n}\nvar ptr = 0\nfunction print(...x) {console.log(...x)}\nfunction readInt() {return +inp[ptr++]}\nfunction readLine() {return inp[ptr++]}\nfunction readInts() {return inp[ptr++].split(' ').map(a => +a)}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction inp() {\n return inputString[currentLine++];\n}\n\nfunction out(str) {\n console.log(str);\n}\n\nfunction stringArrayToNumbers(str) {\n var array = str.split(\" \");\n var result = [];\n for (var i = 0; i < array.length; i++) {\n result.push(parseInt(array[i]));\n }\n return result;\n}\nfunction main() {\n let n = parseInt(inp());\n let s, t;\n s = inp();\n t = inp();\n let s1 = [];\n let i, j;\n //check\n var dc = new Object();\n for (i = 0; i < n; i++) {\n s1.push(s[i]);\n if (s[i] in dc) {\n dc[s[i]] += 1\n }\n else {\n dc[s[i]] = 1\n }\n }\n var chk = 0;\n for (i = 0; i < n; i++) {\n if (t[i] in dc) {\n dc[t[i]] -= 1;\n if (dc[t[i]] < 0) {\n chk = 1;\n break\n }\n }\n else {\n chk = 1;\n break\n }\n }\n if (chk == 1) {\n out(-1)\n }\n else {\n var ans = [];\n for (i = 0; i < n; i++) {\n if (s1[i] != t[i]) {\n let pos = i;\n for (j = i + 1; j < n; j++) {\n if (s1[j] == t[i]) {\n pos = j;\n break;\n }\n }\n for (j = pos - 1; j >= i; j--) {\n ans.push(j+1);\n let t = s1[j];\n s1[j] = s1[j + 1];\n s1[j + 1] = t;\n }\n }\n }\n out(ans.length);\n let ans1 = '';\n for (i = 0; i < ans.length; i++) {\n ans1 += ans[i] + ' ';\n }\n out(ans1);\n\n }\n\n}"}, {"source_code": "function main(){\n var c = +readline();\n var str = readline();\n var strRes = readline();\n var result = [];\n\n for(var i = 0; i < c; i++){\n if(str[i] != strRes[i]){\n var s = str.substr(i).indexOf(strRes[i]);\n if(s == -1){\n print(-1);\n return;\n }\n s+=i;\n while(s != i){\n result.push(s);\n str = str.substr(0,s-1) + str[s] + str[s-1] + str.substr(s+1);\n s--;\n }\n }\n }\n if(result.length > 10000){\n print(-1);\n return;\n }\n print(result.length + '\\n');\n result.forEach(function(v){\n print(v + ' ');\n })\n}\n\nmain();"}], "negative_code": [{"source_code": "\nfunction main() {\n const is = new Scanner();\n is.nextInt();\n const s = is.nextLine().split('');\n const t = is.nextLine().split('');\n const container = {};\n s.forEach((item) => {\n if (container[item] === undefined) {\n container[item] = 1;\n } else {\n container[item] += 1;\n }\n });\n t.forEach((item) => {\n container[item] -= 1;\n });\n\n if (Object.keys(container).some(key => container[key] !== 0)) {\n console.log(-1);\n } else {\n let j;\n const swaps = [];\n t.forEach((item, i) => {\n if (item !== s[i]) {\n j = s.lastIndexOf(item);\n for (let k = j - 1; k !== i - 1; k -= 1) {\n [s[k], s[k + 1]] = [s[k + 1], s[k]];\n swaps.push(k + 1);\n }\n }\n });\n console.log(swaps.length);\n if (swaps.length) {\n console.log(swaps.join(' '));\n }\n }\n}\n\n\n/*\n * Api Scanner\n */\nclass Scanner {\n constructor() {\n this.index = 0;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n\n nextLine() {\n return this.lines[this.index++]; // eslint-disable-line\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray(fn) {\n const array = this.nextLine().split(' ');\n return fn === String ? array : array.map(fn);\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (input) => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}, {"source_code": "function main(){\n var c = +readline();\n var str = readline();\n var strRes = readline();\n var result = [];\n\n for(var i = 0; i < c; i++){\n if(str[i] != strRes[i]){\n var s = str.substr(i).indexOf(strRes[i]);\n if(s == -1){\n print(-1);\n return;\n }\n s+=i;\n while(s != i){\n result.push(s);\n var v = str[s];\n str[s] = str[s-1];\n str[s-1] = v;\n s--;\n }\n }\n }\n if(result.length>10000){\n print(-1);\n return;\n }\n print(result.length + '\\n');\n result.forEach(function(v){\n print(v + ' ');\n })\n}\n\nmain();"}], "src_uid": "48e323edc41086cae52cc0e6bdd84e35"} {"nl": {"description": "One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said \"lala.\" at the end of her sentences, while Rainbow always said \"miao.\" at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is. ", "input_spec": "The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.", "output_spec": "For each sentence, output \"Freda's\" if the sentence was said by Freda, \"Rainbow's\" if the sentence was said by Rainbow, or \"OMG>.< I don't know!\" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with \"miao.\" and ends with \"lala.\", or satisfies neither of the conditions. ", "sample_inputs": ["5\nI will go to play with you lala.\nwow, welcome.\nmiao.lala.\nmiao.\nmiao ."], "sample_outputs": ["Freda's\nOMG>.< I don't know!\nOMG>.< I don't know!\nRainbow's\nOMG>.< I don't know!"], "notes": null}, "positive_code": [{"source_code": "print(function(n) {\n\tvar ans = [];\n\tfor (var i = 0; i < n; i++){\n\t\tvar s = readline();\n\t\tvar a = /^miao\\./.test(s);\n\t\tvar b = /lala\\.$/.test(s);\n\t\tif(a&&!b) ans.push('Rainbow\\'s');\n\t\telse if(b&&!a) ans.push('Freda\\'s');\n\t\telse ans.push('OMG>.< I don\\'t know!');\n\t}\n\treturn ans.join('\\n');\n}(+readline()));"}], "negative_code": [], "src_uid": "ee9ba877dee1a2843e885a18823cbff0"} {"nl": {"description": "Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, 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 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, 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": "var Point = function(x, y) { this.x = parseInt(x); this.y = parseInt(y); };\nvar Line = function(p) {\n this.a = parseInt(p[0]);\n this.b = parseInt(p[1]);\n this.c = parseInt(p[2]);\n this.getY = function(x) { return (this.a * -x) - this.c; };\n this.getLiner = function() { return -this.a / this.b; };\n};\nvar app = {\n lineLength : 0,\n A : {}, B : {},\n result : 0,\n main : function() {\n this.initialize();\n this.readValues();\n this.sovleResult();\n this.printResult();\n },\n initialize : function() {\n app.result = 0;\n },\n readValues : function() {\n var ACor = readline().split(/\\s/),\n BCor = readline().split(/\\s/);\n \n app.A = new Point(ACor[0], ACor[1]);\n app.B = new Point(BCor[0], BCor[1]);\n app.lineLength = parseInt(readline());\n },\n sovleResult : function() {\n for(var index = 0; index < app.lineLength; index++) {\n var line = new Line(readline().split(/\\s/)),\n liner = line.getLiner(),\n whenAxToY = line.getY(app.A.x),\n whenBxToY = line.getY(app.B.x);\n \n // console.log(app.A.y * line.b + ' ' + whenAxToY + ', ' + app.B.y * line.b + ' ' + whenBxToY);\n if(app.A.y * line.b >= whenAxToY && app.B.y * line.b <= whenBxToY) app.result++;\n else if(app.A.y * line.b <= whenAxToY && app.B.y * line.b >= whenBxToY) app.result++;\n }\n },\n printResult : function() {\n print(this.result);\n }\n};\n\napp.main();"}], "negative_code": [{"source_code": "var Point = function(x, y) { this.x = parseInt(x) / 1e6; this.y = parseInt(y) / 1e6; };\nvar Line = function(p) {\n this.a = parseInt(p[0]) / 1e6;\n this.b = parseInt(p[1]) / 1e6;\n this.c = parseInt(p[2]) / 1e6;\n this.getY = function(x) { return (this.a * -x + this.c) / this.b; };\n};\nvar app = {\n lineLength : 0,\n home : {}, universe : {},\n lineEqMap : [],\n result : 0,\n main : function() {\n this.initialize();\n this.readValues();\n this.sovleResult();\n this.printResult();\n },\n initialize : function() {},\n readValues : function() {\n var homeCor = readline().split(/\\s/),\n uniCor = readline().split(/\\s/);\n \n app.home = new Point(homeCor[0], homeCor[1]);\n app.universe = new Point(uniCor[0], uniCor[1]);\n app.lineLength = parseInt(readline());\n },\n sovleResult : function() {\n var hToUG = (app.universe.y - app.home.y) / (app.universe.x - app.home.x) >=0 ? true : false;\n for(var index = 0; index < app.lineLength; index++) {\n var line = new Line(readline().split(/\\s/)),\n whenHomeXtoY = line.getY(app.home.x),\n whenUniXtoY = line.getY(app.universe.x);\n \n if(hToUG) {\n if(app.home.y >= whenHomeXtoY && app.universe.y <= whenUniXtoY) app.result++;\n } else {\n if(app.home.y <= whenHomeXtoY && app.universe.y >= whenUniXtoY) app.result++;\n }\n }\n },\n printResult : function() {\n print(this.result);\n }\n};\n\napp.main();\n"}, {"source_code": "var Point = function(x, y) { this.x = parseInt(x) / 1e4; this.y = parseInt(y) / 1e4; };\nvar Line = function(p) {\n this.a = parseInt(p[0]) / 1e4;\n this.b = parseInt(p[1]) / 1e4;\n this.c = parseInt(p[2]) / 1e4;\n this.getY = function(x) { return (this.a * -x + this.c) / this.b; };\n};\nvar app = {\n lineLength : 0,\n home : {}, universe : {},\n lineEqMap : [],\n result : 0,\n main : function() {\n this.initialize();\n this.readValues();\n this.sovleResult();\n this.printResult();\n },\n initialize : function() {},\n readValues : function() {\n var homeCor = readline().split(/\\s/),\n uniCor = readline().split(/\\s/);\n \n app.home = new Point(homeCor[0], homeCor[1]);\n app.universe = new Point(uniCor[0], uniCor[1]);\n app.lineLength = parseInt(readline());\n },\n sovleResult : function() {\n var hToUG = (app.universe.y - app.home.y) / (app.universe.x - app.home.x) >=0 ? true : false;\n for(var index = 0; index < app.lineLength; index++) {\n var line = new Line(readline().split(/\\s/)),\n whenHomeXtoY = line.getY(app.home.x),\n whenUniXtoY = line.getY(app.universe.x);\n \n if(hToUG) {\n if(app.home.y >= whenHomeXtoY && app.universe.y <= whenUniXtoY) app.result++;\n } else {\n if(app.home.y <= whenHomeXtoY && app.universe.y >= whenUniXtoY) app.result++;\n }\n }\n },\n printResult : function() {\n print(this.result);\n }\n};\n\napp.main();\n"}, {"source_code": "var Point = function(x, y) { this.x = parseInt(x); this.y = parseInt(y); };\nvar Line = function(p) { this.a = parseInt(p[0]); this.b = parseInt(p[1]); this.c = parseInt(p[2]); this.getY = function(x) { return (this.a * -x + this.c) / this.b; }; };\nvar app = {\n lineLength : 0,\n home : {}, universe : {},\n lineEqMap : [],\n result : 0,\n main : function() {\n this.initialize();\n this.readValues();\n this.sovleResult();\n this.printResult();\n },\n initialize : function() {},\n readValues : function() {\n var homeCor = readline().split(/\\s/),\n uniCor = readline().split(/\\s/);\n \n app.home = new Point(homeCor[0], homeCor[1]);\n app.universe = new Point(uniCor[0], uniCor[1]);\n app.lineLength = parseInt(readline());\n for(var index = 0; index < app.lineLength; index++) app.lineEqMap.push(new Line(readline().split(/\\s/)));\n },\n sovleResult : function() {\n var hToUG = (app.universe.y - app.home.y) / (app.universe.x - app.home.x) >=0 ? true : false;\n app.lineEqMap.forEach(function(line) {\n var whenHomeXtoY = line.getY(app.home.x),\n whenUniXtoY = line.getY(app.universe.x);\n \n if(hToUG) {\n if(app.home.y >= whenHomeXtoY && app.universe.y <= whenUniXtoY) app.result++;\n } else {\n if(app.home.y <= whenHomeXtoY && app.universe.y >= whenUniXtoY) app.result++;\n }\n });\n },\n printResult : function() {\n print(this.result);\n }\n};\n\napp.main();\n"}], "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$$$) — 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": "var bigInt = (function(undefined) {\n 'use strict';\n\n var BASE = 1e7,\n LOG_BASE = 7,\n MAX_INT = 9007199254740992,\n MAX_INT_ARR = smallToArray(MAX_INT),\n DEFAULT_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\n\n var supportsNativeBigInt = typeof BigInt === 'function';\n\n function Integer(v, radix, alphabet, caseSensitive) {\n if (typeof v === 'undefined') return Integer[0];\n if (typeof radix !== 'undefined')\n return +radix === 10 && !alphabet\n ? parseValue(v)\n : parseBase(v, radix, alphabet, caseSensitive);\n return parseValue(v);\n }\n\n function BigInteger(value, sign) {\n this.value = value;\n this.sign = sign;\n this.isSmall = false;\n }\n BigInteger.prototype = Object.create(Integer.prototype);\n\n function SmallInteger(value) {\n this.value = value;\n this.sign = value < 0;\n this.isSmall = true;\n }\n SmallInteger.prototype = Object.create(Integer.prototype);\n\n function NativeBigInt(value) {\n this.value = value;\n }\n NativeBigInt.prototype = Object.create(Integer.prototype);\n\n function isPrecise(n) {\n return -MAX_INT < n && n < MAX_INT;\n }\n\n function smallToArray(n) {\n // For performance reasons doesn't reference BASE, need to change this function if BASE changes\n if (n < 1e7) return [n];\n if (n < 1e14) return [n % 1e7, Math.floor(n / 1e7)];\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\n }\n\n function arrayToSmall(arr) {\n // If BASE changes this function may need to change\n trim(arr);\n var length = arr.length;\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\n switch (length) {\n case 0:\n return 0;\n case 1:\n return arr[0];\n case 2:\n return arr[0] + arr[1] * BASE;\n default:\n return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\n }\n }\n return arr;\n }\n\n function trim(v) {\n var i = v.length;\n while (v[--i] === 0);\n v.length = i + 1;\n }\n\n function createArray(length) {\n // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\n var x = new Array(length);\n var i = -1;\n while (++i < length) {\n x[i] = 0;\n }\n return x;\n }\n\n function truncate(n) {\n if (n > 0) return Math.floor(n);\n return Math.ceil(n);\n }\n\n function add(a, b) {\n // assumes a and b are arrays with a.length >= b.length\n var l_a = a.length,\n l_b = b.length,\n r = new Array(l_a),\n carry = 0,\n base = BASE,\n sum,\n i;\n for (i = 0; i < l_b; i++) {\n sum = a[i] + b[i] + carry;\n carry = sum >= base ? 1 : 0;\n r[i] = sum - carry * base;\n }\n while (i < l_a) {\n sum = a[i] + carry;\n carry = sum === base ? 1 : 0;\n r[i++] = sum - carry * base;\n }\n if (carry > 0) r.push(carry);\n return r;\n }\n\n function addAny(a, b) {\n if (a.length >= b.length) return add(a, b);\n return add(b, a);\n }\n\n function addSmall(a, carry) {\n // assumes a is array, carry is number with 0 <= carry < MAX_INT\n var l = a.length,\n r = new Array(l),\n base = BASE,\n sum,\n i;\n for (i = 0; i < l; i++) {\n sum = a[i] - base + carry;\n carry = Math.floor(sum / base);\n r[i] = sum - carry * base;\n carry += 1;\n }\n while (carry > 0) {\n r[i++] = carry % base;\n carry = Math.floor(carry / base);\n }\n return r;\n }\n\n BigInteger.prototype.add = function(v) {\n var n = parseValue(v);\n if (this.sign !== n.sign) {\n return this.subtract(n.negate());\n }\n var a = this.value,\n b = n.value;\n if (n.isSmall) {\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\n }\n return new BigInteger(addAny(a, b), this.sign);\n };\n BigInteger.prototype.plus = BigInteger.prototype.add;\n\n SmallInteger.prototype.add = function(v) {\n var n = parseValue(v);\n var a = this.value;\n if (a < 0 !== n.sign) {\n return this.subtract(n.negate());\n }\n var b = n.value;\n if (n.isSmall) {\n if (isPrecise(a + b)) return new SmallInteger(a + b);\n b = smallToArray(Math.abs(b));\n }\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\n };\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\n\n NativeBigInt.prototype.add = function(v) {\n return new NativeBigInt(this.value + parseValue(v).value);\n };\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\n\n function subtract(a, b) {\n // assumes a and b are arrays with a >= b\n var a_l = a.length,\n b_l = b.length,\n r = new Array(a_l),\n borrow = 0,\n base = BASE,\n i,\n difference;\n for (i = 0; i < b_l; i++) {\n difference = a[i] - borrow - b[i];\n if (difference < 0) {\n difference += base;\n borrow = 1;\n } else borrow = 0;\n r[i] = difference;\n }\n for (i = b_l; i < a_l; i++) {\n difference = a[i] - borrow;\n if (difference < 0) difference += base;\n else {\n r[i++] = difference;\n break;\n }\n r[i] = difference;\n }\n for (; i < a_l; i++) {\n r[i] = a[i];\n }\n trim(r);\n return r;\n }\n\n function subtractAny(a, b, sign) {\n var value;\n if (compareAbs(a, b) >= 0) {\n value = subtract(a, b);\n } else {\n value = subtract(b, a);\n sign = !sign;\n }\n value = arrayToSmall(value);\n if (typeof value === 'number') {\n if (sign) value = -value;\n return new SmallInteger(value);\n }\n return new BigInteger(value, sign);\n }\n\n function subtractSmall(a, b, sign) {\n // assumes a is array, b is number with 0 <= b < MAX_INT\n var l = a.length,\n r = new Array(l),\n carry = -b,\n base = BASE,\n i,\n difference;\n for (i = 0; i < l; i++) {\n difference = a[i] + carry;\n carry = Math.floor(difference / base);\n difference %= base;\n r[i] = difference < 0 ? difference + base : difference;\n }\n r = arrayToSmall(r);\n if (typeof r === 'number') {\n if (sign) r = -r;\n return new SmallInteger(r);\n }\n return new BigInteger(r, sign);\n }\n\n BigInteger.prototype.subtract = function(v) {\n var n = parseValue(v);\n if (this.sign !== n.sign) {\n return this.add(n.negate());\n }\n var a = this.value,\n b = n.value;\n if (n.isSmall) return subtractSmall(a, Math.abs(b), this.sign);\n return subtractAny(a, b, this.sign);\n };\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\n\n SmallInteger.prototype.subtract = function(v) {\n var n = parseValue(v);\n var a = this.value;\n if (a < 0 !== n.sign) {\n return this.add(n.negate());\n }\n var b = n.value;\n if (n.isSmall) {\n return new SmallInteger(a - b);\n }\n return subtractSmall(b, Math.abs(a), a >= 0);\n };\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\n\n NativeBigInt.prototype.subtract = function(v) {\n return new NativeBigInt(this.value - parseValue(v).value);\n };\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\n\n BigInteger.prototype.negate = function() {\n return new BigInteger(this.value, !this.sign);\n };\n SmallInteger.prototype.negate = function() {\n var sign = this.sign;\n var small = new SmallInteger(-this.value);\n small.sign = !sign;\n return small;\n };\n NativeBigInt.prototype.negate = function() {\n return new NativeBigInt(-this.value);\n };\n\n BigInteger.prototype.abs = function() {\n return new BigInteger(this.value, false);\n };\n SmallInteger.prototype.abs = function() {\n return new SmallInteger(Math.abs(this.value));\n };\n NativeBigInt.prototype.abs = function() {\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\n };\n\n function multiplyLong(a, b) {\n var a_l = a.length,\n b_l = b.length,\n l = a_l + b_l,\n r = createArray(l),\n base = BASE,\n product,\n carry,\n i,\n a_i,\n b_j;\n for (i = 0; i < a_l; ++i) {\n a_i = a[i];\n for (var j = 0; j < b_l; ++j) {\n b_j = b[j];\n product = a_i * b_j + r[i + j];\n carry = Math.floor(product / base);\n r[i + j] = product - carry * base;\n r[i + j + 1] += carry;\n }\n }\n trim(r);\n return r;\n }\n\n function multiplySmall(a, b) {\n // assumes a is array, b is number with |b| < BASE\n var l = a.length,\n r = new Array(l),\n base = BASE,\n carry = 0,\n product,\n i;\n for (i = 0; i < l; i++) {\n product = a[i] * b + carry;\n carry = Math.floor(product / base);\n r[i] = product - carry * base;\n }\n while (carry > 0) {\n r[i++] = carry % base;\n carry = Math.floor(carry / base);\n }\n return r;\n }\n\n function shiftLeft(x, n) {\n var r = [];\n while (n-- > 0) r.push(0);\n return r.concat(x);\n }\n\n function multiplyKaratsuba(x, y) {\n var n = Math.max(x.length, y.length);\n\n if (n <= 30) return multiplyLong(x, y);\n n = Math.ceil(n / 2);\n\n var b = x.slice(n),\n a = x.slice(0, n),\n d = y.slice(n),\n c = y.slice(0, n);\n\n var ac = multiplyKaratsuba(a, c),\n bd = multiplyKaratsuba(b, d),\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\n\n var product = addAny(\n addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)),\n shiftLeft(bd, 2 * n)\n );\n trim(product);\n return product;\n }\n\n // The following function is derived from a surface fit of a graph plotting the performance difference\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\n function useKaratsuba(l1, l2) {\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\n }\n\n BigInteger.prototype.multiply = function(v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value,\n sign = this.sign !== n.sign,\n abs;\n if (n.isSmall) {\n if (b === 0) return Integer[0];\n if (b === 1) return this;\n if (b === -1) return this.negate();\n abs = Math.abs(b);\n if (abs < BASE) {\n return new BigInteger(multiplySmall(a, abs), sign);\n }\n b = smallToArray(abs);\n }\n if (useKaratsuba(a.length, b.length))\n // Karatsuba is only faster for certain array sizes\n return new BigInteger(multiplyKaratsuba(a, b), sign);\n return new BigInteger(multiplyLong(a, b), sign);\n };\n\n BigInteger.prototype.times = BigInteger.prototype.multiply;\n\n function multiplySmallAndArray(a, b, sign) {\n // a >= 0\n if (a < BASE) {\n return new BigInteger(multiplySmall(b, a), sign);\n }\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\n }\n SmallInteger.prototype._multiplyBySmall = function(a) {\n if (isPrecise(a.value * this.value)) {\n return new SmallInteger(a.value * this.value);\n }\n return multiplySmallAndArray(\n Math.abs(a.value),\n smallToArray(Math.abs(this.value)),\n this.sign !== a.sign\n );\n };\n BigInteger.prototype._multiplyBySmall = function(a) {\n if (a.value === 0) return Integer[0];\n if (a.value === 1) return this;\n if (a.value === -1) return this.negate();\n return multiplySmallAndArray(\n Math.abs(a.value),\n this.value,\n this.sign !== a.sign\n );\n };\n SmallInteger.prototype.multiply = function(v) {\n return parseValue(v)._multiplyBySmall(this);\n };\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\n\n NativeBigInt.prototype.multiply = function(v) {\n return new NativeBigInt(this.value * parseValue(v).value);\n };\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\n\n function square(a) {\n //console.assert(2 * BASE * BASE < MAX_INT);\n var l = a.length,\n r = createArray(l + l),\n base = BASE,\n product,\n carry,\n i,\n a_i,\n a_j;\n for (i = 0; i < l; i++) {\n a_i = a[i];\n carry = 0 - a_i * a_i;\n for (var j = i; j < l; j++) {\n a_j = a[j];\n product = 2 * (a_i * a_j) + r[i + j] + carry;\n carry = Math.floor(product / base);\n r[i + j] = product - carry * base;\n }\n r[i + l] = carry;\n }\n trim(r);\n return r;\n }\n\n BigInteger.prototype.square = function() {\n return new BigInteger(square(this.value), false);\n };\n\n SmallInteger.prototype.square = function() {\n var value = this.value * this.value;\n if (isPrecise(value)) return new SmallInteger(value);\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\n };\n\n NativeBigInt.prototype.square = function(v) {\n return new NativeBigInt(this.value * this.value);\n };\n\n function divMod1(a, b) {\n // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\n var a_l = a.length,\n b_l = b.length,\n base = BASE,\n result = createArray(b.length),\n divisorMostSignificantDigit = b[b_l - 1],\n // normalization\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\n remainder = multiplySmall(a, lambda),\n divisor = multiplySmall(b, lambda),\n quotientDigit,\n shift,\n carry,\n borrow,\n i,\n l,\n q;\n if (remainder.length <= a_l) remainder.push(0);\n divisor.push(0);\n divisorMostSignificantDigit = divisor[b_l - 1];\n for (shift = a_l - b_l; shift >= 0; shift--) {\n quotientDigit = base - 1;\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\n quotientDigit = Math.floor(\n (remainder[shift + b_l] * base + remainder[shift + b_l - 1]) /\n divisorMostSignificantDigit\n );\n }\n // quotientDigit <= base - 1\n carry = 0;\n borrow = 0;\n l = divisor.length;\n for (i = 0; i < l; i++) {\n carry += quotientDigit * divisor[i];\n q = Math.floor(carry / base);\n borrow += remainder[shift + i] - (carry - q * base);\n carry = q;\n if (borrow < 0) {\n remainder[shift + i] = borrow + base;\n borrow = -1;\n } else {\n remainder[shift + i] = borrow;\n borrow = 0;\n }\n }\n while (borrow !== 0) {\n quotientDigit -= 1;\n carry = 0;\n for (i = 0; i < l; i++) {\n carry += remainder[shift + i] - base + divisor[i];\n if (carry < 0) {\n remainder[shift + i] = carry + base;\n carry = 0;\n } else {\n remainder[shift + i] = carry;\n carry = 1;\n }\n }\n borrow += carry;\n }\n result[shift] = quotientDigit;\n }\n // denormalization\n remainder = divModSmall(remainder, lambda)[0];\n return [arrayToSmall(result), arrayToSmall(remainder)];\n }\n\n function divMod2(a, b) {\n // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\n // Performs faster than divMod1 on larger input sizes.\n var a_l = a.length,\n b_l = b.length,\n result = [],\n part = [],\n base = BASE,\n guess,\n xlen,\n highx,\n highy,\n check;\n while (a_l) {\n part.unshift(a[--a_l]);\n trim(part);\n if (compareAbs(part, b) < 0) {\n result.push(0);\n continue;\n }\n xlen = part.length;\n highx = part[xlen - 1] * base + part[xlen - 2];\n highy = b[b_l - 1] * base + b[b_l - 2];\n if (xlen > b_l) {\n highx = (highx + 1) * base;\n }\n guess = Math.ceil(highx / highy);\n do {\n check = multiplySmall(b, guess);\n if (compareAbs(check, part) <= 0) break;\n guess--;\n } while (guess);\n result.push(guess);\n part = subtract(part, check);\n }\n result.reverse();\n return [arrayToSmall(result), arrayToSmall(part)];\n }\n\n function divModSmall(value, lambda) {\n var length = value.length,\n quotient = createArray(length),\n base = BASE,\n i,\n q,\n remainder,\n divisor;\n remainder = 0;\n for (i = length - 1; i >= 0; --i) {\n divisor = remainder * base + value[i];\n q = truncate(divisor / lambda);\n remainder = divisor - q * lambda;\n quotient[i] = q | 0;\n }\n return [quotient, remainder | 0];\n }\n\n function divModAny(self, v) {\n var value,\n n = parseValue(v);\n if (supportsNativeBigInt) {\n return [\n new NativeBigInt(self.value / n.value),\n new NativeBigInt(self.value % n.value),\n ];\n }\n var a = self.value,\n b = n.value;\n var quotient;\n if (b === 0) throw new Error('Cannot divide by zero');\n if (self.isSmall) {\n if (n.isSmall) {\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\n }\n return [Integer[0], self];\n }\n if (n.isSmall) {\n if (b === 1) return [self, Integer[0]];\n if (b == -1) return [self.negate(), Integer[0]];\n var abs = Math.abs(b);\n if (abs < BASE) {\n value = divModSmall(a, abs);\n quotient = arrayToSmall(value[0]);\n var remainder = value[1];\n if (self.sign) remainder = -remainder;\n if (typeof quotient === 'number') {\n if (self.sign !== n.sign) quotient = -quotient;\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\n }\n return [\n new BigInteger(quotient, self.sign !== n.sign),\n new SmallInteger(remainder),\n ];\n }\n b = smallToArray(abs);\n }\n var comparison = compareAbs(a, b);\n if (comparison === -1) return [Integer[0], self];\n if (comparison === 0)\n return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\n\n // divMod1 is faster on smaller input sizes\n if (a.length + b.length <= 200) value = divMod1(a, b);\n else value = divMod2(a, b);\n\n quotient = value[0];\n var qSign = self.sign !== n.sign,\n mod = value[1],\n mSign = self.sign;\n if (typeof quotient === 'number') {\n if (qSign) quotient = -quotient;\n quotient = new SmallInteger(quotient);\n } else quotient = new BigInteger(quotient, qSign);\n if (typeof mod === 'number') {\n if (mSign) mod = -mod;\n mod = new SmallInteger(mod);\n } else mod = new BigInteger(mod, mSign);\n return [quotient, mod];\n }\n\n BigInteger.prototype.divmod = function(v) {\n var result = divModAny(this, v);\n return {\n quotient: result[0],\n remainder: result[1],\n };\n };\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod =\n BigInteger.prototype.divmod;\n\n BigInteger.prototype.divide = function(v) {\n return divModAny(this, v)[0];\n };\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function(v) {\n return new NativeBigInt(this.value / parseValue(v).value);\n };\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over =\n BigInteger.prototype.divide;\n\n BigInteger.prototype.mod = function(v) {\n return divModAny(this, v)[1];\n };\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function(v) {\n return new NativeBigInt(this.value % parseValue(v).value);\n };\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder =\n BigInteger.prototype.mod;\n\n BigInteger.prototype.pow = function(v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value,\n value,\n x,\n y;\n if (b === 0) return Integer[1];\n if (a === 0) return Integer[0];\n if (a === 1) return Integer[1];\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\n if (n.sign) {\n return Integer[0];\n }\n if (!n.isSmall)\n throw new Error('The exponent ' + n.toString() + ' is too large.');\n if (this.isSmall) {\n if (isPrecise((value = Math.pow(a, b))))\n return new SmallInteger(truncate(value));\n }\n x = this;\n y = Integer[1];\n while (true) {\n if (b & (1 === 1)) {\n y = y.times(x);\n --b;\n }\n if (b === 0) break;\n b /= 2;\n x = x.square();\n }\n return y;\n };\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\n\n NativeBigInt.prototype.pow = function(v) {\n var n = parseValue(v);\n var a = this.value,\n b = n.value;\n var _0 = BigInt(0),\n _1 = BigInt(1),\n _2 = BigInt(2);\n if (b === _0) return Integer[1];\n if (a === _0) return Integer[0];\n if (a === _1) return Integer[1];\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\n if (n.isNegative()) return new NativeBigInt(_0);\n var x = this;\n var y = Integer[1];\n while (true) {\n if ((b & _1) === _1) {\n y = y.times(x);\n --b;\n }\n if (b === _0) break;\n b /= _2;\n x = x.square();\n }\n return y;\n };\n\n BigInteger.prototype.modPow = function(exp, mod) {\n exp = parseValue(exp);\n mod = parseValue(mod);\n if (mod.isZero()) throw new Error('Cannot take modPow with modulus 0');\n var r = Integer[1],\n base = this.mod(mod);\n while (exp.isPositive()) {\n if (base.isZero()) return Integer[0];\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\n exp = exp.divide(2);\n base = base.square().mod(mod);\n }\n return r;\n };\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow =\n BigInteger.prototype.modPow;\n\n function compareAbs(a, b) {\n if (a.length !== b.length) {\n return a.length > b.length ? 1 : -1;\n }\n for (var i = a.length - 1; i >= 0; i--) {\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\n }\n return 0;\n }\n\n BigInteger.prototype.compareAbs = function(v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (n.isSmall) return 1;\n return compareAbs(a, b);\n };\n SmallInteger.prototype.compareAbs = function(v) {\n var n = parseValue(v),\n a = Math.abs(this.value),\n b = n.value;\n if (n.isSmall) {\n b = Math.abs(b);\n return a === b ? 0 : a > b ? 1 : -1;\n }\n return -1;\n };\n NativeBigInt.prototype.compareAbs = function(v) {\n var a = this.value;\n var b = parseValue(v).value;\n a = a >= 0 ? a : -a;\n b = b >= 0 ? b : -b;\n return a === b ? 0 : a > b ? 1 : -1;\n };\n\n BigInteger.prototype.compare = function(v) {\n // See discussion about comparison with Infinity:\n // https://github.com/peterolson/BigInteger.js/issues/61\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (this.sign !== n.sign) {\n return n.sign ? 1 : -1;\n }\n if (n.isSmall) {\n return this.sign ? -1 : 1;\n }\n return compareAbs(a, b) * (this.sign ? -1 : 1);\n };\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\n\n SmallInteger.prototype.compare = function(v) {\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (n.isSmall) {\n return a == b ? 0 : a > b ? 1 : -1;\n }\n if (a < 0 !== n.sign) {\n return a < 0 ? -1 : 1;\n }\n return a < 0 ? 1 : -1;\n };\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\n\n NativeBigInt.prototype.compare = function(v) {\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n var a = this.value;\n var b = parseValue(v).value;\n return a === b ? 0 : a > b ? 1 : -1;\n };\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\n\n BigInteger.prototype.equals = function(v) {\n return this.compare(v) === 0;\n };\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq =\n BigInteger.prototype.equals;\n\n BigInteger.prototype.notEquals = function(v) {\n return this.compare(v) !== 0;\n };\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq =\n BigInteger.prototype.notEquals;\n\n BigInteger.prototype.greater = function(v) {\n return this.compare(v) > 0;\n };\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt =\n BigInteger.prototype.greater;\n\n BigInteger.prototype.lesser = function(v) {\n return this.compare(v) < 0;\n };\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt =\n BigInteger.prototype.lesser;\n\n BigInteger.prototype.greaterOrEquals = function(v) {\n return this.compare(v) >= 0;\n };\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq =\n BigInteger.prototype.greaterOrEquals;\n\n BigInteger.prototype.lesserOrEquals = function(v) {\n return this.compare(v) <= 0;\n };\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq =\n BigInteger.prototype.lesserOrEquals;\n\n BigInteger.prototype.isEven = function() {\n return (this.value[0] & 1) === 0;\n };\n SmallInteger.prototype.isEven = function() {\n return (this.value & 1) === 0;\n };\n NativeBigInt.prototype.isEven = function() {\n return (this.value & BigInt(1)) === BigInt(0);\n };\n\n BigInteger.prototype.isOdd = function() {\n return (this.value[0] & 1) === 1;\n };\n SmallInteger.prototype.isOdd = function() {\n return (this.value & 1) === 1;\n };\n NativeBigInt.prototype.isOdd = function() {\n return (this.value & BigInt(1)) === BigInt(1);\n };\n\n BigInteger.prototype.isPositive = function() {\n return !this.sign;\n };\n SmallInteger.prototype.isPositive = function() {\n return this.value > 0;\n };\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\n\n BigInteger.prototype.isNegative = function() {\n return this.sign;\n };\n SmallInteger.prototype.isNegative = function() {\n return this.value < 0;\n };\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\n\n BigInteger.prototype.isUnit = function() {\n return false;\n };\n SmallInteger.prototype.isUnit = function() {\n return Math.abs(this.value) === 1;\n };\n NativeBigInt.prototype.isUnit = function() {\n return this.abs().value === BigInt(1);\n };\n\n BigInteger.prototype.isZero = function() {\n return false;\n };\n SmallInteger.prototype.isZero = function() {\n return this.value === 0;\n };\n NativeBigInt.prototype.isZero = function() {\n return this.value === BigInt(0);\n };\n\n BigInteger.prototype.isDivisibleBy = function(v) {\n var n = parseValue(v);\n if (n.isZero()) return false;\n if (n.isUnit()) return true;\n if (n.compareAbs(2) === 0) return this.isEven();\n return this.mod(n).isZero();\n };\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy =\n BigInteger.prototype.isDivisibleBy;\n\n function isBasicPrime(v) {\n var n = v.abs();\n if (n.isUnit()) return false;\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\n if (n.lesser(49)) return true;\n // we don't know if it's prime: let the other functions figure it out\n }\n\n function millerRabinTest(n, a) {\n var nPrev = n.prev(),\n b = nPrev,\n r = 0,\n d,\n t,\n i,\n x;\n while (b.isEven()) (b = b.divide(2)), r++;\n next: for (i = 0; i < a.length; i++) {\n if (n.lesser(a[i])) continue;\n x = bigInt(a[i]).modPow(b, n);\n if (x.isUnit() || x.equals(nPrev)) continue;\n for (d = r - 1; d != 0; d--) {\n x = x.square().mod(n);\n if (x.isUnit()) return false;\n if (x.equals(nPrev)) continue next;\n }\n return false;\n }\n return true;\n }\n\n // Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\n BigInteger.prototype.isPrime = function(strict) {\n var isPrime = isBasicPrime(this);\n if (isPrime !== undefined) return isPrime;\n var n = this.abs();\n var bits = n.bitLength();\n if (bits <= 64)\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\n var logN = Math.log(2) * bits.toJSNumber();\n var t = Math.ceil(strict === true ? 2 * Math.pow(logN, 2) : logN);\n for (var a = [], i = 0; i < t; i++) {\n a.push(bigInt(i + 2));\n }\n return millerRabinTest(n, a);\n };\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime =\n BigInteger.prototype.isPrime;\n\n BigInteger.prototype.isProbablePrime = function(iterations) {\n var isPrime = isBasicPrime(this);\n if (isPrime !== undefined) return isPrime;\n var n = this.abs();\n var t = iterations === undefined ? 5 : iterations;\n for (var a = [], i = 0; i < t; i++) {\n a.push(bigInt.randBetween(2, n.minus(2)));\n }\n return millerRabinTest(n, a);\n };\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime =\n BigInteger.prototype.isProbablePrime;\n\n BigInteger.prototype.modInv = function(n) {\n var t = bigInt.zero,\n newT = bigInt.one,\n r = parseValue(n),\n newR = this.abs(),\n q,\n lastT,\n lastR;\n while (!newR.isZero()) {\n q = r.divide(newR);\n lastT = t;\n lastR = r;\n t = newT;\n r = newR;\n newT = lastT.subtract(q.multiply(newT));\n newR = lastR.subtract(q.multiply(newR));\n }\n if (!r.isUnit())\n throw new Error(\n this.toString() + ' and ' + n.toString() + ' are not co-prime'\n );\n if (t.compare(0) === -1) {\n t = t.add(n);\n }\n if (this.isNegative()) {\n return t.negate();\n }\n return t;\n };\n\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv =\n BigInteger.prototype.modInv;\n\n BigInteger.prototype.next = function() {\n var value = this.value;\n if (this.sign) {\n return subtractSmall(value, 1, this.sign);\n }\n return new BigInteger(addSmall(value, 1), this.sign);\n };\n SmallInteger.prototype.next = function() {\n var value = this.value;\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\n return new BigInteger(MAX_INT_ARR, false);\n };\n NativeBigInt.prototype.next = function() {\n return new NativeBigInt(this.value + BigInt(1));\n };\n\n BigInteger.prototype.prev = function() {\n var value = this.value;\n if (this.sign) {\n return new BigInteger(addSmall(value, 1), true);\n }\n return subtractSmall(value, 1, this.sign);\n };\n SmallInteger.prototype.prev = function() {\n var value = this.value;\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\n return new BigInteger(MAX_INT_ARR, true);\n };\n NativeBigInt.prototype.prev = function() {\n return new NativeBigInt(this.value - BigInt(1));\n };\n\n var powersOfTwo = [1];\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE)\n powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\n var powers2Length = powersOfTwo.length,\n highestPower2 = powersOfTwo[powers2Length - 1];\n\n function shift_isSmall(n) {\n return Math.abs(n) <= BASE;\n }\n\n BigInteger.prototype.shiftLeft = function(v) {\n var n = parseValue(v).toJSNumber();\n if (!shift_isSmall(n)) {\n throw new Error(String(n) + ' is too large for shifting.');\n }\n if (n < 0) return this.shiftRight(-n);\n var result = this;\n if (result.isZero()) return result;\n while (n >= powers2Length) {\n result = result.multiply(highestPower2);\n n -= powers2Length - 1;\n }\n return result.multiply(powersOfTwo[n]);\n };\n NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft =\n BigInteger.prototype.shiftLeft;\n\n BigInteger.prototype.shiftRight = function(v) {\n var remQuo;\n var n = parseValue(v).toJSNumber();\n if (!shift_isSmall(n)) {\n throw new Error(String(n) + ' is too large for shifting.');\n }\n if (n < 0) return this.shiftLeft(-n);\n var result = this;\n while (n >= powers2Length) {\n if (result.isZero() || (result.isNegative() && result.isUnit()))\n return result;\n remQuo = divModAny(result, highestPower2);\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\n n -= powers2Length - 1;\n }\n remQuo = divModAny(result, powersOfTwo[n]);\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\n };\n NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight =\n BigInteger.prototype.shiftRight;\n\n function bitwise(x, y, fn) {\n y = parseValue(y);\n var xSign = x.isNegative(),\n ySign = y.isNegative();\n var xRem = xSign ? x.not() : x,\n yRem = ySign ? y.not() : y;\n var xDigit = 0,\n yDigit = 0;\n var xDivMod = null,\n yDivMod = null;\n var result = [];\n while (!xRem.isZero() || !yRem.isZero()) {\n xDivMod = divModAny(xRem, highestPower2);\n xDigit = xDivMod[1].toJSNumber();\n if (xSign) {\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\n }\n\n yDivMod = divModAny(yRem, highestPower2);\n yDigit = yDivMod[1].toJSNumber();\n if (ySign) {\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\n }\n\n xRem = xDivMod[0];\n yRem = yDivMod[0];\n result.push(fn(xDigit, yDigit));\n }\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\n for (var i = result.length - 1; i >= 0; i -= 1) {\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\n }\n return sum;\n }\n\n BigInteger.prototype.not = function() {\n return this.negate().prev();\n };\n NativeBigInt.prototype.not = SmallInteger.prototype.not =\n BigInteger.prototype.not;\n\n BigInteger.prototype.and = function(n) {\n return bitwise(this, n, function(a, b) {\n return a & b;\n });\n };\n NativeBigInt.prototype.and = SmallInteger.prototype.and =\n BigInteger.prototype.and;\n\n BigInteger.prototype.or = function(n) {\n return bitwise(this, n, function(a, b) {\n return a | b;\n });\n };\n NativeBigInt.prototype.or = SmallInteger.prototype.or =\n BigInteger.prototype.or;\n\n BigInteger.prototype.xor = function(n) {\n return bitwise(this, n, function(a, b) {\n return a ^ b;\n });\n };\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor =\n BigInteger.prototype.xor;\n\n var LOBMASK_I = 1 << 30,\n LOBMASK_BI = ((BASE & -BASE) * (BASE & -BASE)) | LOBMASK_I;\n function roughLOB(n) {\n // get lowestOneBit (rough)\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\n var v = n.value,\n x =\n typeof v === 'number'\n ? v | LOBMASK_I\n : typeof v === 'bigint'\n ? v | BigInt(LOBMASK_I)\n : (v[0] + v[1] * BASE) | LOBMASK_BI;\n return x & -x;\n }\n\n function integerLogarithm(value, base) {\n if (base.compareTo(value) <= 0) {\n var tmp = integerLogarithm(value, base.square(base));\n var p = tmp.p;\n var e = tmp.e;\n var t = p.multiply(base);\n return t.compareTo(value) <= 0\n ? { p: t, e: e * 2 + 1 }\n : { p: p, e: e * 2 };\n }\n return { p: bigInt(1), e: 0 };\n }\n\n BigInteger.prototype.bitLength = function() {\n var n = this;\n if (n.compareTo(bigInt(0)) < 0) {\n n = n.negate().subtract(bigInt(1));\n }\n if (n.compareTo(bigInt(0)) === 0) {\n return bigInt(0);\n }\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\n };\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength =\n BigInteger.prototype.bitLength;\n\n function max(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n return a.greater(b) ? a : b;\n }\n function min(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n return a.lesser(b) ? a : b;\n }\n function gcd(a, b) {\n a = parseValue(a).abs();\n b = parseValue(b).abs();\n if (a.equals(b)) return a;\n if (a.isZero()) return b;\n if (b.isZero()) return a;\n var c = Integer[1],\n d,\n t;\n while (a.isEven() && b.isEven()) {\n d = min(roughLOB(a), roughLOB(b));\n a = a.divide(d);\n b = b.divide(d);\n c = c.multiply(d);\n }\n while (a.isEven()) {\n a = a.divide(roughLOB(a));\n }\n do {\n while (b.isEven()) {\n b = b.divide(roughLOB(b));\n }\n if (a.greater(b)) {\n t = b;\n b = a;\n a = t;\n }\n b = b.subtract(a);\n } while (!b.isZero());\n return c.isUnit() ? a : a.multiply(c);\n }\n function lcm(a, b) {\n a = parseValue(a).abs();\n b = parseValue(b).abs();\n return a.divide(gcd(a, b)).multiply(b);\n }\n function randBetween(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n var low = min(a, b),\n high = max(a, b);\n var range = high.subtract(low).add(1);\n if (range.isSmall) return low.add(Math.floor(Math.random() * range));\n var digits = toBase(range, BASE).value;\n var result = [],\n restricted = true;\n for (var i = 0; i < digits.length; i++) {\n var top = restricted ? digits[i] : BASE;\n var digit = truncate(Math.random() * top);\n result.push(digit);\n if (digit < top) restricted = false;\n }\n return low.add(Integer.fromArray(result, BASE, false));\n }\n\n var parseBase = function(text, base, alphabet, caseSensitive) {\n alphabet = alphabet || DEFAULT_ALPHABET;\n text = String(text);\n if (!caseSensitive) {\n text = text.toLowerCase();\n alphabet = alphabet.toLowerCase();\n }\n var length = text.length;\n var i;\n var absBase = Math.abs(base);\n var alphabetValues = {};\n for (i = 0; i < alphabet.length; i++) {\n alphabetValues[alphabet[i]] = i;\n }\n for (i = 0; i < length; i++) {\n var c = text[i];\n if (c === '-') continue;\n if (c in alphabetValues) {\n if (alphabetValues[c] >= absBase) {\n if (c === '1' && absBase === 1) continue;\n throw new Error(c + ' is not a valid digit in base ' + base + '.');\n }\n }\n }\n base = parseValue(base);\n var digits = [];\n var isNegative = text[0] === '-';\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\n var c = text[i];\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\n else if (c === '<') {\n var start = i;\n do {\n i++;\n } while (text[i] !== '>' && i < text.length);\n digits.push(parseValue(text.slice(start + 1, i)));\n } else throw new Error(c + ' is not a valid character');\n }\n return parseBaseFromArray(digits, base, isNegative);\n };\n\n function parseBaseFromArray(digits, base, isNegative) {\n var val = Integer[0],\n pow = Integer[1],\n i;\n for (i = digits.length - 1; i >= 0; i--) {\n val = val.add(digits[i].times(pow));\n pow = pow.times(base);\n }\n return isNegative ? val.negate() : val;\n }\n\n function stringify(digit, alphabet) {\n alphabet = alphabet || DEFAULT_ALPHABET;\n if (digit < alphabet.length) {\n return alphabet[digit];\n }\n return '<' + digit + '>';\n }\n\n function toBase(n, base) {\n base = bigInt(base);\n if (base.isZero()) {\n if (n.isZero()) return { value: [0], isNegative: false };\n throw new Error('Cannot convert nonzero numbers to base 0.');\n }\n if (base.equals(-1)) {\n if (n.isZero()) return { value: [0], isNegative: false };\n if (n.isNegative())\n return {\n value: [].concat.apply(\n [],\n Array.apply(null, Array(-n.toJSNumber())).map(\n Array.prototype.valueOf,\n [1, 0]\n )\n ),\n isNegative: false,\n };\n\n var arr = Array.apply(null, Array(n.toJSNumber() - 1)).map(\n Array.prototype.valueOf,\n [0, 1]\n );\n arr.unshift([1]);\n return {\n value: [].concat.apply([], arr),\n isNegative: false,\n };\n }\n\n var neg = false;\n if (n.isNegative() && base.isPositive()) {\n neg = true;\n n = n.abs();\n }\n if (base.isUnit()) {\n if (n.isZero()) return { value: [0], isNegative: false };\n\n return {\n value: Array.apply(null, Array(n.toJSNumber())).map(\n Number.prototype.valueOf,\n 1\n ),\n isNegative: neg,\n };\n }\n var out = [];\n var left = n,\n divmod;\n while (left.isNegative() || left.compareAbs(base) >= 0) {\n divmod = left.divmod(base);\n left = divmod.quotient;\n var digit = divmod.remainder;\n if (digit.isNegative()) {\n digit = base.minus(digit).abs();\n left = left.next();\n }\n out.push(digit.toJSNumber());\n }\n out.push(left.toJSNumber());\n return { value: out.reverse(), isNegative: neg };\n }\n\n function toBaseString(n, base, alphabet) {\n var arr = toBase(n, base);\n return (\n (arr.isNegative ? '-' : '') +\n arr.value\n .map(function(x) {\n return stringify(x, alphabet);\n })\n .join('')\n );\n }\n\n BigInteger.prototype.toArray = function(radix) {\n return toBase(this, radix);\n };\n\n SmallInteger.prototype.toArray = function(radix) {\n return toBase(this, radix);\n };\n\n NativeBigInt.prototype.toArray = function(radix) {\n return toBase(this, radix);\n };\n\n BigInteger.prototype.toString = function(radix, alphabet) {\n if (radix === undefined) radix = 10;\n if (radix !== 10) return toBaseString(this, radix, alphabet);\n var v = this.value,\n l = v.length,\n str = String(v[--l]),\n zeros = '0000000',\n digit;\n while (--l >= 0) {\n digit = String(v[l]);\n str += zeros.slice(digit.length) + digit;\n }\n var sign = this.sign ? '-' : '';\n return sign + str;\n };\n\n SmallInteger.prototype.toString = function(radix, alphabet) {\n if (radix === undefined) radix = 10;\n if (radix != 10) return toBaseString(this, radix, alphabet);\n return String(this.value);\n };\n\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\n\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function() {\n return this.toString();\n };\n\n BigInteger.prototype.valueOf = function() {\n return parseInt(this.toString(), 10);\n };\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\n\n SmallInteger.prototype.valueOf = function() {\n return this.value;\n };\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function() {\n return parseInt(this.toString(), 10);\n };\n\n function parseStringValue(v) {\n if (isPrecise(+v)) {\n var x = +v;\n if (x === truncate(x))\n return supportsNativeBigInt\n ? new NativeBigInt(BigInt(x))\n : new SmallInteger(x);\n throw new Error('Invalid integer: ' + v);\n }\n var sign = v[0] === '-';\n if (sign) v = v.slice(1);\n var split = v.split(/e/i);\n if (split.length > 2)\n throw new Error('Invalid integer: ' + split.join('e'));\n if (split.length === 2) {\n var exp = split[1];\n if (exp[0] === '+') exp = exp.slice(1);\n exp = +exp;\n if (exp !== truncate(exp) || !isPrecise(exp))\n throw new Error(\n 'Invalid integer: ' + exp + ' is not a valid exponent.'\n );\n var text = split[0];\n var decimalPlace = text.indexOf('.');\n if (decimalPlace >= 0) {\n exp -= text.length - decimalPlace - 1;\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\n }\n if (exp < 0)\n throw new Error('Cannot include negative exponent part for integers');\n text += new Array(exp + 1).join('0');\n v = text;\n }\n var isValid = /^([0-9][0-9]*)$/.test(v);\n if (!isValid) throw new Error('Invalid integer: ' + v);\n if (supportsNativeBigInt) {\n return new NativeBigInt(BigInt(sign ? '-' + v : v));\n }\n var r = [],\n max = v.length,\n l = LOG_BASE,\n min = max - l;\n while (max > 0) {\n r.push(+v.slice(min, max));\n min -= l;\n if (min < 0) min = 0;\n max -= l;\n }\n trim(r);\n return new BigInteger(r, sign);\n }\n\n function parseNumberValue(v) {\n if (supportsNativeBigInt) {\n return new NativeBigInt(BigInt(v));\n }\n if (isPrecise(v)) {\n if (v !== truncate(v)) throw new Error(v + ' is not an integer.');\n return new SmallInteger(v);\n }\n return parseStringValue(v.toString());\n }\n\n function parseValue(v) {\n if (typeof v === 'number') {\n return parseNumberValue(v);\n }\n if (typeof v === 'string') {\n return parseStringValue(v);\n }\n if (typeof v === 'bigint') {\n return new NativeBigInt(v);\n }\n return v;\n }\n // Pre-define numbers in range [-999,999]\n for (var i = 0; i < 1000; i++) {\n Integer[i] = parseValue(i);\n if (i > 0) Integer[-i] = parseValue(-i);\n }\n // Backwards compatibility\n Integer.one = Integer[1];\n Integer.zero = Integer[0];\n Integer.minusOne = Integer[-1];\n Integer.max = max;\n Integer.min = min;\n Integer.gcd = gcd;\n Integer.lcm = lcm;\n Integer.isInstance = function(x) {\n return (\n x instanceof BigInteger ||\n x instanceof SmallInteger ||\n x instanceof NativeBigInt\n );\n };\n Integer.randBetween = randBetween;\n\n Integer.fromArray = function(digits, base, isNegative) {\n return parseBaseFromArray(\n digits.map(parseValue),\n parseValue(base || 10),\n isNegative\n );\n };\n\n return Integer;\n})();\n\n// Node.js check\nif (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {\n module.exports = bigInt;\n}\n\n//amd check\nif (typeof define === 'function' && define.amd) {\n define('big-integer', [], function() {\n return bigInt;\n });\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\n// your code goes here\n\nvar input = ``;\n\nfunction cacheInput(data) {\n input += data;\n}\n\nfunction main() {\n let lines = input.split('\\r\\n');\n let n = parseInt(lines[0]);\n for (var i = 1; i <= n; i++) {\n let steps = bigInt(0);\n let input = lines[i].split(' ');\n let n = bigInt(input[0]);\n let k = bigInt(input[1]);\n while (n.value) {\n let mod = bigInt(n).mod(bigInt(k));\n if (mod.value === 0) {\n n = bigInt(n).divide(bigInt(k));\n steps = bigInt(steps).add(1);\n } else {\n n = bigInt(n).minus(bigInt(mod));\n steps = bigInt(steps).add(bigInt(mod));\n }\n }\n console.log(steps.toString());\n }\n}\n\nprocess.stdin.on('data', cacheInput).on('end', main);"}, {"source_code": "var bigInt = (function(undefined) {\n 'use strict';\n\n var BASE = 1e7,\n LOG_BASE = 7,\n MAX_INT = 9007199254740992,\n MAX_INT_ARR = smallToArray(MAX_INT),\n DEFAULT_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\n\n var supportsNativeBigInt = typeof BigInt === 'function';\n\n function Integer(v, radix, alphabet, caseSensitive) {\n if (typeof v === 'undefined') return Integer[0];\n if (typeof radix !== 'undefined')\n return +radix === 10 && !alphabet\n ? parseValue(v)\n : parseBase(v, radix, alphabet, caseSensitive);\n return parseValue(v);\n }\n\n function BigInteger(value, sign) {\n this.value = value;\n this.sign = sign;\n this.isSmall = false;\n }\n BigInteger.prototype = Object.create(Integer.prototype);\n\n function SmallInteger(value) {\n this.value = value;\n this.sign = value < 0;\n this.isSmall = true;\n }\n SmallInteger.prototype = Object.create(Integer.prototype);\n\n function NativeBigInt(value) {\n this.value = value;\n }\n NativeBigInt.prototype = Object.create(Integer.prototype);\n\n function isPrecise(n) {\n return -MAX_INT < n && n < MAX_INT;\n }\n\n function smallToArray(n) {\n // For performance reasons doesn't reference BASE, need to change this function if BASE changes\n if (n < 1e7) return [n];\n if (n < 1e14) return [n % 1e7, Math.floor(n / 1e7)];\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\n }\n\n function arrayToSmall(arr) {\n // If BASE changes this function may need to change\n trim(arr);\n var length = arr.length;\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\n switch (length) {\n case 0:\n return 0;\n case 1:\n return arr[0];\n case 2:\n return arr[0] + arr[1] * BASE;\n default:\n return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\n }\n }\n return arr;\n }\n\n function trim(v) {\n var i = v.length;\n while (v[--i] === 0);\n v.length = i + 1;\n }\n\n function createArray(length) {\n // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\n var x = new Array(length);\n var i = -1;\n while (++i < length) {\n x[i] = 0;\n }\n return x;\n }\n\n function truncate(n) {\n if (n > 0) return Math.floor(n);\n return Math.ceil(n);\n }\n\n function add(a, b) {\n // assumes a and b are arrays with a.length >= b.length\n var l_a = a.length,\n l_b = b.length,\n r = new Array(l_a),\n carry = 0,\n base = BASE,\n sum,\n i;\n for (i = 0; i < l_b; i++) {\n sum = a[i] + b[i] + carry;\n carry = sum >= base ? 1 : 0;\n r[i] = sum - carry * base;\n }\n while (i < l_a) {\n sum = a[i] + carry;\n carry = sum === base ? 1 : 0;\n r[i++] = sum - carry * base;\n }\n if (carry > 0) r.push(carry);\n return r;\n }\n\n function addAny(a, b) {\n if (a.length >= b.length) return add(a, b);\n return add(b, a);\n }\n\n function addSmall(a, carry) {\n // assumes a is array, carry is number with 0 <= carry < MAX_INT\n var l = a.length,\n r = new Array(l),\n base = BASE,\n sum,\n i;\n for (i = 0; i < l; i++) {\n sum = a[i] - base + carry;\n carry = Math.floor(sum / base);\n r[i] = sum - carry * base;\n carry += 1;\n }\n while (carry > 0) {\n r[i++] = carry % base;\n carry = Math.floor(carry / base);\n }\n return r;\n }\n\n BigInteger.prototype.add = function(v) {\n var n = parseValue(v);\n if (this.sign !== n.sign) {\n return this.subtract(n.negate());\n }\n var a = this.value,\n b = n.value;\n if (n.isSmall) {\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\n }\n return new BigInteger(addAny(a, b), this.sign);\n };\n BigInteger.prototype.plus = BigInteger.prototype.add;\n\n SmallInteger.prototype.add = function(v) {\n var n = parseValue(v);\n var a = this.value;\n if (a < 0 !== n.sign) {\n return this.subtract(n.negate());\n }\n var b = n.value;\n if (n.isSmall) {\n if (isPrecise(a + b)) return new SmallInteger(a + b);\n b = smallToArray(Math.abs(b));\n }\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\n };\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\n\n NativeBigInt.prototype.add = function(v) {\n return new NativeBigInt(this.value + parseValue(v).value);\n };\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\n\n function subtract(a, b) {\n // assumes a and b are arrays with a >= b\n var a_l = a.length,\n b_l = b.length,\n r = new Array(a_l),\n borrow = 0,\n base = BASE,\n i,\n difference;\n for (i = 0; i < b_l; i++) {\n difference = a[i] - borrow - b[i];\n if (difference < 0) {\n difference += base;\n borrow = 1;\n } else borrow = 0;\n r[i] = difference;\n }\n for (i = b_l; i < a_l; i++) {\n difference = a[i] - borrow;\n if (difference < 0) difference += base;\n else {\n r[i++] = difference;\n break;\n }\n r[i] = difference;\n }\n for (; i < a_l; i++) {\n r[i] = a[i];\n }\n trim(r);\n return r;\n }\n\n function subtractAny(a, b, sign) {\n var value;\n if (compareAbs(a, b) >= 0) {\n value = subtract(a, b);\n } else {\n value = subtract(b, a);\n sign = !sign;\n }\n value = arrayToSmall(value);\n if (typeof value === 'number') {\n if (sign) value = -value;\n return new SmallInteger(value);\n }\n return new BigInteger(value, sign);\n }\n\n function subtractSmall(a, b, sign) {\n // assumes a is array, b is number with 0 <= b < MAX_INT\n var l = a.length,\n r = new Array(l),\n carry = -b,\n base = BASE,\n i,\n difference;\n for (i = 0; i < l; i++) {\n difference = a[i] + carry;\n carry = Math.floor(difference / base);\n difference %= base;\n r[i] = difference < 0 ? difference + base : difference;\n }\n r = arrayToSmall(r);\n if (typeof r === 'number') {\n if (sign) r = -r;\n return new SmallInteger(r);\n }\n return new BigInteger(r, sign);\n }\n\n BigInteger.prototype.subtract = function(v) {\n var n = parseValue(v);\n if (this.sign !== n.sign) {\n return this.add(n.negate());\n }\n var a = this.value,\n b = n.value;\n if (n.isSmall) return subtractSmall(a, Math.abs(b), this.sign);\n return subtractAny(a, b, this.sign);\n };\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\n\n SmallInteger.prototype.subtract = function(v) {\n var n = parseValue(v);\n var a = this.value;\n if (a < 0 !== n.sign) {\n return this.add(n.negate());\n }\n var b = n.value;\n if (n.isSmall) {\n return new SmallInteger(a - b);\n }\n return subtractSmall(b, Math.abs(a), a >= 0);\n };\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\n\n NativeBigInt.prototype.subtract = function(v) {\n return new NativeBigInt(this.value - parseValue(v).value);\n };\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\n\n BigInteger.prototype.negate = function() {\n return new BigInteger(this.value, !this.sign);\n };\n SmallInteger.prototype.negate = function() {\n var sign = this.sign;\n var small = new SmallInteger(-this.value);\n small.sign = !sign;\n return small;\n };\n NativeBigInt.prototype.negate = function() {\n return new NativeBigInt(-this.value);\n };\n\n BigInteger.prototype.abs = function() {\n return new BigInteger(this.value, false);\n };\n SmallInteger.prototype.abs = function() {\n return new SmallInteger(Math.abs(this.value));\n };\n NativeBigInt.prototype.abs = function() {\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\n };\n\n function multiplyLong(a, b) {\n var a_l = a.length,\n b_l = b.length,\n l = a_l + b_l,\n r = createArray(l),\n base = BASE,\n product,\n carry,\n i,\n a_i,\n b_j;\n for (i = 0; i < a_l; ++i) {\n a_i = a[i];\n for (var j = 0; j < b_l; ++j) {\n b_j = b[j];\n product = a_i * b_j + r[i + j];\n carry = Math.floor(product / base);\n r[i + j] = product - carry * base;\n r[i + j + 1] += carry;\n }\n }\n trim(r);\n return r;\n }\n\n function multiplySmall(a, b) {\n // assumes a is array, b is number with |b| < BASE\n var l = a.length,\n r = new Array(l),\n base = BASE,\n carry = 0,\n product,\n i;\n for (i = 0; i < l; i++) {\n product = a[i] * b + carry;\n carry = Math.floor(product / base);\n r[i] = product - carry * base;\n }\n while (carry > 0) {\n r[i++] = carry % base;\n carry = Math.floor(carry / base);\n }\n return r;\n }\n\n function shiftLeft(x, n) {\n var r = [];\n while (n-- > 0) r.push(0);\n return r.concat(x);\n }\n\n function multiplyKaratsuba(x, y) {\n var n = Math.max(x.length, y.length);\n\n if (n <= 30) return multiplyLong(x, y);\n n = Math.ceil(n / 2);\n\n var b = x.slice(n),\n a = x.slice(0, n),\n d = y.slice(n),\n c = y.slice(0, n);\n\n var ac = multiplyKaratsuba(a, c),\n bd = multiplyKaratsuba(b, d),\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\n\n var product = addAny(\n addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)),\n shiftLeft(bd, 2 * n)\n );\n trim(product);\n return product;\n }\n\n // The following function is derived from a surface fit of a graph plotting the performance difference\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\n function useKaratsuba(l1, l2) {\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\n }\n\n BigInteger.prototype.multiply = function(v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value,\n sign = this.sign !== n.sign,\n abs;\n if (n.isSmall) {\n if (b === 0) return Integer[0];\n if (b === 1) return this;\n if (b === -1) return this.negate();\n abs = Math.abs(b);\n if (abs < BASE) {\n return new BigInteger(multiplySmall(a, abs), sign);\n }\n b = smallToArray(abs);\n }\n if (useKaratsuba(a.length, b.length))\n // Karatsuba is only faster for certain array sizes\n return new BigInteger(multiplyKaratsuba(a, b), sign);\n return new BigInteger(multiplyLong(a, b), sign);\n };\n\n BigInteger.prototype.times = BigInteger.prototype.multiply;\n\n function multiplySmallAndArray(a, b, sign) {\n // a >= 0\n if (a < BASE) {\n return new BigInteger(multiplySmall(b, a), sign);\n }\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\n }\n SmallInteger.prototype._multiplyBySmall = function(a) {\n if (isPrecise(a.value * this.value)) {\n return new SmallInteger(a.value * this.value);\n }\n return multiplySmallAndArray(\n Math.abs(a.value),\n smallToArray(Math.abs(this.value)),\n this.sign !== a.sign\n );\n };\n BigInteger.prototype._multiplyBySmall = function(a) {\n if (a.value === 0) return Integer[0];\n if (a.value === 1) return this;\n if (a.value === -1) return this.negate();\n return multiplySmallAndArray(\n Math.abs(a.value),\n this.value,\n this.sign !== a.sign\n );\n };\n SmallInteger.prototype.multiply = function(v) {\n return parseValue(v)._multiplyBySmall(this);\n };\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\n\n NativeBigInt.prototype.multiply = function(v) {\n return new NativeBigInt(this.value * parseValue(v).value);\n };\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\n\n function square(a) {\n //console.assert(2 * BASE * BASE < MAX_INT);\n var l = a.length,\n r = createArray(l + l),\n base = BASE,\n product,\n carry,\n i,\n a_i,\n a_j;\n for (i = 0; i < l; i++) {\n a_i = a[i];\n carry = 0 - a_i * a_i;\n for (var j = i; j < l; j++) {\n a_j = a[j];\n product = 2 * (a_i * a_j) + r[i + j] + carry;\n carry = Math.floor(product / base);\n r[i + j] = product - carry * base;\n }\n r[i + l] = carry;\n }\n trim(r);\n return r;\n }\n\n BigInteger.prototype.square = function() {\n return new BigInteger(square(this.value), false);\n };\n\n SmallInteger.prototype.square = function() {\n var value = this.value * this.value;\n if (isPrecise(value)) return new SmallInteger(value);\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\n };\n\n NativeBigInt.prototype.square = function(v) {\n return new NativeBigInt(this.value * this.value);\n };\n\n function divMod1(a, b) {\n // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\n var a_l = a.length,\n b_l = b.length,\n base = BASE,\n result = createArray(b.length),\n divisorMostSignificantDigit = b[b_l - 1],\n // normalization\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\n remainder = multiplySmall(a, lambda),\n divisor = multiplySmall(b, lambda),\n quotientDigit,\n shift,\n carry,\n borrow,\n i,\n l,\n q;\n if (remainder.length <= a_l) remainder.push(0);\n divisor.push(0);\n divisorMostSignificantDigit = divisor[b_l - 1];\n for (shift = a_l - b_l; shift >= 0; shift--) {\n quotientDigit = base - 1;\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\n quotientDigit = Math.floor(\n (remainder[shift + b_l] * base + remainder[shift + b_l - 1]) /\n divisorMostSignificantDigit\n );\n }\n // quotientDigit <= base - 1\n carry = 0;\n borrow = 0;\n l = divisor.length;\n for (i = 0; i < l; i++) {\n carry += quotientDigit * divisor[i];\n q = Math.floor(carry / base);\n borrow += remainder[shift + i] - (carry - q * base);\n carry = q;\n if (borrow < 0) {\n remainder[shift + i] = borrow + base;\n borrow = -1;\n } else {\n remainder[shift + i] = borrow;\n borrow = 0;\n }\n }\n while (borrow !== 0) {\n quotientDigit -= 1;\n carry = 0;\n for (i = 0; i < l; i++) {\n carry += remainder[shift + i] - base + divisor[i];\n if (carry < 0) {\n remainder[shift + i] = carry + base;\n carry = 0;\n } else {\n remainder[shift + i] = carry;\n carry = 1;\n }\n }\n borrow += carry;\n }\n result[shift] = quotientDigit;\n }\n // denormalization\n remainder = divModSmall(remainder, lambda)[0];\n return [arrayToSmall(result), arrayToSmall(remainder)];\n }\n\n function divMod2(a, b) {\n // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\n // Performs faster than divMod1 on larger input sizes.\n var a_l = a.length,\n b_l = b.length,\n result = [],\n part = [],\n base = BASE,\n guess,\n xlen,\n highx,\n highy,\n check;\n while (a_l) {\n part.unshift(a[--a_l]);\n trim(part);\n if (compareAbs(part, b) < 0) {\n result.push(0);\n continue;\n }\n xlen = part.length;\n highx = part[xlen - 1] * base + part[xlen - 2];\n highy = b[b_l - 1] * base + b[b_l - 2];\n if (xlen > b_l) {\n highx = (highx + 1) * base;\n }\n guess = Math.ceil(highx / highy);\n do {\n check = multiplySmall(b, guess);\n if (compareAbs(check, part) <= 0) break;\n guess--;\n } while (guess);\n result.push(guess);\n part = subtract(part, check);\n }\n result.reverse();\n return [arrayToSmall(result), arrayToSmall(part)];\n }\n\n function divModSmall(value, lambda) {\n var length = value.length,\n quotient = createArray(length),\n base = BASE,\n i,\n q,\n remainder,\n divisor;\n remainder = 0;\n for (i = length - 1; i >= 0; --i) {\n divisor = remainder * base + value[i];\n q = truncate(divisor / lambda);\n remainder = divisor - q * lambda;\n quotient[i] = q | 0;\n }\n return [quotient, remainder | 0];\n }\n\n function divModAny(self, v) {\n var value,\n n = parseValue(v);\n if (supportsNativeBigInt) {\n return [\n new NativeBigInt(self.value / n.value),\n new NativeBigInt(self.value % n.value),\n ];\n }\n var a = self.value,\n b = n.value;\n var quotient;\n if (b === 0) throw new Error('Cannot divide by zero');\n if (self.isSmall) {\n if (n.isSmall) {\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\n }\n return [Integer[0], self];\n }\n if (n.isSmall) {\n if (b === 1) return [self, Integer[0]];\n if (b == -1) return [self.negate(), Integer[0]];\n var abs = Math.abs(b);\n if (abs < BASE) {\n value = divModSmall(a, abs);\n quotient = arrayToSmall(value[0]);\n var remainder = value[1];\n if (self.sign) remainder = -remainder;\n if (typeof quotient === 'number') {\n if (self.sign !== n.sign) quotient = -quotient;\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\n }\n return [\n new BigInteger(quotient, self.sign !== n.sign),\n new SmallInteger(remainder),\n ];\n }\n b = smallToArray(abs);\n }\n var comparison = compareAbs(a, b);\n if (comparison === -1) return [Integer[0], self];\n if (comparison === 0)\n return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\n\n // divMod1 is faster on smaller input sizes\n if (a.length + b.length <= 200) value = divMod1(a, b);\n else value = divMod2(a, b);\n\n quotient = value[0];\n var qSign = self.sign !== n.sign,\n mod = value[1],\n mSign = self.sign;\n if (typeof quotient === 'number') {\n if (qSign) quotient = -quotient;\n quotient = new SmallInteger(quotient);\n } else quotient = new BigInteger(quotient, qSign);\n if (typeof mod === 'number') {\n if (mSign) mod = -mod;\n mod = new SmallInteger(mod);\n } else mod = new BigInteger(mod, mSign);\n return [quotient, mod];\n }\n\n BigInteger.prototype.divmod = function(v) {\n var result = divModAny(this, v);\n return {\n quotient: result[0],\n remainder: result[1],\n };\n };\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod =\n BigInteger.prototype.divmod;\n\n BigInteger.prototype.divide = function(v) {\n return divModAny(this, v)[0];\n };\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function(v) {\n return new NativeBigInt(this.value / parseValue(v).value);\n };\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over =\n BigInteger.prototype.divide;\n\n BigInteger.prototype.mod = function(v) {\n return divModAny(this, v)[1];\n };\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function(v) {\n return new NativeBigInt(this.value % parseValue(v).value);\n };\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder =\n BigInteger.prototype.mod;\n\n BigInteger.prototype.pow = function(v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value,\n value,\n x,\n y;\n if (b === 0) return Integer[1];\n if (a === 0) return Integer[0];\n if (a === 1) return Integer[1];\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\n if (n.sign) {\n return Integer[0];\n }\n if (!n.isSmall)\n throw new Error('The exponent ' + n.toString() + ' is too large.');\n if (this.isSmall) {\n if (isPrecise((value = Math.pow(a, b))))\n return new SmallInteger(truncate(value));\n }\n x = this;\n y = Integer[1];\n while (true) {\n if (b & (1 === 1)) {\n y = y.times(x);\n --b;\n }\n if (b === 0) break;\n b /= 2;\n x = x.square();\n }\n return y;\n };\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\n\n NativeBigInt.prototype.pow = function(v) {\n var n = parseValue(v);\n var a = this.value,\n b = n.value;\n var _0 = BigInt(0),\n _1 = BigInt(1),\n _2 = BigInt(2);\n if (b === _0) return Integer[1];\n if (a === _0) return Integer[0];\n if (a === _1) return Integer[1];\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\n if (n.isNegative()) return new NativeBigInt(_0);\n var x = this;\n var y = Integer[1];\n while (true) {\n if ((b & _1) === _1) {\n y = y.times(x);\n --b;\n }\n if (b === _0) break;\n b /= _2;\n x = x.square();\n }\n return y;\n };\n\n BigInteger.prototype.modPow = function(exp, mod) {\n exp = parseValue(exp);\n mod = parseValue(mod);\n if (mod.isZero()) throw new Error('Cannot take modPow with modulus 0');\n var r = Integer[1],\n base = this.mod(mod);\n while (exp.isPositive()) {\n if (base.isZero()) return Integer[0];\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\n exp = exp.divide(2);\n base = base.square().mod(mod);\n }\n return r;\n };\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow =\n BigInteger.prototype.modPow;\n\n function compareAbs(a, b) {\n if (a.length !== b.length) {\n return a.length > b.length ? 1 : -1;\n }\n for (var i = a.length - 1; i >= 0; i--) {\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\n }\n return 0;\n }\n\n BigInteger.prototype.compareAbs = function(v) {\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (n.isSmall) return 1;\n return compareAbs(a, b);\n };\n SmallInteger.prototype.compareAbs = function(v) {\n var n = parseValue(v),\n a = Math.abs(this.value),\n b = n.value;\n if (n.isSmall) {\n b = Math.abs(b);\n return a === b ? 0 : a > b ? 1 : -1;\n }\n return -1;\n };\n NativeBigInt.prototype.compareAbs = function(v) {\n var a = this.value;\n var b = parseValue(v).value;\n a = a >= 0 ? a : -a;\n b = b >= 0 ? b : -b;\n return a === b ? 0 : a > b ? 1 : -1;\n };\n\n BigInteger.prototype.compare = function(v) {\n // See discussion about comparison with Infinity:\n // https://github.com/peterolson/BigInteger.js/issues/61\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (this.sign !== n.sign) {\n return n.sign ? 1 : -1;\n }\n if (n.isSmall) {\n return this.sign ? -1 : 1;\n }\n return compareAbs(a, b) * (this.sign ? -1 : 1);\n };\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\n\n SmallInteger.prototype.compare = function(v) {\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n\n var n = parseValue(v),\n a = this.value,\n b = n.value;\n if (n.isSmall) {\n return a == b ? 0 : a > b ? 1 : -1;\n }\n if (a < 0 !== n.sign) {\n return a < 0 ? -1 : 1;\n }\n return a < 0 ? 1 : -1;\n };\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\n\n NativeBigInt.prototype.compare = function(v) {\n if (v === Infinity) {\n return -1;\n }\n if (v === -Infinity) {\n return 1;\n }\n var a = this.value;\n var b = parseValue(v).value;\n return a === b ? 0 : a > b ? 1 : -1;\n };\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\n\n BigInteger.prototype.equals = function(v) {\n return this.compare(v) === 0;\n };\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq =\n BigInteger.prototype.equals;\n\n BigInteger.prototype.notEquals = function(v) {\n return this.compare(v) !== 0;\n };\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq =\n BigInteger.prototype.notEquals;\n\n BigInteger.prototype.greater = function(v) {\n return this.compare(v) > 0;\n };\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt =\n BigInteger.prototype.greater;\n\n BigInteger.prototype.lesser = function(v) {\n return this.compare(v) < 0;\n };\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt =\n BigInteger.prototype.lesser;\n\n BigInteger.prototype.greaterOrEquals = function(v) {\n return this.compare(v) >= 0;\n };\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq =\n BigInteger.prototype.greaterOrEquals;\n\n BigInteger.prototype.lesserOrEquals = function(v) {\n return this.compare(v) <= 0;\n };\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq =\n BigInteger.prototype.lesserOrEquals;\n\n BigInteger.prototype.isEven = function() {\n return (this.value[0] & 1) === 0;\n };\n SmallInteger.prototype.isEven = function() {\n return (this.value & 1) === 0;\n };\n NativeBigInt.prototype.isEven = function() {\n return (this.value & BigInt(1)) === BigInt(0);\n };\n\n BigInteger.prototype.isOdd = function() {\n return (this.value[0] & 1) === 1;\n };\n SmallInteger.prototype.isOdd = function() {\n return (this.value & 1) === 1;\n };\n NativeBigInt.prototype.isOdd = function() {\n return (this.value & BigInt(1)) === BigInt(1);\n };\n\n BigInteger.prototype.isPositive = function() {\n return !this.sign;\n };\n SmallInteger.prototype.isPositive = function() {\n return this.value > 0;\n };\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\n\n BigInteger.prototype.isNegative = function() {\n return this.sign;\n };\n SmallInteger.prototype.isNegative = function() {\n return this.value < 0;\n };\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\n\n BigInteger.prototype.isUnit = function() {\n return false;\n };\n SmallInteger.prototype.isUnit = function() {\n return Math.abs(this.value) === 1;\n };\n NativeBigInt.prototype.isUnit = function() {\n return this.abs().value === BigInt(1);\n };\n\n BigInteger.prototype.isZero = function() {\n return false;\n };\n SmallInteger.prototype.isZero = function() {\n return this.value === 0;\n };\n NativeBigInt.prototype.isZero = function() {\n return this.value === BigInt(0);\n };\n\n BigInteger.prototype.isDivisibleBy = function(v) {\n var n = parseValue(v);\n if (n.isZero()) return false;\n if (n.isUnit()) return true;\n if (n.compareAbs(2) === 0) return this.isEven();\n return this.mod(n).isZero();\n };\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy =\n BigInteger.prototype.isDivisibleBy;\n\n function isBasicPrime(v) {\n var n = v.abs();\n if (n.isUnit()) return false;\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\n if (n.lesser(49)) return true;\n // we don't know if it's prime: let the other functions figure it out\n }\n\n function millerRabinTest(n, a) {\n var nPrev = n.prev(),\n b = nPrev,\n r = 0,\n d,\n t,\n i,\n x;\n while (b.isEven()) (b = b.divide(2)), r++;\n next: for (i = 0; i < a.length; i++) {\n if (n.lesser(a[i])) continue;\n x = bigInt(a[i]).modPow(b, n);\n if (x.isUnit() || x.equals(nPrev)) continue;\n for (d = r - 1; d != 0; d--) {\n x = x.square().mod(n);\n if (x.isUnit()) return false;\n if (x.equals(nPrev)) continue next;\n }\n return false;\n }\n return true;\n }\n\n // Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\n BigInteger.prototype.isPrime = function(strict) {\n var isPrime = isBasicPrime(this);\n if (isPrime !== undefined) return isPrime;\n var n = this.abs();\n var bits = n.bitLength();\n if (bits <= 64)\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\n var logN = Math.log(2) * bits.toJSNumber();\n var t = Math.ceil(strict === true ? 2 * Math.pow(logN, 2) : logN);\n for (var a = [], i = 0; i < t; i++) {\n a.push(bigInt(i + 2));\n }\n return millerRabinTest(n, a);\n };\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime =\n BigInteger.prototype.isPrime;\n\n BigInteger.prototype.isProbablePrime = function(iterations) {\n var isPrime = isBasicPrime(this);\n if (isPrime !== undefined) return isPrime;\n var n = this.abs();\n var t = iterations === undefined ? 5 : iterations;\n for (var a = [], i = 0; i < t; i++) {\n a.push(bigInt.randBetween(2, n.minus(2)));\n }\n return millerRabinTest(n, a);\n };\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime =\n BigInteger.prototype.isProbablePrime;\n\n BigInteger.prototype.modInv = function(n) {\n var t = bigInt.zero,\n newT = bigInt.one,\n r = parseValue(n),\n newR = this.abs(),\n q,\n lastT,\n lastR;\n while (!newR.isZero()) {\n q = r.divide(newR);\n lastT = t;\n lastR = r;\n t = newT;\n r = newR;\n newT = lastT.subtract(q.multiply(newT));\n newR = lastR.subtract(q.multiply(newR));\n }\n if (!r.isUnit())\n throw new Error(\n this.toString() + ' and ' + n.toString() + ' are not co-prime'\n );\n if (t.compare(0) === -1) {\n t = t.add(n);\n }\n if (this.isNegative()) {\n return t.negate();\n }\n return t;\n };\n\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv =\n BigInteger.prototype.modInv;\n\n BigInteger.prototype.next = function() {\n var value = this.value;\n if (this.sign) {\n return subtractSmall(value, 1, this.sign);\n }\n return new BigInteger(addSmall(value, 1), this.sign);\n };\n SmallInteger.prototype.next = function() {\n var value = this.value;\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\n return new BigInteger(MAX_INT_ARR, false);\n };\n NativeBigInt.prototype.next = function() {\n return new NativeBigInt(this.value + BigInt(1));\n };\n\n BigInteger.prototype.prev = function() {\n var value = this.value;\n if (this.sign) {\n return new BigInteger(addSmall(value, 1), true);\n }\n return subtractSmall(value, 1, this.sign);\n };\n SmallInteger.prototype.prev = function() {\n var value = this.value;\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\n return new BigInteger(MAX_INT_ARR, true);\n };\n NativeBigInt.prototype.prev = function() {\n return new NativeBigInt(this.value - BigInt(1));\n };\n\n var powersOfTwo = [1];\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE)\n powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\n var powers2Length = powersOfTwo.length,\n highestPower2 = powersOfTwo[powers2Length - 1];\n\n function shift_isSmall(n) {\n return Math.abs(n) <= BASE;\n }\n\n BigInteger.prototype.shiftLeft = function(v) {\n var n = parseValue(v).toJSNumber();\n if (!shift_isSmall(n)) {\n throw new Error(String(n) + ' is too large for shifting.');\n }\n if (n < 0) return this.shiftRight(-n);\n var result = this;\n if (result.isZero()) return result;\n while (n >= powers2Length) {\n result = result.multiply(highestPower2);\n n -= powers2Length - 1;\n }\n return result.multiply(powersOfTwo[n]);\n };\n NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft =\n BigInteger.prototype.shiftLeft;\n\n BigInteger.prototype.shiftRight = function(v) {\n var remQuo;\n var n = parseValue(v).toJSNumber();\n if (!shift_isSmall(n)) {\n throw new Error(String(n) + ' is too large for shifting.');\n }\n if (n < 0) return this.shiftLeft(-n);\n var result = this;\n while (n >= powers2Length) {\n if (result.isZero() || (result.isNegative() && result.isUnit()))\n return result;\n remQuo = divModAny(result, highestPower2);\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\n n -= powers2Length - 1;\n }\n remQuo = divModAny(result, powersOfTwo[n]);\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\n };\n NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight =\n BigInteger.prototype.shiftRight;\n\n function bitwise(x, y, fn) {\n y = parseValue(y);\n var xSign = x.isNegative(),\n ySign = y.isNegative();\n var xRem = xSign ? x.not() : x,\n yRem = ySign ? y.not() : y;\n var xDigit = 0,\n yDigit = 0;\n var xDivMod = null,\n yDivMod = null;\n var result = [];\n while (!xRem.isZero() || !yRem.isZero()) {\n xDivMod = divModAny(xRem, highestPower2);\n xDigit = xDivMod[1].toJSNumber();\n if (xSign) {\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\n }\n\n yDivMod = divModAny(yRem, highestPower2);\n yDigit = yDivMod[1].toJSNumber();\n if (ySign) {\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\n }\n\n xRem = xDivMod[0];\n yRem = yDivMod[0];\n result.push(fn(xDigit, yDigit));\n }\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\n for (var i = result.length - 1; i >= 0; i -= 1) {\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\n }\n return sum;\n }\n\n BigInteger.prototype.not = function() {\n return this.negate().prev();\n };\n NativeBigInt.prototype.not = SmallInteger.prototype.not =\n BigInteger.prototype.not;\n\n BigInteger.prototype.and = function(n) {\n return bitwise(this, n, function(a, b) {\n return a & b;\n });\n };\n NativeBigInt.prototype.and = SmallInteger.prototype.and =\n BigInteger.prototype.and;\n\n BigInteger.prototype.or = function(n) {\n return bitwise(this, n, function(a, b) {\n return a | b;\n });\n };\n NativeBigInt.prototype.or = SmallInteger.prototype.or =\n BigInteger.prototype.or;\n\n BigInteger.prototype.xor = function(n) {\n return bitwise(this, n, function(a, b) {\n return a ^ b;\n });\n };\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor =\n BigInteger.prototype.xor;\n\n var LOBMASK_I = 1 << 30,\n LOBMASK_BI = ((BASE & -BASE) * (BASE & -BASE)) | LOBMASK_I;\n function roughLOB(n) {\n // get lowestOneBit (rough)\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\n var v = n.value,\n x =\n typeof v === 'number'\n ? v | LOBMASK_I\n : typeof v === 'bigint'\n ? v | BigInt(LOBMASK_I)\n : (v[0] + v[1] * BASE) | LOBMASK_BI;\n return x & -x;\n }\n\n function integerLogarithm(value, base) {\n if (base.compareTo(value) <= 0) {\n var tmp = integerLogarithm(value, base.square(base));\n var p = tmp.p;\n var e = tmp.e;\n var t = p.multiply(base);\n return t.compareTo(value) <= 0\n ? { p: t, e: e * 2 + 1 }\n : { p: p, e: e * 2 };\n }\n return { p: bigInt(1), e: 0 };\n }\n\n BigInteger.prototype.bitLength = function() {\n var n = this;\n if (n.compareTo(bigInt(0)) < 0) {\n n = n.negate().subtract(bigInt(1));\n }\n if (n.compareTo(bigInt(0)) === 0) {\n return bigInt(0);\n }\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\n };\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength =\n BigInteger.prototype.bitLength;\n\n function max(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n return a.greater(b) ? a : b;\n }\n function min(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n return a.lesser(b) ? a : b;\n }\n function gcd(a, b) {\n a = parseValue(a).abs();\n b = parseValue(b).abs();\n if (a.equals(b)) return a;\n if (a.isZero()) return b;\n if (b.isZero()) return a;\n var c = Integer[1],\n d,\n t;\n while (a.isEven() && b.isEven()) {\n d = min(roughLOB(a), roughLOB(b));\n a = a.divide(d);\n b = b.divide(d);\n c = c.multiply(d);\n }\n while (a.isEven()) {\n a = a.divide(roughLOB(a));\n }\n do {\n while (b.isEven()) {\n b = b.divide(roughLOB(b));\n }\n if (a.greater(b)) {\n t = b;\n b = a;\n a = t;\n }\n b = b.subtract(a);\n } while (!b.isZero());\n return c.isUnit() ? a : a.multiply(c);\n }\n function lcm(a, b) {\n a = parseValue(a).abs();\n b = parseValue(b).abs();\n return a.divide(gcd(a, b)).multiply(b);\n }\n function randBetween(a, b) {\n a = parseValue(a);\n b = parseValue(b);\n var low = min(a, b),\n high = max(a, b);\n var range = high.subtract(low).add(1);\n if (range.isSmall) return low.add(Math.floor(Math.random() * range));\n var digits = toBase(range, BASE).value;\n var result = [],\n restricted = true;\n for (var i = 0; i < digits.length; i++) {\n var top = restricted ? digits[i] : BASE;\n var digit = truncate(Math.random() * top);\n result.push(digit);\n if (digit < top) restricted = false;\n }\n return low.add(Integer.fromArray(result, BASE, false));\n }\n\n var parseBase = function(text, base, alphabet, caseSensitive) {\n alphabet = alphabet || DEFAULT_ALPHABET;\n text = String(text);\n if (!caseSensitive) {\n text = text.toLowerCase();\n alphabet = alphabet.toLowerCase();\n }\n var length = text.length;\n var i;\n var absBase = Math.abs(base);\n var alphabetValues = {};\n for (i = 0; i < alphabet.length; i++) {\n alphabetValues[alphabet[i]] = i;\n }\n for (i = 0; i < length; i++) {\n var c = text[i];\n if (c === '-') continue;\n if (c in alphabetValues) {\n if (alphabetValues[c] >= absBase) {\n if (c === '1' && absBase === 1) continue;\n throw new Error(c + ' is not a valid digit in base ' + base + '.');\n }\n }\n }\n base = parseValue(base);\n var digits = [];\n var isNegative = text[0] === '-';\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\n var c = text[i];\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\n else if (c === '<') {\n var start = i;\n do {\n i++;\n } while (text[i] !== '>' && i < text.length);\n digits.push(parseValue(text.slice(start + 1, i)));\n } else throw new Error(c + ' is not a valid character');\n }\n return parseBaseFromArray(digits, base, isNegative);\n };\n\n function parseBaseFromArray(digits, base, isNegative) {\n var val = Integer[0],\n pow = Integer[1],\n i;\n for (i = digits.length - 1; i >= 0; i--) {\n val = val.add(digits[i].times(pow));\n pow = pow.times(base);\n }\n return isNegative ? val.negate() : val;\n }\n\n function stringify(digit, alphabet) {\n alphabet = alphabet || DEFAULT_ALPHABET;\n if (digit < alphabet.length) {\n return alphabet[digit];\n }\n return '<' + digit + '>';\n }\n\n function toBase(n, base) {\n base = bigInt(base);\n if (base.isZero()) {\n if (n.isZero()) return { value: [0], isNegative: false };\n throw new Error('Cannot convert nonzero numbers to base 0.');\n }\n if (base.equals(-1)) {\n if (n.isZero()) return { value: [0], isNegative: false };\n if (n.isNegative())\n return {\n value: [].concat.apply(\n [],\n Array.apply(null, Array(-n.toJSNumber())).map(\n Array.prototype.valueOf,\n [1, 0]\n )\n ),\n isNegative: false,\n };\n\n var arr = Array.apply(null, Array(n.toJSNumber() - 1)).map(\n Array.prototype.valueOf,\n [0, 1]\n );\n arr.unshift([1]);\n return {\n value: [].concat.apply([], arr),\n isNegative: false,\n };\n }\n\n var neg = false;\n if (n.isNegative() && base.isPositive()) {\n neg = true;\n n = n.abs();\n }\n if (base.isUnit()) {\n if (n.isZero()) return { value: [0], isNegative: false };\n\n return {\n value: Array.apply(null, Array(n.toJSNumber())).map(\n Number.prototype.valueOf,\n 1\n ),\n isNegative: neg,\n };\n }\n var out = [];\n var left = n,\n divmod;\n while (left.isNegative() || left.compareAbs(base) >= 0) {\n divmod = left.divmod(base);\n left = divmod.quotient;\n var digit = divmod.remainder;\n if (digit.isNegative()) {\n digit = base.minus(digit).abs();\n left = left.next();\n }\n out.push(digit.toJSNumber());\n }\n out.push(left.toJSNumber());\n return { value: out.reverse(), isNegative: neg };\n }\n\n function toBaseString(n, base, alphabet) {\n var arr = toBase(n, base);\n return (\n (arr.isNegative ? '-' : '') +\n arr.value\n .map(function(x) {\n return stringify(x, alphabet);\n })\n .join('')\n );\n }\n\n BigInteger.prototype.toArray = function(radix) {\n return toBase(this, radix);\n };\n\n SmallInteger.prototype.toArray = function(radix) {\n return toBase(this, radix);\n };\n\n NativeBigInt.prototype.toArray = function(radix) {\n return toBase(this, radix);\n };\n\n BigInteger.prototype.toString = function(radix, alphabet) {\n if (radix === undefined) radix = 10;\n if (radix !== 10) return toBaseString(this, radix, alphabet);\n var v = this.value,\n l = v.length,\n str = String(v[--l]),\n zeros = '0000000',\n digit;\n while (--l >= 0) {\n digit = String(v[l]);\n str += zeros.slice(digit.length) + digit;\n }\n var sign = this.sign ? '-' : '';\n return sign + str;\n };\n\n SmallInteger.prototype.toString = function(radix, alphabet) {\n if (radix === undefined) radix = 10;\n if (radix != 10) return toBaseString(this, radix, alphabet);\n return String(this.value);\n };\n\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\n\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function() {\n return this.toString();\n };\n\n BigInteger.prototype.valueOf = function() {\n return parseInt(this.toString(), 10);\n };\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\n\n SmallInteger.prototype.valueOf = function() {\n return this.value;\n };\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function() {\n return parseInt(this.toString(), 10);\n };\n\n function parseStringValue(v) {\n if (isPrecise(+v)) {\n var x = +v;\n if (x === truncate(x))\n return supportsNativeBigInt\n ? new NativeBigInt(BigInt(x))\n : new SmallInteger(x);\n throw new Error('Invalid integer: ' + v);\n }\n var sign = v[0] === '-';\n if (sign) v = v.slice(1);\n var split = v.split(/e/i);\n if (split.length > 2)\n throw new Error('Invalid integer: ' + split.join('e'));\n if (split.length === 2) {\n var exp = split[1];\n if (exp[0] === '+') exp = exp.slice(1);\n exp = +exp;\n if (exp !== truncate(exp) || !isPrecise(exp))\n throw new Error(\n 'Invalid integer: ' + exp + ' is not a valid exponent.'\n );\n var text = split[0];\n var decimalPlace = text.indexOf('.');\n if (decimalPlace >= 0) {\n exp -= text.length - decimalPlace - 1;\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\n }\n if (exp < 0)\n throw new Error('Cannot include negative exponent part for integers');\n text += new Array(exp + 1).join('0');\n v = text;\n }\n var isValid = /^([0-9][0-9]*)$/.test(v);\n if (!isValid) throw new Error('Invalid integer: ' + v);\n if (supportsNativeBigInt) {\n return new NativeBigInt(BigInt(sign ? '-' + v : v));\n }\n var r = [],\n max = v.length,\n l = LOG_BASE,\n min = max - l;\n while (max > 0) {\n r.push(+v.slice(min, max));\n min -= l;\n if (min < 0) min = 0;\n max -= l;\n }\n trim(r);\n return new BigInteger(r, sign);\n }\n\n function parseNumberValue(v) {\n if (supportsNativeBigInt) {\n return new NativeBigInt(BigInt(v));\n }\n if (isPrecise(v)) {\n if (v !== truncate(v)) throw new Error(v + ' is not an integer.');\n return new SmallInteger(v);\n }\n return parseStringValue(v.toString());\n }\n\n function parseValue(v) {\n if (typeof v === 'number') {\n return parseNumberValue(v);\n }\n if (typeof v === 'string') {\n return parseStringValue(v);\n }\n if (typeof v === 'bigint') {\n return new NativeBigInt(v);\n }\n return v;\n }\n // Pre-define numbers in range [-999,999]\n for (var i = 0; i < 1000; i++) {\n Integer[i] = parseValue(i);\n if (i > 0) Integer[-i] = parseValue(-i);\n }\n // Backwards compatibility\n Integer.one = Integer[1];\n Integer.zero = Integer[0];\n Integer.minusOne = Integer[-1];\n Integer.max = max;\n Integer.min = min;\n Integer.gcd = gcd;\n Integer.lcm = lcm;\n Integer.isInstance = function(x) {\n return (\n x instanceof BigInteger ||\n x instanceof SmallInteger ||\n x instanceof NativeBigInt\n );\n };\n Integer.randBetween = randBetween;\n\n Integer.fromArray = function(digits, base, isNegative) {\n return parseBaseFromArray(\n digits.map(parseValue),\n parseValue(base || 10),\n isNegative\n );\n };\n\n return Integer;\n})();\n\n// Node.js check\nif (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {\n module.exports = bigInt;\n}\n\n//amd check\nif (typeof define === 'function' && define.amd) {\n define('big-integer', [], function() {\n return bigInt;\n });\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\n// your code goes here\n\nvar input = ``;\n\nfunction cacheInput(data) {\n input += data;\n}\n\nfunction main() {\n let lines = input.split('\\r\\n');\n let n = parseInt(lines[0]);\n for (var i = 1; i <= n; i++) {\n let steps = bigInt(0);\n let input = lines[i].split(' ');\n let n = bigInt(input[0]);\n let k = bigInt(input[1]);\n while (n.value) {\n let mod = bigInt(n).mod(bigInt(k));\n if (mod.value === 0) {\n n = bigInt(n).divide(bigInt(k));\n steps = bigInt(steps).add(1);\n } else {\n n = bigInt(n).minus(bigInt(mod));\n steps = bigInt(steps).add(bigInt(mod));\n }\n }\n console.log(steps.toString());\n }\n}\n\nprocess.stdin.on('data', cacheInput).on('end', main);"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet ans = '';\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let [n, k] = d.split(' ').map(BigInt);\n let curr = 0n;\n\n while (n > 0n) {\n let reminder = n % k;\n if (reminder === 0n) {\n n /= k;\n curr++;\n }\n else {\n curr += reminder;\n n -= reminder;\n }\n }\n\n ans += `${curr.toString()}\\n`;\n\n c++;\n});\n\nrl.on('close', () => {\n console.log(ans);\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$$$) — 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 inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let num = +readLine();\n if (num % 4 === 0) console.log(\"YES\");\n else console.log(\"NO\");\n }\n}\n"}, {"source_code": "//↓見なくていいよ!ここから--------------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//↑見なくていいよ!ここまで--------------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = nextInt();\n\t\tif(N % 4 == 0){\n\t\t\toutput[i] = \"YES\";\n\t\t}else{\n\t\t\toutput[i] = \"NO\";\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "var data = '';\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', (buffer) =>\n{\n data += buffer;\n});\n\nprocess.stdin.on('end', () =>\n{\n var x = data.split(/\\s+/);\n for (var i = 1; i <= x[0]; i++)\n console.log(x[i] % 4 ? 'NO' : 'YES');\n})"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nlet input = '';\nprocess.stdin.on('data', (line) => {\n input += line;\n});\nprocess.stdin.on('end', () => {\n const lines = input.split('\\n');\n let tests = parseInt(lines.shift(), 10);\n while (tests--) {\n const n = parseInt(lines.shift(), 10);\n console.log(n % 4 ? 'NO' : 'YES');\n }\n});\n// input helper\nfunction lineToNumArray(line) {\n return line.split(' ').map(element => parseInt(element, 10));\n}\n"}, {"source_code": "const processData = (lines) => {\n let acc = 0\n const n = +lines[acc]\n acc++\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "\nlet _inputLines;\nlet _lineNumber = 0;\nlet inputReader = _inputReader ();\n\nfunction _main() {\n\t\n\t_inputLines = _inputData.trim().split('\\n').map((string) => {\n\t\treturn string.trim();\n\t});;\n\tlet t=inputReader.readNumber();\n\twhile(t--){\n\t let n=inputReader.readNumber();\n\t if(n%4==0){\n\t console.log('YES'); \n\t \n\t }else{\n\t console.log(\"NO\");\n\t }\n\t}\n\t\n\n}\n\nvar _inputData = '';\nfunction cacheInput(data) {\n\t_inputData += data;\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', cacheInput).on('end', _main);\n\nfunction _inputReader () {\n\tfunction readNumber(){\n\t\treturn Number(_inputLines[_lineNumber++]);\n\t}\n\t\t\n\t\n\treturn {\n\t\treadNumber,\n\t}\n}"}, {"source_code": "function solve() {\n var T = Number(read());\n for (var t = 0; t < T; t++) {\n var n = BigInt(read());\n write(n % 4n === 0n ? 'YES' : 'NO');\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n\n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n\n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n solve();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n\n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n\n RL.on('close', solve);\n }\n} else {\n solve();\n}\n\nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main(){\n let n = readline();\n while(n--){\n let x = readline();\n x%4 === 0 ? console.log('YES') : console.log('NO');\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let t = readLine()\n t = parseInt(t)\n let side = 0\n \n for (let i = 0; i < t; i++) {\n side = readLine()\n side = parseInt(side)\n \n if (side % 4 === 0) console.log(\"YES\")\n else console.log(\"NO\")\n }\n}\n\n\n"}, {"source_code": "\"use strict\";\n\nlet t = readline();\n\nfor(let i=0;i {\n MEMORY = data.split('\\r\\n');\n solve();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', solve);\n }\n} else {\n solve();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}"}, {"source_code": "var Tc = parseInt(readline());\nwhile (Tc-- > 0) {\n\tvar n = parseInt(readline());\n\tprint(n % 4 == 0 ? 'YES' : 'NO');\n}\n"}, {"source_code": "var t = Number(readline());\nwhile (t--) {\n var n = Number(readline());\n print(n % 4 == 0 ? 'YES' : 'NO');\n}"}], "negative_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let num = +readLine();\n if (num % 2 === 0 && num >= 4) console.log(\"YES\");\n else console.log(\"NO\");\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let num = +readLine();\n if (num % 2 === 0) console.log(\"YES\");\n else console.log(\"NO\");\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let t = readLine()\n t = parseInt(t)\n let side = 0\n for (let i = 0; i < t; i++) {\n side = readLine()\n side = parseInt(side)\n if (side <= 3 || side === 5 || side === 6) console.log(\"NO\")\n else console.log(\"YES\")\n }\n \n}"}], "src_uid": "07e56d4031bcb119d2f684203f7ed133"} {"nl": {"description": "You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima.An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.", "input_spec": "The first line contains one integer n (1 ≤ n ≤ 1000) — the number of elements in array a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the elements of array a.", "output_spec": "Print the number of local extrema in the given array.", "sample_inputs": ["3\n1 2 3", "4\n1 5 2 5"], "sample_outputs": ["0", "2"], "notes": null}, "positive_code": [{"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var N = nextInt();\n var list = nextIntArray();\n var output = 0;\n for(var i = 1; i < N - 1; i++){\n if(list[i] < list[i + 1] && list[i] < list[i - 1] || list[i] > list[i + 1] && list[i] > list[i - 1]){\n output++;\n }\n }\n myout(output);\n}"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let ans = 0;\n\n for (let i = 1; i < arr.length - 1; i++) {\n if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) {\n ans++;\n }\n\n if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {\n ans++;\n }\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "function readArr()\n{\n return readline().split(' ').map(function(x){return +x;})\n}\n\nn=+readline()\na=readArr()\nkol=0\nfor (i=1;ia[i-1]&&a[i]>a[i+1])kol++;\n if (a[i] ar[i-1] && ar[i] > ar[i+1])) {\n\t\tres++;\n\t}\n}\n\nprint(res);"}, {"source_code": "var n = Number(readline());\nvar a = readline().split(\" \").map(function(each) {return Number(each);});\n\nvar count = 0;\nfor (var i = 1; i < a.length - 1; ++i) {\n if ((a[i] > a[i - 1] && a[i] > a[i + 1]) || (a[i] < a[i - 1] && a[i] < a[i + 1]))\n ++count;\n}\n\nprint(count);"}, {"source_code": "n = readline();\nstr = readline().split(' ').map(Number);\n\nvar count = 0;\n\nfor (var i = 1; i < str.length - 1; i++) {\n\tif ((str[i] > str[i - 1] && str[i] > str[i + 1]) || (str[i] < str[i - 1] && str[i] < str[i + 1])) {\n\t\tcount++;\n\t};\n};\n\nprint(count);"}], "negative_code": [{"source_code": "var n = Number(readline());\nvar a = readline().split(\" \").map(function(each) {return Number(each);});\n\nvar count = 0;\nfor (var i = 1; i < a.length - 1; ++i) {\n if ((a[i] > a[i - 1] && a[i] > a[i + 1]) || (a[i] < a[i - 1] && a[i] < a[i - 1]))\n ++count;\n}\n\nprint(count);"}], "src_uid": "67cf9f83ed791a614bd01c5e0310813f"} {"nl": {"description": "Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?", "input_spec": "The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.", "output_spec": "Print a single integer – the answer to the problem.", "sample_inputs": ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"], "sample_outputs": ["82", "4"], "notes": "NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin."}, "positive_code": [{"source_code": ";(function () {\n var n = readline().split(' ').map(Number),\n k = n[1],\n m = {},\n q = null,\n s = 0,\n i = 0;\n n = n[0];\n\n readline().split('').forEach(function (e) {\n m[e] = m[e] ? m[e] + 1 : 1;\n });\n\n q = Object.keys(m).sort(function (a, b) {\n return m[b] - m[a];\n });\n\n while (k > 0) {\n s += Math.pow(Math.min(m[q[i]], k), 2);\n k -= m[q[i++]];\n }\n\n print(s);\n\n}.call(this));\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar data = tokenizeIntegers(readline()),\n\t\tn = data[0], k = data[1],\n\t\tcards = trim(readline()),\n\t\tcounts = {};\n\tfor (var i = 65; i <= 90; ++i) {\n\t\tcounts[String.fromCharCode(i)] = 0;\n\t}\n\tfor (var i = 0; i < n; ++i) {\n\t\tcounts[cards.charAt(i)] += 1;\n\t}\n\tvar pairs = [];\n\tfor (var i = 65; i <= 90; ++i) {\n\t\tvar ch = String.fromCharCode(i);\n\t\tpairs.push([ch, counts[ch]]);\n\t}\n\tpairs.sort(function (a, b) {\n\t\treturn a[1] - b[1];\n\t});\n\tvar score = 0, pos = 25;\n\twhile (k != 0 && pos != -1) {\n\t\tvar count = Math.min(k, pairs[pos][1]);\n\t\tk -= count;\n\t\tscore += count*count;\n\t\t--pos;\n\t}\n\tprint(score);\n}\n\nmain();\n"}, {"source_code": "var input = readline().replace(/\\s{1,}/gi, ' ').split(/\\s/).map(Number),\n\t\t\tn = input[0], k = input[1],\n\t\t\taCards = readline().split(''),\n\t\t\tprevCard = '', count = 0, rs = [], sum = 0, ts = {};\n\n\t\taCards.forEach(function(a, i)\t{\n\t\t\tvar tsCount = ts[a] == undefined ? 0 : ts[a];\n\n\t\t\tts[a] = tsCount + 1;\n\t\t});\n\n\t\tObject.keys(ts).forEach(function(c, i)\t{ rs.push(ts[c]); });\n\n\t\trs.sort(function(a, b){return b-a});\n\n\t\tfor(var i=0; i= k)\t{\n\t\t\t\tcount -= c;\n\n\t\t\t\tsum += Math.pow(k - count, 2);\n\n\t\t\t\tbreak;\n\t\t\t} else\t{\n\t\t\t\tsum += Math.pow(c, 2);\n\t\t\t}\n\t\t}\n\n\t\tprint(sum);"}, {"source_code": "/**\n * Created by artyom.\n */\n\nvar a = readline().split(' ').map(function (v) {\n return parseInt(v);\n }),\n n = a[0], k = a[1], i, sum = 0, t, size = 26,\n s = readline(),\n g = Array.apply(null, new Array(size)).map(Number.prototype.valueOf, 0);\n\nfor (i = 0; i < n; i++) {\n g[s.charCodeAt(i) - 65]++;\n}\ng.sort(function (a, b) {\n return a - b;\n});\nfor (i = size - 1; i >= 0 && k > 0; i--) {\n t = Math.min(g[i], k);\n sum += t * t;\n k -= t;\n}\n\nprint(sum);"}, {"source_code": "function gao()\n{\n var numbers = readline().split(' ');\n\tvar str = readline();\n\tvar n = numbers[0];\n\tvar k = numbers[1];\n var alphbet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\tvar amounts = new Array(26);\n\tfor( var i = 0; i< alphbet.length; i++)\n\t{\n\t var c = alphbet.charAt(i);\n\t var reg = new RegExp( c, 'g' );\n\t var result = str.match(reg);\n\t\tif(result != null )\n\t\t{\n\t amounts[i] = result.length;\n\t\t}\n\t}\n\t\n\tamounts.sort(sortNum);\n\t\n\tvar ans = 0;\n\tfor( var i=0;i= 0 && k > 0; i--) {\n t = Math.min(g[i], k);\n sum += t * t;\n k -= t;\n}\n\nprint(sum);"}], "src_uid": "480defc596ee5bc800ea569fd76dc584"} {"nl": {"description": "Consider a conveyor belt represented using a grid consisting of $$$n$$$ rows and $$$m$$$ columns. The cell in the $$$i$$$-th row from the top and the $$$j$$$-th column from the left is labelled $$$(i,j)$$$. Every cell, except $$$(n,m)$$$, has a direction R (Right) or D (Down) assigned to it. If the cell $$$(i,j)$$$ is assigned direction R, any luggage kept on that will move to the cell $$$(i,j+1)$$$. Similarly, if the cell $$$(i,j)$$$ is assigned direction D, any luggage kept on that will move to the cell $$$(i+1,j)$$$. If at any moment, the luggage moves out of the grid, it is considered to be lost. There is a counter at the cell $$$(n,m)$$$ from where all luggage is picked. A conveyor belt is called functional if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell $$$(i,j)$$$, any luggage placed in this cell should eventually end up in the cell $$$(n,m)$$$. This may not hold initially; you are, however, allowed to change the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.Please note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n, m$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m \\le 100$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines each contain $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line, $$$a_{i,j}$$$ is the initial direction of the cell $$$(i, j)$$$. Please note that $$$a_{n,m}=$$$ C.", "output_spec": "For each case, output in a new line the minimum number of cells that you have to change to make the conveyor belt functional. ", "sample_inputs": ["4\n3 3\nRRD\nDDR\nRRC\n1 4\nDDDC\n6 9\nRDDDDDRRR\nRRDDRRDDD\nRRDRDRRDR\nDDDDRDDRR\nDRRDRDDDR\nDDRDRRDDC\n1 1\nC"], "sample_outputs": ["1\n3\n9\n0"], "notes": "NoteIn the first case, just changing the direction of $$$(2,3)$$$ to D is enough.You can verify that the resulting belt is functional. For example, if we place any luggage at $$$(2,2)$$$, it first moves to $$$(3,2)$$$ and then to $$$(3,3)$$$. In the second case, we have no option but to change the first $$$3$$$ cells from D to R making the grid equal to RRRC."}, "positive_code": [{"source_code": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var changes = 0;\n var nm = readNumArray();\n var n = nm[0];\n var m = nm[1];\n for (var j = 0; j < n; j++) {\n var next = readline();\n if (j < n - 1 && next[m - 1] === 'R') {\n changes ++;\n }\n if (j === n - 1) {\n for (var k = 0; k < m - 1; k++) {\n if (next[k] === 'D') {\n changes++;\n }\n }\n }\n }\n print(changes);\n }\n}\n\nmain();"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n \n \nfunction main() {\n const x = readline();\n var cases = parseInt(x);\n //console.log(\"Cases\",cases);\n for(var i=1;i<=cases;i++){\n //console.log(\"case \",i);\n var line2 = readline();\n var dims = line2.split(\" \");\n var row = parseInt(dims[0]);\n var col = parseInt(dims[1]);\n \n var arr = [];\n for(var p=0;p {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [row, col] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n let i = 0;\n let count = 0;\n const store = [];\n while (i < row) {\n const r = readLine().split(\"\");\n store.push(r);\n if (r[col - 1] === \"R\") count++;\n i++;\n }\n for (let i = 0; i < col; i++) {\n if (store[row - 1][i] === \"D\") count++;\n }\n\n console.log(count);\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n \tvar one = nextIntArray();\n \tvar N = one[0];\n \tvar M = one[1];\n \tvar list = new Array(N);\n \tfor(var j = 0; j < N; j++){\n \t\tlist[j] = nextCharArray();\n \t}\n \tvar count = 0;\n \tfor(var j = 0; j < N - 1; j++){\n \t\tif(list[j][M - 1] == \"R\"){\n \t\t\tcount++;\n \t\t}\n \t}\n \tfor(var j = 0; j < M; j++){\n \t\tif(list[N - 1][j] == \"D\"){\n \t\t\tcount++;\n \t\t}\n \t}\n \toutput[i] = count;\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n\tdata = data.split('\\n');\n\tconst testCases = data[0] * 1;\n\tlet i = 1;\n\tlet r = 1;\n\twhile (i <= testCases) {\n let num = data[r].trim().split(' ').map(Number);\n let n = num[0] * 1;\n let m = r + 1;\n r += n + 1;\n let count = 0;\n let arr = [];\n for (let j = m; j < r; j += 1) arr.push(data[j].trim());\n if (n === 1) {\n for (let j = 0; j < arr[0].length; j += 1) {\n if (arr[0][j] === 'D') count += 1;\n }\n } else {\n for (let j = 0; j < arr.length; j += 1) {\n if (arr[j][arr[j].length - 1] === 'R') count += 1;\n }\n for (let j = 0; j < arr[arr.length - 1].length - 1; j += 1) {\n if (arr[arr.length - 1][j] === 'D') count += 1;\n }\n }\n console.log(count);\n i += 1;\n\t}\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.split(/\\n/);\n main(); \n});\n \nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n const t = Number(readLine())\n for (let i = 0; i < t; i++) {\n const [n, m] = readLine().split(/\\s/).map(Number)\n let result = 0;\n for (let r = 0; r < n; r++) {\n const row = readLine()\n if (r === n - 1) {\n for (let c = 0; c < m - 1; c++) {\n if (row[c] === 'D') {\n result += 1\n }\n }\n } else if (row[m - 1] === 'R') {\n result += 1\n }\n }\n console.log(result)\n }\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet [n, m] = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\t\tlet arr = [],\n\t\t\tc = 0;\n\n\t\tfor (let i = 0; i < n; ++i) {\n\t\t\tlet l = readLine().split('');\n\t\t\tarr.push(l);\n\t\t\tif (arr[i][m - 1] === 'R') c++;\n\t\t\tif (i === n - 1) {\n\t\t\t\tfor (let j = 0; j < m - 1; j++) if (arr[n - 1][j] === 'D') c++;\n\t\t\t}\n\t\t}\n\n\t\tconsole.log(c);\n\t}\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction lcm(a, b) {\n return (a / gcd(a, b) * b);\n}\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n \n \nfunction main() {\n const x = readline();\n var cases = parseInt(x);\n //console.log(\"Cases\",cases);\n for(var i=1;i<=cases;i++){\n //console.log(\"case \",i);\n var line2 = readline();\n var dims = line2.split(\" \");\n var row = parseInt(dims[0]);\n var col = parseInt(dims[1]);\n \n var arr = [];\n for(var p=0;p0){\n var leftElem = arr[row][col-1];\n if(leftElem == \"R\"){\n minValFromLeft = dp[row][col-1];\n }\n else{\n minValFromLeft = 1+dp[row][col-1];\n }\n }\n if(row>0){\n var topElem = arr[row-1][col];\n if(topElem == \"D\"){\n minValFromTop = dp[row-1][col];\n }\n else{\n minValFromTop = 1+dp[row-1][col];\n }\n }\n dp[row][col] = Math.min(minValFromLeft,minValFromTop);\n }\n }\n\n return dp[arr.length-1][cleng-1];\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n \n \nfunction main() {\n const x = readline();\n var cases = parseInt(x);\n console.log(\"Cases\",cases);\n for(var i=1;i<=cases;i++){\n //console.log(\"case \",i);\n var line2 = readline();\n var dims = line2.split(\" \");\n var row = parseInt(dims[0]);\n var col = parseInt(dims[1]);\n \n var arr = [];\n for(var p=0;p0){\n var leftElem = arr[row][col-1];\n if(leftElem == \"R\"){\n minValFromLeft = dp[row][col-1];\n }\n else{\n minValFromLeft = 1+dp[row][col-1];\n }\n }\n if(row>0){\n var topElem = arr[row-1][col];\n if(topElem == \"D\"){\n minValFromTop = dp[row-1][col];\n }\n else{\n minValFromTop = 1+dp[row-1][col];\n }\n }\n dp[row][col] = Math.min(minValFromLeft,minValFromTop);\n }\n }\n\n return dp[arr.length-1][cleng-1];\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet [n, m] = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\t\tlet arr = [];\n\t\tfor (let i = 0; i < n; i++) arr[i] = readLine().split('');\n\t\tlet c = 0;\n\t\tfor (let i = 0; i < m - 1; ++i) if (arr[0][i] !== 'R') c++;\n\t\tif (arr[0][m - 1] === 'R') c++;\n\t\tfor (let i = 1; i < n - 1; ++i) if (arr[i][m - 1] !== 'D') c++;\n\n\t\tconsole.log(c);\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', data => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\twhile (t--) {\n\t\tlet [n, m] = readLine()\n\t\t\t.split(' ')\n\t\t\t.map(x => x >> 0);\n\t\tlet arr = [];\n\t\tfor (let i = 0; i < n; i++) arr[i] = readLine().split('');\n\n\t\tlet c = 0;\n\t\tfor (let i = 0; i < n - 1; ++i)\n\t\t\tif (arr[i][m - 1] !== 'D') {\n\t\t\t\tc++;\n\t\t\t\tarr[i][m - 1] = 'D';\n\t\t\t}\n\n\t\tfor (let x = 0; x < m - 1; x++) {\n\t\t\tif (arr[0][x] === 'R') continue;\n\t\t\tlet i = 0,\n\t\t\t\tj = x;\n\t\t\twhile (i < n && j < m) {\n\t\t\t\tif (arr[i][j] === 'R') j++;\n\t\t\t\telse i++;\n\t\t\t}\n\t\t\tif (i !== n || j !== m) {\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\n\t\tconsole.log(c);\n\t}\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction lcm(a, b) {\n return (a / gcd(a, b) * b);\n}\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r Number(n));\n let arrays = [];\n let i = 1;\n let prev = 0;\n while (sequenceArray[i]) {\n const curr = sequenceArray[i - 1];\n const next = sequenceArray[i];\n\n if (curr >= next) {\n arrays.push(sequenceArray.slice(prev, i));\n prev = i;\n }\n\n i++;\n\n if (!sequenceArray[i]) {\n arrays.push(sequenceArray.slice(prev, i));\n }\n }\n\n // console.log(arrays);\n console.log(\n arrays.reduce((acc, el) => {\n return el.length > acc ? el.length : acc;\n }, 1)\n );\n}\n\nfunction readLine(str, line) {\n return str.split(/\\r?\\n/).filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let best = 1;\n let curr = 1;\n let v = arr[0];\n\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > v) {\n curr++;\n }\n else {\n curr = 1;\n }\n\n best = Math.max(curr, best);\n v = arr[i];\n }\n\n console.log(best);\n\n c++;\n});\n\nrl.on('close', () => {\n\n});\n"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nlet switcher = false;\n\nrl.on('line', function(line){\n if (switcher) {\n let arr = line.split(' ').map(el => +el);\n console.log(findMaxLength(arr));\n }\n switcher = !switcher;\n});\n\nconst findMaxLength = arr => {\n let maxLength = 1;\n let tmpMax = 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i - 1] < arr[i]) {\n tmpMax++;\n } else {\n if (tmpMax > maxLength) maxLength = tmpMax;\n tmpMax = 1;\n }\n }\n if (tmpMax > maxLength) maxLength = tmpMax;\n return maxLength;\n}"}, {"source_code": "readline = require('readline');\nrl = readline.createInterface({\n input: process.stdin\n})\n\nlet lineNum = 0;\n\nrl.on('line', (l) => {\n lineNum++\n if (lineNum === 1) {\n return\n }\n arr = l.split(\" \").map(x => parseInt(x));\n // console.log(arr);\n let maxlen = 0;\n let x = 0;\n while (x < arr.length) {\n templen = 1;\n let y = x+1;\n while(y < arr.length && arr[y] > arr[y-1]) {\n templen++\n y++\n }\n if (templen > maxlen) {\n maxlen = templen\n }\n x = y;\n }\n console.log(maxlen)\n rl.close();\n})"}, {"source_code": "var n = +readline();\nvar a = readline().split(' ').map(Number);\nvar max = 0, cnt = 1;\nfor (var i = 1; i < n; i++) {\n if (a[i - 1] < a[i]) {\n cnt += 1\n } else {\n max = Math.max(max, cnt);\n cnt = 1\n }\n}\nprint(Math.max(max, cnt));"}, {"source_code": "readline();\nvar arr = readline().split(' ');\narr = arr.map(elem => {\n return parseInt(elem, 10);\n});\nvar res = 1;\nvar max = 0;\nfor (var i = 0; i < arr.length - 1; i++) {\n if (arr[i+1] <= arr[i]) {\n if (res > max) {\n max = res;\n }\n res = 1;\n } else {\n res++;\n }\n}\nif (res > max) {\n max = res;\n}\nprint(max);"}, {"source_code": "var n = readline();\n\nvar a = readline().split(' ');\n\nvar b = [];\n\nfor (var i = 0; i < a.length; i++) {\n a[i] = Number(a[i]);\n}\n\nvar cur = 1;\nvar ans = 1;\n\nfor (var i = 1; i < a.length; i++) {\n a[i] = Number(a[i]);\n if (a[i] > a[i - 1]) {\n cur = cur + 1;\n }\n else {\n cur = 1; \n }\n ans = Math.max(cur, ans);\n}\n\nprint(ans);"}, {"source_code": "//var array = readline().split(\" \").map(item => +item);\nreadline();\nvar line = readline().split(\" \").map(item => +item);\nvar max = 1;\n\nif(line.length > 1) {\n var prev = line[0],\n count = 1;\n\n for(var i = 1; i < line.length; i++) {\n if (prev < line[i]) {\n count++;\n max = Math.max(max, count);\n } else {\n count = 1;\n }\n prev = line[i];\n }\n print(max);\n} else {\n print(1);\n}\n\n//print((i - 1).toString());"}, {"source_code": "'use strict';\n\n// const rlLib = require('readline');\n\n// const rl = rlLib.createInterface({\n// input: process.stdin,\n// output: process.stdout\n// });\n\n// let inputs = [];\n// let allCount = 2;\n// let currentLine = 0;\n\n// rl.on('line', (input) => {\n// inputs.push(input);\n// if (inputs.length >= allCount) {\n// main();\n\n// rl.close(); \n// }\n// });\n\n// function readline() {\n// return inputs[currentLine++];\n// }\n// function print() {\n// console.log.apply(this, arguments);\n// }\n\n\n// // function main() {\n// // let count = +readline();\n// // let arr = readline().split(' ').map(function(e) {return parseInt(e, 10);});\n// // print(func(arr));\n// // }\n\n\n// /**\n// * @param {number} s\n// * @param {number[]} nums\n// * @return {number}\n// */\n// function main() {\n readline();\n let arr = readline().split(' ').map(function(e) {return parseInt(e, 10);});\n let res = 0;\n\n for (var i = 1, count = 1; i < arr.length; i++) {\n if (arr[i] <= arr[i - 1]) {\n if (res < count) {\n res = count;\n }\n count = 1;\n } else {\n count++;\n }\n }\n\n print(count > res ? count : res);\n// };\n\n\n"}, {"source_code": "function main() {\n readline();\n var data = readline().split(' ').map(Number);\n var res = 1;\n var current = 1;\n for(var i=1;idata[i-1]){\n current++;\n } else {\n current = 1;\n }\n if(current>res){\n res = current;\n }\n }\n print(res)\n}\n\n\n\n\nmain()"}, {"source_code": "'use strict';\n\nfunction findMax(n, arr) {\n let maxLen = 1;\n let currentLen = 1;\n\n for (let i=1; i arr[i-1]) {\n currentLen++;\n if (currentLen > maxLen) {\n maxLen = currentLen;\n }\n } else {\n currentLen = 1;\n }\n }\n return maxLen;\n}\n\nprint(findMax(parseInt(readline()), readline().split(' ').map(x=>parseInt(x))));\n"}, {"source_code": "//var n = 3;\nvar n = parseInt(readline());\n//var a = [1, 2, 3];\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\n\nif (n == 1) {\n write(\"1\");\n}\nelse\n{\n var t = 1;\n var max = -1;\n\n for (var i = 1; i< n; ++i) {\n if (a[i - 1] < a[i]) {\n ++t;\n } else {\n if (t > max) {\n max = t;\n }\n t = 1;\n }\n }\n\n if (t > max) {\n max = t;\n }\n\n write(max);\n}\n\n//function write(n) {\n// console.log(n);\n//}"}, {"source_code": "var n = readline();\nvar a = readline().split(' ');\n\nfor (var i = 0; i < a.length; i++) {\n\ta[i] = Number(a[i])\n}\nvar count = 1;\n\nvar ans = 1;\nfor (var i = 0; i < a.length - 1; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++;\n\t} else {\n\t\tcount = 1;\n\t}\n\tans = Math.max(ans, count);\n}\n\nprint(ans);\n// console.log(ans)"}, {"source_code": "var n = readline();\nvar a = readline().split(' ');\n\nfor (var i = 0; i < a.length; i++) {\n\ta[i] = Number(a[i])\n}\n\nvar count = 1;\n\nvar len = []\nvar count = 1\n\nfor (var i = 0; i < a.length; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++\n\t} else {\n\t\tlen.push(count)\n\t\tcount = 1\n\t}\n}\n\nlen.sort().reverse()\n\nprint(len[0])\n// console.log(ans)"}], "negative_code": [{"source_code": "var stdin = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\nprocess.stdin.on(\"data\", function(data) {\n stdin += data;\n});\nprocess.stdin.on(\"end\", function() {\n main(stdin);\n});\n\n// const stdin = `3\n// 1 7 2 11 15`;\n// main(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n const sequence = readLine(stdin, 1);\n const sequenceArray = sequence.split(\" \").map(n => Number(n));\n let maxSeq = 0;\n let currSeq = 1;\n let i = 1;\n while (sequenceArray[i]) {\n const curr = sequenceArray[i - 1];\n const next = sequenceArray[i];\n\n if (curr < next) {\n currSeq++;\n }\n\n maxSeq = maxSeq < currSeq ? currSeq : maxSeq;\n\n if (curr > next) {\n currSeq = 1;\n }\n\n i++;\n }\n\n console.log(maxSeq);\n}\n\nfunction readLine(str, line) {\n return str.split(/\\r?\\n/).filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "var stdin = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\nprocess.stdin.on(\"data\", function(data) {\n stdin += data;\n});\nprocess.stdin.on(\"end\", function() {\n main(stdin);\n});\n\n// const stdin = `5\n// 1 7 2 11 15`;\n// main(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n const sequence = readLine(stdin, 1);\n const sequenceArray = sequence.split(\" \").map(n => Number(n));\n let arrays = [];\n let i = 1;\n let prev = 0;\n while (sequenceArray[i]) {\n const curr = sequenceArray[i - 1];\n const next = sequenceArray[i];\n\n if (curr >= next) {\n arrays.push(sequenceArray.slice(prev, i));\n prev = i;\n }\n\n i++;\n\n if (!sequenceArray[i]) {\n arrays.push(sequenceArray.slice(prev, i));\n }\n }\n\n // console.log(arrays);\n console.log(\n arrays.reduce((acc, el) => {\n return el.length > acc ? el.length : acc;\n }, 0)\n );\n}\n\nfunction readLine(str, line) {\n return str.split(/\\r?\\n/).filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "var stdin = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\nprocess.stdin.on(\"data\", function(data) {\n stdin += data;\n});\nprocess.stdin.on(\"end\", function() {\n main(stdin);\n});\n\n// const stdin = `5\n// 1 7 2 11 15`;\n// main(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n const sequence = readLine(stdin, 1);\n const sequenceArray = sequence.split(\" \").map(n => Number(n));\n let arrays = [];\n let i = 1;\n let prev = 0;\n while (sequenceArray[i]) {\n const curr = sequenceArray[i - 1];\n const next = sequenceArray[i];\n\n if (curr >= next) {\n arrays.push(sequenceArray.slice(prev, i));\n prev = i;\n }\n\n i++;\n\n if (!sequenceArray[i]) {\n arrays.push(sequenceArray.slice(prev, i));\n }\n }\n\n console.log(arrays);\n console.log(\n arrays.reduce((acc, el) => {\n return el.length > acc ? el.length : acc;\n }, 0)\n );\n}\n\nfunction readLine(str, line) {\n return str.split(/\\r?\\n/).filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', function(line){\n if (line.length > 1) {\n let arr = line.split(' ');\n console.log(findMaxLength(arr));\n }\n})\n\nconst findMaxLength = arr => {\n let maxLength = 1;\n let tmpMax = 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i - 1] < arr[i]) {\n tmpMax++;\n } else {\n if (tmpMax > maxLength) maxLength = tmpMax;\n tmpMax = 1;\n }\n }\n if (tmpMax > maxLength) maxLength = tmpMax;\n return maxLength;\n}"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nrl.on('line', function(line){\n if (line.length > 1) {\n let arr = line.split(' ').map(el => +el);\n console.log(findMaxLength(arr));\n }\n})\n\nconst findMaxLength = arr => {\n let maxLength = 1;\n let tmpMax = 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i - 1] < arr[i]) {\n tmpMax++;\n } else {\n if (tmpMax > maxLength) maxLength = tmpMax;\n tmpMax = 1;\n }\n }\n if (tmpMax > maxLength) maxLength = tmpMax;\n return maxLength;\n}"}, {"source_code": "readline = require('readline');\nrl = readline.createInterface({\n input: process.stdin\n})\n\nrl.on('line', (l) => {\n arr = l.split(\" \").map(x => parseInt(x));\n // console.log(arr);\n let maxlen = 0;\n let x = 0;\n while (x < arr.length - 1) {\n templen = 1;\n let y = x+1;\n while(y < arr.length && arr[y] > arr[y-1]) {\n templen++\n y++\n }\n if (templen > maxlen) {\n maxlen = templen\n }\n x = y;\n }\n console.log(maxlen)\n rl.close();\n})"}, {"source_code": "readline();\nvar arr = readline().split(' ');\narr = arr.map(elem => {\n return parseInt(elem);\n});\nvar res = 1;\nvar max = 0;\nfor (var i = 0; i < arr.length - 1; i++) {\n if (arr[i+1] <= arr[i]) {\n if (res > max) {\n max = res;\n res = 1;\n }\n } else {\n res++;\n }\n}\nprint(max);"}, {"source_code": "readline();\nvar arr = readline().split(' ');\narr = arr.map(elem => {\n return parseInt(elem);\n});\nvar res = 1;\nvar max = 1;\nfor (var i = 0; i < arr.length - 1; i++) {\n if (arr[i+1] <= arr[i]) {\n if (res > max) {\n max = res;\n res = 1;\n }\n } else {\n res++;\n }\n}\nif (res > max) {\n max = res;\n}\nprint(max);"}, {"source_code": "readline();\nvar arr = readline().split(' ');\narr = arr.map(elem => {\n return parseInt(elem);\n});\nvar res = 1;\nvar max = 0;\nfor (var i = 0; i < arr.length - 1; i++) {\n if (arr[i+1] <= arr[i]) {\n if (res > max) {\n max = res;\n res = 1;\n }\n } else {\n res++;\n }\n}\nif (res > max) {\n max = res;\n}\nprint(max);"}, {"source_code": "var a = readline().split(' ');\n\nfor (var i = 0; i < a.length; i++) {\n a[i] = Number(a[i]);\n}\n\nvar cur = 1;\nvar ans = 1;\n\nfor (var i = 1; i < a.length; i++) {\n a[i] = Number(a[i]);\n if (a[i] > a[i - 1]) {\n cur = cur + 1;\n }\n else {\n cur = 1; \n }\n ans = Math.max(cur, ans);\n}\n\nprint(ans);"}, {"source_code": "//var array = readline().split(\" \").map(item => +item);\nreadline();\nvar line = readline().split(\" \").map(item => +item);\nvar max = 1;\n\nif(line.length > 1) {\n var prev = line[0],\n count = 1;\n\n for(var i = 1; i < line.length; i++) {\n if (prev < line[i]) {\n count++;\n max = Math.max(max, count);\n prev = line[i];\n } else {\n count = 1;\n }\n }\n print(max);\n} else {\n print(1);\n}\n\n//print((i - 1).toString());"}, {"source_code": "//var n = 5\nvar n = parseInt(readline());\n//var a = [100, 100, 100, 100, 100];\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\n\nvar max = -1;\n\nif (n == 1) {\n write(\"1\");\n} else {\n var t = 0;\n\n for (var i = 1; i< n; ++i) {\n if (a[i - 1] < a[i]) {\n ++t;\n } else {\n if (t > max) {\n max = t;\n }\n t = 1;\n }\n }\n\n if (t > max) {\n max = t;\n }\n\n //console.log(\"r: \" + max);\n write(max);\n}"}, {"source_code": "var n = readline()\nvar a = readline().split(' ')\n\nvar len = []\nvar count = 1\n\nfor (var i = 0; i < a.length; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++\n\t} else {\n\t\tlen.push(count)\n\t\tcount = 1\n\t}\n}\n\nlen.sort().reverse()\n\nprint(len[0])"}, {"source_code": "var n = readline();\nvar a = readline().split(' ');\nvar count = 1;\n\nvar ans = 1;\nfor (var i = 0; i < a.length - 1; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++;\n\t} else {\n\t\tcount = 1;\n\t}\n\tans = Math.max(ans, count);\n}\n\nprint(ans);"}, {"source_code": "var n = readline()\nvar a = readline().split(' ')\n\nvar a = [1, 7, 2, 11, 15]\n\nvar len = []\nvar count = 1\n\nfor (var i = 0; i < a.length - 1; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++\n\t} else {\n\t\tlen.push(count)\n\t\tcount = 1\n\t}\n}\n\nlen.sort().reverse()\n\nprint(len[0])"}, {"source_code": "var n = readline()\nvar a = readline().split(' ');\n\nvar len = [];\nvar count = 1;\n\nfor (var i = 0; i < a.length; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++;\n\t} else {\n\t\tlen.push(count)\n\t\tcount = 1;\n\t}\n}\n\nlen.sort().reverse();\nprint(len[0]);"}, {"source_code": "var n = readline()\nvar a = readline().split(' ')\n\nvar len = []\nvar count = 1\n\nfor (var i = 0; i < a.length - 1; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++\n\t} else {\n\t\tlen.push(count)\n\t\tcount = 1\n\t}\n}\n\nlen.sort().reverse()\n\nprint(len[0])"}, {"source_code": "var n = readline()\nvar a = readline().split(' ')\n\nvar count = 1\n\nvar ans = 1\nfor (var i = 0; i < a.length - 1; i++) {\n\tif (a[i] < a[i + 1]) {\n\t\tcount++\n\t} else {\n\t\tcount = 1\n\t}\n\tans = Math.max(ans, count);\n}\n\nprint(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$$$)  — 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$$$)  — 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": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => { \n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i];\n }else{\n var k = lines[i].split(' ').map(Number);\n var total = 0;\n var flag = false;\n for(j = 0; j < n; j++){\n total += k[j];\n }\n for(j = 0; j < n; j++){\n var a = (total - k[j]) / (n - 1);\n if(k[j] == a){\n flag = true;\n break;\n }\n }\n console.log(flag ? 'YES' : 'NO');\n }\n }\n});"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n\tvar t = lines[0];\n\tvar n = 0;\n\tfor(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i];\n }else{\n var k = lines[i].split(' ').map(Number);\n var sum = 0;\n var b = false;\n for(j = 0; j < n; j++){\n sum += k[j];\n }\n for(j = 0; j < n; j++){\n var v1 = k[j];\n var v2 = ((sum - k[j]) / (n - 1));\n if(v1 == v2){\n b = true;\n break;\n }\n }\n console.log(b ? 'YES' : 'NO');\n }\n }\n});\n\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n let arr = readline().split(' ').map(Number);\r\n\r\n let sum = arr.reduce((a, b) => a + b, 0);\r\n let res = 'NO';\r\n\r\n for (let i = 0; i < n; i++) {\r\n if ((sum - arr[i]) / (n - 1) === arr[i]) {\r\n res = 'YES';\r\n break;\r\n }\r\n }\r\n\r\n output(res);\r\n }\r\n}"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst lineReader = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet inputPos = 0;\r\nconst inputWords = [];\r\nlineReader.on('line', (line) => {\r\n inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));\r\n});\r\nlineReader.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(inputWords[inputPos++]));\r\n}\r\nfunction nextStr() {\r\n return inputWords[inputPos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nfunction lowerBound(a, x) {\r\n let lo = 0;\r\n let hi = a.length;\r\n while (lo < hi) {\r\n let mid = lo + Math.trunc((hi - lo) / 2);\r\n if (a[mid] >= x) {\r\n hi = mid;\r\n }\r\n else {\r\n lo = mid + 1;\r\n }\r\n }\r\n return hi;\r\n}\r\nconst INIT = -1;\r\nconst INF = Infinity;\r\nlet n;\r\nlet a;\r\nfunction solve() {\r\n let sum = 0;\r\n for (let i = 0; i < n; i++) {\r\n sum += a[i];\r\n }\r\n for (let i = 0; i < n; i++) {\r\n let tot = sum - a[i];\r\n if (a[i] * (n - 1) == tot) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n a = af(n);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = nextInt();\r\n }\r\n if (solve()) {\r\n printf(\"YES\\n\");\r\n }\r\n else {\r\n printf(\"NO\\n\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar sum = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tsum += list[i];\r\n\t\t}\r\n\t\tvar ok = false;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tif((sum - list[i]) / (N - 1) == list[i]){\r\n\t\t\t\tok = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout((ok) ? \"Yes\" : \"No\");\r\n\t}\r\n}\r\n"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\n/*---------------------------------------------------*/\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst getDigits = (x) => {\n let digits = new Array(10).fill(false);\n let len = 0;\n while (x) {\n len++;\n digits[x % 10n] = true;\n x /= 10n;\n }\n return [digits, len];\n}\n\nconst getLen = (x) => {\n let str = x.toString(10);\n return str.length;\n}\n\nconst calc = (t)=>{\n /* read */\n let n = readline();\n let a = ra();\n\n let sum = 0;\n for (let i = 0; i < n; i++) {\n sum += a[i];\n }\n\n for (let i = 0; i < n; i++) {\n if ((sum - a[i]) / (n - 1) === a[i]) return 'YES';\n } \n\n return 'NO';\n};\n\nfunction main() {\n let T = +readline();\n let out = [];\n for (let t = 1; t <= T; t++){\n out.push(calc(t));\n // process.stdout.write(`${calc(t)}\\n`);\n }\n process.stdout.write(out.join('\\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"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\nfunction Main(){\r\n // test case in nodeJs\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tsolve();\r\n\t}\r\n}\r\n\r\nfunction solve() {\r\n\tconst n = nextInt();\r\n\tconst arr = nextIntArray(n);\r\n\r\n\tconst sum = arr.reduce((sum, ele) => sum + ele, 0);\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tif (arr[i] === (sum - arr[i]) / (arr.length - 1)) {\r\n\t\t\tmyout(\"YES\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tmyout(\"NO\");\r\n}"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, a) {\r\n const sum = a.reduce((a, b) => a + b, 0);\r\n for (let i = 0; i < n; i++) {\r\n if (sum - a[i] === a[i] * (n - 1)) return 'YES';\r\n }\r\n return 'NO';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = function(arg){\n let str = arg;\n if (arguments.length>1)\n str = Array.prototype.slice.call(arguments).join(' ');\n process.stdout.write(str+'\\n');\n};\nlet IS_MULTITEST, testN, tests;\nconst pcalc = (testN, toPrint)=>{\n let res = CALC(testN);\n if (Array.isArray(res)){\n toPrint.push(res.join(' '));\n } else if (Number.isFinite(res) || typeof res=='string'){\n toPrint.push(res+'');\n }\n if (process.env.DEBUG && toPrint.length){\n let ans = toPrint.pop();\n print(ans);\n let expected = tests[testN-1];\n if (expected){\n if (expected==ans)\n console.log('\\x1b[32m%s\\x1b[0m', 'correct'); \n else {\n console.log('\\x1b[31m%s\\x1b[0m', 'wrong, expected:', expected); \n }\n }\n }\n};\n\nconst main = ()=>{\n let toPrint = [];\n L('\\nSolving:');\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(testN, toPrint);\n } else {\n pcalc(1, toPrint);\n }\n if (toPrint.length){\n print(toPrint.join('\\n'));\n }\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`\\nTest #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\ntests = [\n``, // Test #1\n``, // Test #2\n``, // Test #3\n``, // Test #4\n``, // Test #5\n];\n\n// SOLUTION:\nIS_MULTITEST = true;\n \nconst CALC = (testN)=>{\n // READING:\n let [n, m] = ra();\n let A = ra();\n LT({n, A});\n // PROCESSING:\n let ans = 0;\n for (let i=0; i parseInt(aa) );\n\n if (handle(a))\n print (\"YES\");\n else\n print (\"NO\");\n}\n\nfunction handle(a) {\n\n for (var i=0; i +a)\r\n ans = 'NO'\r\n\r\n mesmo = 1\r\n \r\n for(i=0; i ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n const n = parseInt(await getLine());\r\n const vertices = new Set();\r\n const stack = [];\r\n const addedge = function (a, b) {\r\n if (a > b) {\r\n addedge(b, a);\r\n return;\r\n }\r\n vertices.add(a + ' ' + b);\r\n }\r\n rl.output.write('? 1' + '\\n');\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n addedge(1, i + 1);\r\n }\r\n }\r\n let sumOdd = d.reduce((prev, cur) => { return prev + cur % 2; }, 0);\r\n\r\n d.forEach((dist, index) => {\r\n if (sumOdd < n - sumOdd && dist % 2 === 1)\r\n stack.push(index + 1);\r\n else if (sumOdd >= n - sumOdd && dist % 2 === 0 && dist !== 0)\r\n stack.push(index + 1);\r\n })\r\n\r\n for (let j = 0; j < stack.length; j++) {\r\n const v = stack[j];\r\n rl.output.write('? ' + v + '\\n');\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n addedge(v, i + 1);\r\n }\r\n }\r\n }\r\n\r\n rl.output.write('!\\n');\r\n vertices.forEach(v => {\r\n rl.output.write(v + '\\n');\r\n });\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n const n = parseInt(await getLine());\r\n const vertices = new Set();\r\n const stack = [];\r\n const addedge = function (a, b) {\r\n if (a > b) {\r\n addedge(b, a);\r\n return;\r\n }\r\n vertices.add(a + ' ' + b);\r\n }\r\n rl.output.write('? 1' + '\\n');\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n addedge(1, i + 1);\r\n }\r\n }\r\n const maxPath = Math.max(...d);\r\n const cnt = new Array(n + 1);\r\n let sumOdd = 0;\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] % 2 === 1)\r\n sumOdd++;\r\n }\r\n d.forEach((dist, index) => {\r\n if (sumOdd < n - sumOdd && dist % 2 === 1)\r\n stack.push(index + 1);\r\n else if (sumOdd >= n - sumOdd && dist % 2 === 0 && dist !== 0)\r\n stack.push(index + 1);\r\n })\r\n\r\n for (let j = 0; j < stack.length; j++) {\r\n const v = stack[j];\r\n rl.output.write('? ' + v + '\\n');\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n addedge(v, i + 1);\r\n }\r\n }\r\n }\r\n\r\n rl.output.write('!\\n');\r\n vertices.forEach(v => {\r\n rl.output.write(v + '\\n');\r\n });\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n const n = parseInt(await getLine());\r\n const vertices = new Set();\r\n const stack = [];\r\n const addedge = function (a, b) {\r\n if (a > b) {\r\n addedge(b, a);\r\n return;\r\n }\r\n vertices.add(a + ' ' + b);\r\n }\r\n rl.output.cork();\r\n rl.output.write('? 1' + '\\n');\r\n rl.output.uncork();\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n addedge(1, i + 1);\r\n }\r\n }\r\n const maxPath = Math.max(...d);\r\n const cnt = new Array(n + 1);\r\n let sumOdd = 0;\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] % 2 === 1)\r\n sumOdd++;\r\n }\r\n d.forEach((dist, index) => {\r\n if (sumOdd < n - sumOdd && dist % 2 === 1)\r\n stack.push(index + 1);\r\n else if (sumOdd >= n - sumOdd && dist % 2 === 0 && dist !== 0)\r\n stack.push(index + 1);\r\n })\r\n\r\n for (let j = 0; j < stack.length; j++) {\r\n const v = stack[j];\r\n rl.output.cork();\r\n rl.output.write('? ' + v + '\\n');\r\n rl.output.uncork();\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n addedge(v, i + 1);\r\n }\r\n }\r\n }\r\n\r\n rl.output.write('!\\n');\r\n vertices.forEach(v => {\r\n rl.output.write(v + '\\n');\r\n });\r\n}\r\n\r\nsolve();\r\n"}], "negative_code": [{"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n const n = parseInt(await getLine());\r\n const vertices = new Set();\r\n const stack = [1];\r\n const addedge = function (a, b) {\r\n if (a > b) {\r\n addedge(b, a);\r\n return;\r\n }\r\n vertices.add(a + ' ' + b);\r\n }\r\n const was = new Array(n + 1);\r\n was[1] = true;\r\n while (vertices.size < n - 1) {\r\n const v = stack.shift();\r\n rl.output.write('? ' + v + '\\n');\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n let ones = 0;\r\n let onev;\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n ones++;\r\n onev = i + 1;\r\n addedge(v, i + 1);\r\n } /* else if (d[i] === 2 && !was[i + 1]) {\r\n stack.push(i + 1);\r\n } */\r\n }\r\n if (ones == 1) {\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 2) {\r\n addedge(onev, i + 1);\r\n }\r\n }\r\n }\r\n\r\n for (let i = 0; i < d.length; i++) {\r\n if (d[i] === 2 && !was[i+1]) {\r\n was[i + 1] = true;\r\n stack.push(i + 1);\r\n }\r\n }\r\n\r\n }\r\n\r\n console.log('!');\r\n vertices.forEach(v => {\r\n console.log(v);\r\n });\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => ((await getLineGen.next()).value);\r\n})();\r\n\r\nlet solve = async () => {\r\n const n = parseInt(await getLine());\r\n const vertices = new Set();\r\n const stack = [1];\r\n const addedge = function(a, b) {\r\n if (a > b) {\r\n addedge(b, a);\r\n return;\r\n }\r\n vertices.add(a + ' ' + b);\r\n }\r\n const was = new Array(n + 1);\r\n\r\n while (vertices.size < n - 1) {\r\n const v = stack.shift();\r\n rl.output.write('? ' + v + '\\n');\r\n const d = (await getLine()).split(' ').map(num => parseInt(num));\r\n for(let i = 0; i < d.length; i++) {\r\n if (d[i] === 1) {\r\n addedge(v, i + 1);\r\n } else if (d[i] === 2 && !was[i + 1]) {\r\n stack.push(i + 1);\r\n }\r\n }\r\n }\r\n\r\n console.log('!');\r\n vertices.forEach(v => {\r\n console.log(v);\r\n });\r\n}\r\n\r\nsolve();\r\n"}], "src_uid": "5dbafdd7c4e93b2c01122fa80ef42f0e"} {"nl": {"description": "You are given a positive integer $$$n$$$. Let's call some positive integer $$$a$$$ without leading zeroes palindromic if it remains the same after reversing the order of its digits. Find the number of distinct ways to express $$$n$$$ as a sum of positive palindromic integers. Two ways are considered different if the frequency of at least one palindromic integer is different in them. For example, $$$5=4+1$$$ and $$$5=3+1+1$$$ are considered different but $$$5=3+1+1$$$ and $$$5=1+3+1$$$ are considered the same. Formally, you need to find the number of distinct multisets of positive palindromic integers the sum of which is equal to $$$n$$$.Since the answer can be quite large, print it modulo $$$10^9+7$$$.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1\\leq t\\leq 10^4$$$) denoting the number of testcases. Each testcase contains a single line of input containing a single integer $$$n$$$ ($$$1\\leq n\\leq 4\\cdot 10^4$$$) — the required sum of palindromic integers.", "output_spec": "For each testcase, print a single integer denoting the required answer modulo $$$10^9+7$$$.", "sample_inputs": ["2\n5\n12"], "sample_outputs": ["7\n74"], "notes": "NoteFor the first testcase, there are $$$7$$$ ways to partition $$$5$$$ as a sum of positive palindromic integers: $$$5=1+1+1+1+1$$$ $$$5=1+1+1+2$$$ $$$5=1+2+2$$$ $$$5=1+1+3$$$ $$$5=2+3$$$ $$$5=1+4$$$ $$$5=5$$$ For the second testcase, there are total $$$77$$$ ways to partition $$$12$$$ as a sum of positive integers but among them, the partitions $$$12=2+10$$$, $$$12=1+1+10$$$ and $$$12=12$$$ are not valid partitions of $$$12$$$ as a sum of positive palindromic integers because $$$10$$$ and $$$12$$$ are not palindromic. So, there are $$$74$$$ ways to partition $$$12$$$ as a sum of positive palindromic integers."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nconst f = [];\r\nconst N = 4 * 10 ** 4 + 10;\r\nfor (let i = 1; i < N; i++) {\r\n if (i.toString() === i.toString().split('').reverse().join('')) f.push(i);\r\n}\r\nconst m = f.length;\r\nconst dp = new Array(N).fill(0);\r\nconst MOD = 10 ** 9 + 7;\r\nconst mod = num => num >= MOD ? (num % MOD + MOD) % MOD : num;\r\ndp[0] = 1;\r\nfor (let i = 0; i < m; i++) {\r\n for (let j = 0; j < N; j++) {\r\n const k = f[i] + j;\r\n dp[k] = mod(dp[k] + dp[j]);\r\n }\r\n}\r\nfunction solve(n) {\r\n return dp[n];\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n res[i] = solve(n);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst mxN = 40001;\r\nconst MOD = 1e9+7;\r\n\r\nconst f = Array(mxN).fill(0); f[0] = 1;\r\n\r\nfunction reverse (n) {\r\n\tn = String(n);\r\n\tn = n.split('');\r\n\tn = n.reverse();\r\n\tn = n.join('');\r\n\tn = Number(n);\r\n\treturn n;\r\n}\r\n\r\nfunction compute () {\r\n\tfor (let p = 1; p < mxN; p++) {\r\n\t\tif (p != reverse(p)) continue;\r\n\t\tfor (let i = p; i < mxN; i++) {\r\n\t\t\tf[i] += f[i-p];\r\n\t\t\tf[i] %= MOD;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction main () {\r\n\tcompute();\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconsole.log(f[n]);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const n = +lines[l++]\r\n output[i] = solve(n)\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nconst CACHE = pre(4e4)\r\nfunction pre(n) {\r\n const ps = []\r\n for (let i = 1; i <= n; i++) {\r\n const a = String(i)\r\n let ok = true\r\n for (let j = 0; j < a.length; j++) {\r\n if (a[j] !== a[a.length - 1 - j]) {\r\n ok = false\r\n break\r\n }\r\n }\r\n if (ok) ps.push(i)\r\n }\r\n //\r\n const dp = []\r\n for (let j = 0; j < ps.length; j++) {\r\n if (!j) {\r\n dp[j] = Array(n + 1).fill(1)\r\n continue\r\n }\r\n dp[j] = dp[j - 1].slice()\r\n for (let i = ps[j]; i <= n; i++) {\r\n const k = Math.floor(i / ps[j])\r\n dp[j][i] = dp[j][i - ps[j]]\r\n dp[j][i] = add(dp[j][i], dp[j - 1][i] || 1)\r\n // for (let k = 0; k * ps[j] <= i; k++) {\r\n // // dp[j][i] = dp[j - 1][i] + dp[j - 1][i - ps[j] * k]\r\n // dp[j][i] = add(dp[j][i], dp[j - 1][i - ps[j] * k] || 1)\r\n // }\r\n }\r\n }\r\n// console.log(dp)\r\n // for (let i = 1; i <= n; i++) {\r\n // dp[i] = []\r\n // let prev\r\n // for (let j = 0; j < ps.length; j++) {\r\n // if (ps[j] > i) {\r\n // dp[i][j] = prev\r\n // continue\r\n // }\r\n\r\n // let now = 0\r\n // for (let k = 0; k <= j; k++) {\r\n // const max = ps[k]\r\n // now = add(now, i === max ? 1 : dp[i - max][k])\r\n // }\r\n // dp[i][j] = now\r\n // prev = now\r\n // }\r\n // }\r\n return dp[ps.length - 1]\r\n}\r\nfunction solve(n) {\r\n return CACHE[n]\r\n}\r\nfunction add(a, b) {\r\n return (a + b) % (1e9 + 7)\r\n}\r\n"}], "negative_code": [{"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst mxN = 40001;\r\nconst mxM = 500;\r\n\r\nconst pal = [];\r\nconst f = Array.from(Array(mxN), _ => Array(mxM).fill(0));\r\n\r\nfunction reverse (n) {\r\n\tn = String(n);\r\n\tn = n.split('');\r\n\tn = n.reverse();\r\n\tn = n.join('');\r\n\tn = Number(n);\r\n\treturn n;\r\n}\r\n\r\nfunction compute () {\r\n\tfor (let i = 1; i < mxN; i++) {\r\n\t\tif (i == reverse(i)) {\r\n\t\t\tpal.push(i);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (let i = 0; i < pal.length; i++) { \r\n\t\tf[1][i] = 1, f[0][i] = 1;\r\n\t}\r\n\r\n\tfor (let i = 2; i < mxN; i++) {\r\n\t\tfor (j = 0; j < pal.length; j++) {\r\n\t\t\tf[i][j] = j-1 >= 0 ? f[i][j-1] : 0;\r\n\t\t\tf[i][j] += i-pal[j] >= 0 ? f[i-pal[j]][j] : 0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction main () {\r\n\tcompute();\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconsole.log(f[n][pal.length-1]);\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "529d4ab0bdbb29d8b7f3d3eed19eca63"} {"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 ≤ n ≤ 10 000, 1 ≤ k ≤ 100).", "output_spec": "On the first line print a single integer — 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, 2, 3, 4} isn't a valid set of rank 1 since ."}, "positive_code": [{"source_code": "var nums = readline().split(' ');\nvar n = parseInt(nums[0]);\nvar k = parseInt(nums[1]);\n\nprint((n*6-1)*k);\nvar x =0;\nfor(var i=1;i<=n;i++)\n{\n print(((x+1)*k)+' '+((x+3)*k)+' '+((x+5)*k)+' '+((x+2)*k));\n\tx+=6;\n}"}], "negative_code": [], "src_uid": "5e7b4d1e11628152e33d3e18e30f4530"} {"nl": {"description": "Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon $$$P$$$ which is defined by coordinates of its vertices. Define $$$P(x,y)$$$ as a polygon obtained by translating $$$P$$$ by vector $$$\\overrightarrow {(x,y)}$$$. The picture below depicts an example of the translation:Define $$$T$$$ as a set of points which is the union of all $$$P(x,y)$$$ such that the origin $$$(0,0)$$$ lies in $$$P(x,y)$$$ (both strictly inside and on the boundary). There is also an equivalent definition: a point $$$(x,y)$$$ lies in $$$T$$$ only if there are two points $$$A,B$$$ in $$$P$$$ such that $$$\\overrightarrow {AB} = \\overrightarrow {(x,y)}$$$. One can prove $$$T$$$ is a polygon too. For example, if $$$P$$$ is a regular triangle then $$$T$$$ is a regular hexagon. At the picture below $$$P$$$ is drawn in black and some $$$P(x,y)$$$ which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if $$$P$$$ and $$$T$$$ are similar. Your task is to check whether the polygons $$$P$$$ and $$$T$$$ are similar.", "input_spec": "The first line of input will contain a single integer $$$n$$$ ($$$3 \\le n \\le 10^5$$$) — the number of points. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i, y_i$$$ ($$$|x_i|, |y_i| \\le 10^9$$$), denoting the coordinates of the $$$i$$$-th vertex. It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.", "output_spec": "Output \"YES\" in a separate line, if $$$P$$$ and $$$T$$$ are similar. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).", "sample_inputs": ["4\n1 0\n4 1\n3 4\n0 3", "3\n100 86\n50 0\n150 0", "8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3"], "sample_outputs": ["YES", "nO", "YES"], "notes": "NoteThe following image shows the first sample: both $$$P$$$ and $$$T$$$ are squares. The second sample was shown in the statements."}, "positive_code": [{"source_code": "'use strict'\n\nconst problem = (n, v) => {\n if (n % 2) return 'NO';\n v.push(v[0]);\n for (let i = 0; i < n/2; i++) {\n if (Math.abs(v[i][0] - v[i+1][0]) !== Math.abs(v[i + n/2][0] - v[i+1 + n/2][0])) return 'NO';\n if (Math.abs(v[i][1] - v[i+1][1]) !== Math.abs(v[i + n/2][1] - v[i+1 + n/2][1])) return 'NO';\n }\n return 'YES';\n}\nconst n = +readline();\nconst v = Array.from({ length: n }, () => readline().split(' ').map(i => +i))\nprint(problem(n, v))\n"}], "negative_code": [], "src_uid": "424f37abd0e19208e6b0cb8b670e7187"} {"nl": {"description": "The city where Mocha lives in is called Zhijiang. There are $$$n+1$$$ villages and $$$2n-1$$$ directed roads in this city. There are two kinds of roads: $$$n-1$$$ roads are from village $$$i$$$ to village $$$i+1$$$, for all $$$1\\leq i \\leq n-1$$$. $$$n$$$ roads can be described by a sequence $$$a_1,\\ldots,a_n$$$. If $$$a_i=0$$$, the $$$i$$$-th of these roads goes from village $$$i$$$ to village $$$n+1$$$, otherwise it goes from village $$$n+1$$$ to village $$$i$$$, for all $$$1\\leq i\\leq n$$$. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village exactly once. They can start and finish at any villages. Can you help them to draw up a plan? ", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 20$$$) — 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 10^4$$$) — indicates that the number of villages is $$$n+1$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 1$$$). If $$$a_i=0$$$, it means that there is a road from village $$$i$$$ to village $$$n+1$$$. If $$$a_i=1$$$, it means that there is a road from village $$$n+1$$$ to village $$$i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For each test case, print a line with $$$n+1$$$ integers, where the $$$i$$$-th number is the $$$i$$$-th village they will go through. If the answer doesn't exist, print $$$-1$$$. If there are multiple correct answers, you can print any one of them.", "sample_inputs": ["2\n3\n0 1 0\n3\n1 1 0"], "sample_outputs": ["1 4 2 3 \n4 1 2 3"], "notes": "NoteIn the first test case, the city looks like the following graph:So all possible answers are $$$(1 \\to 4 \\to 2 \\to 3)$$$, $$$(1 \\to 2 \\to 3 \\to 4)$$$.In the second test case, the city looks like the following graph:So all possible answers are $$$(4 \\to 1 \\to 2 \\to 3)$$$, $$$(1 \\to 2 \\to 3 \\to 4)$$$, $$$(3 \\to 4 \\to 1 \\to 2)$$$, $$$(2 \\to 3 \\to 4 \\to 1)$$$."}, "positive_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\r\n\t\tlet ans = Array.from(Array(n), (_, i) => i + 1);\r\n\t\tif (a[0]) {\r\n\t\t\tans.unshift(n + 1);\r\n\t\t} else if (!a[n - 1]) {\r\n\t\t\tans.push(n + 1);\r\n\t\t} else if (a.join('').includes('01')) {\r\n\t\t\tfor (let i = 0; i < n - 1; ++i) {\r\n\t\t\t\tif (!a[i] && a[i + 1]) {\r\n\t\t\t\t\tans.splice(i + 1, 0, n + 1);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tans = false;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rn();\r\n\t\tlet a = rna();\r\n\r\n\t\tlet ans = Array.from(Array(n), (_, i) => i+1);\r\n\t\tif (a[n-1] == 0) {\r\n\t\t\tans.push(n+1);\r\n\t\t} else if (a[0] == 1) {\r\n\t\t\tans.unshift(n+1);\r\n\t\t} else if (a.join('').includes('01')) {\r\n\t\t\tfor (let i = 0; i < n-1; i++) {\r\n\t\t\t\tif (a[i] == 0 && a[i+1] == 1) {\r\n\t\t\t\t\tans.splice(i+1, 0, n+1);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tans = false;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nlet arr = [];\r\nconst precompute = () => {\r\n arr.push(1n);\r\n let k = 2n;\r\n for (let i = 1; i < 51; i++, k = k * 2n) arr[i] = k;\r\n};\r\nconst solve = () => {\r\n precompute();\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let dir = new Array(n).fill(0).map((cur, ind) => ind + 1);\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (arr[i] === 0) break;\r\n else dir.pop();\r\n }\r\n if (dir.length) {\r\n let s = dir[dir.length - 1];\r\n s++;\r\n dir.push(n + 1);\r\n while (s <= n) dir.push(s++);\r\n console.log(dir.join(\" \"));\r\n } else {\r\n let res = `${n + 1} `,\r\n i = 1;\r\n while (i <= n) res += `${i++} `;\r\n console.log(res);\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict'\r\nObject.defineProperty(exports, '__esModule', { value: !0 })\r\nvar os = require('os')\r\nconst stdin = process.stdin,\r\n stdout = process.stdout,\r\n integerRegex = /-?\\d+/g,\r\n decimalRegex = /-?\\d+(?:\\.\\d+)?/g\r\nclass InputAndOutput {\r\n lineIndex = 0\r\n lines = []\r\n dried() {\r\n return this.lineIndex >= this.lines.length\r\n }\r\n readLine() {\r\n const e = this.lines[this.lineIndex]\r\n return (this.lineIndex += 1), e\r\n }\r\n readLineAsNumber() {\r\n return Number(this.readLine())\r\n }\r\n readIntegersOfLine() {\r\n const e = this.readLine().match(integerRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n readNumsOfLine() {\r\n const e = this.readLine().match(decimalRegex)\r\n return null == e ? [] : e.map(e => Number(e))\r\n }\r\n print(e) {\r\n stdout.write(e)\r\n }\r\n async init() {\r\n const e = await this.readLines()\r\n this.lines = e\r\n }\r\n readLines() {\r\n const e = []\r\n return new Promise(n => {\r\n stdin.on('data', n => e.push(n)),\r\n stdin.on('end', function () {\r\n const t = e.join('').split(os.EOL)\r\n n(t)\r\n })\r\n })\r\n }\r\n}\r\nasync function __main__(e) {\r\n const n = new InputAndOutput()\r\n await n.init(), e(n)\r\n}\r\nconst nums = new Array(10010).fill(0).map((e, n) => n)\r\nfunction solve(e, n) {\r\n if (0 === n[e - 1]) return nums.slice(1, e + 2)\r\n if (1 === n[0]) return [e + 1].concat(nums.slice(1, e + 1))\r\n let t = 0\r\n for (let s = e - 1; t < s && (0 !== n[t] || 1 !== n[t + 1]); ++t);\r\n if (t === e - 1) return -1\r\n const s = nums.slice(1, t + 2)\r\n s.push(e + 1)\r\n for (let n = t + 1; n < e; ++n) s.push(n + 1)\r\n return s\r\n}\r\n__main__(function (e) {\r\n const n = e.readLineAsNumber()\r\n for (let t = 1; t <= n; ++t) {\r\n const n = solve(e.readLineAsNumber(), e.readIntegersOfLine())\r\n ;-1 === n ? e.print(n + '\\n') : e.print(n.join(' ') + '\\n')\r\n }\r\n})\r\n"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rn();\r\n\t\tlet a = rna();\r\n\r\n\t\tlet ans = Array.from(Array(n), (_, i) => i+1);\r\n\t\tif (a[n-1] == 0) {\r\n\t\t\tans.push(n+1);\r\n\t\t} else if (a[0] == 1) {\r\n\t\t\tans.unshift(n+1);\r\n\t\t} else if (a.join('').includes('01')) {\r\n\t\t\tfor (let i = 0; i < n-1; i++) {\r\n\t\t\t\tif (a[i] == 0 && a[i+1] == 1) {\r\n\t\t\t\t\ta.splice(i+1, 0, n+1);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tans = false;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet n = rn();\r\n\t\tlet a = rna();\r\n\r\n\t\tlet ans = Array.from(Array(n), (_, i) => i+1);\r\n\t\tif (a[n-1] == 0) {\r\n\t\t\tans.push(n+1);\r\n\t\t} else if (a[0] == 1) {\r\n\t\t\tans.unshift(n+1);\r\n\t\t} else if (a.join('').includes('01')) {\r\n\t\t\tfor (let i = 1; i < n-1; i++) {\r\n\t\t\t\tif (a[i] == 0 && a[i+1] == 1) {\r\n\t\t\t\t\ta.splice(i+1, 0, n+1);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tans = false;\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst readLine = () => dataitr.next().value.trim();\r\nfunction rl () {\r\n\tlet ans = readLine().split(' ');\r\n\tif (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));\r\n\treturn ans.length == 1 ? ans[0] : ans;\r\n}\r\n\r\nconst RANGE = (s, e) => Array.from(Array(e - s + 1), (_, index) => index + s);\r\n\r\nfunction main () {\r\n\tlet t = rl();\r\n\twhile (t--) {\r\n\t\tlet n = rl();\r\n\t\tlet a = rl();\r\n\r\n\t\tlet ans = [], i = 0;\r\n\t\twhile (i < n && a[i] == 0) i++;\r\n\t\tif (i != n ) { \r\n\t\t\tans = [...RANGE(1, i), n + 1, ...RANGE(i + 1, n)];\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.length == 0 ? -1 : ans.join(' '))\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst readLine = () => dataitr.next().value.trim();\r\nfunction rl () {\r\n\tlet ans = readLine().split(' ');\r\n\tif (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));\r\n\treturn ans.length == 1 ? ans[0] : ans;\r\n}\r\n\r\nconst RANGE = (s, e) => Array.from(Array(e - s + 1), (_, index) => index + s);\r\n\r\nfunction main () {\r\n\tlet t = rl();\r\n\twhile (t--) {\r\n\t\tlet n = rl();\r\n\t\tlet a = rl();\r\n\r\n\t\tlet ans = [], i = 0;\r\n\t\twhile (i < n && a[i] == 0) i++;\r\n\t\tif (i != n ) { \r\n\t\t\tans = [...RANGE(1, i), n + 1, ...RANGE(i + 1, n)];\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.length == 0 ? -1 : ans.join(' '))\r\n\t}\r\n}\r\n\r\n"}], "src_uid": "3f9525d74f4934eb9dca1b16c53662bf"} {"nl": {"description": "It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.According to the borscht recipe it consists of n ingredients that have to be mixed in proportion litres (thus, there should be a1 ·x, ..., an ·x litres of corresponding ingredients mixed for some non-negative x). In the kitchen Volodya found out that he has b1, ..., bn litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a V litres volume pan (which means the amount of soup cooked can be between 0 and V litres). What is the volume of borscht Volodya will cook ultimately?", "input_spec": "The first line of the input contains two space-separated integers n and V (1 ≤ n ≤ 20, 1 ≤ V ≤ 10000). The next line contains n space-separated integers ai (1 ≤ ai ≤ 100). Finally, the last line contains n space-separated integers bi (0 ≤ bi ≤ 100).", "output_spec": "Your program should output just one real number — the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10 - 4.", "sample_inputs": ["1 100\n1\n40", "2 100\n1 1\n25 30", "2 100\n1 1\n60 60"], "sample_outputs": ["40.0", "50.0", "100.0"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nlet N = lll[0]\nlet V = lll[1]\nlet as = readline().split(' ').map(v => parseInt(v))\nlet bs = readline().split(' ').map(v => parseInt(v))\n\nlet p = as.reduce((r, v) => r + v, 0)\nlet ds = bs.map((b, i) => b / as[i] * p)\nlet s = ds.reduce((r, d) => Math.min(r, d), Infinity)\nprint(Math.min(s, V))"}], "negative_code": [], "src_uid": "351d8874a10f84d157a7b2e1eb64e2a1"} {"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 — $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ — 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": "const { createInterface } = require('readline');\nconst lines = []\n\nconst numbers = [4, 8, 15, 16, 23, 42];\n\nconst map = {};\nfor (let i = 0; i < 6; i ++) {\n for (let j = i +1; j < 6; j++) {\n map[numbers[i] * numbers[j]] = [numbers[i], numbers[j]];\n }\n}\n\nconst found = [];\n\nconst nums = [];\n\nfunction solve() {\n if (nums[0][0] === nums[1][0]) {\n found.push(nums[0][1], nums[0][0], nums[1][1])\n } else if (nums[0][0] === nums[1][1]) {\n found.push(nums[0][1], nums[0][0], nums[1][0])\n } else if (nums[0][1] === nums[1][0]) {\n found.push(nums[0][0], nums[0][1], nums[1][1])\n } else if (nums[0][1] === nums[1][1]) {\n found.push(nums[0][0], nums[0][1], nums[1][0])\n }\n numbers.forEach((num) => {\n if (!found.includes(num)) {\n found.push(num);\n }\n })\n\n console.log(`! ${found.join(' ')}`)\n}\n\nconsole.log('? 1 1');\nlet iter = 1;\n\n( function processLineByLine() {\n const rl = createInterface({\n input: process.stdin\n });\n\n rl.on('line', (line) => {\n switch (iter) {\n case 1:\n found.push(parseInt(Math.sqrt(+line)));\n console.log('? 2 2');\n iter++;\n break;\n case 2:\n found.push(parseInt(Math.sqrt(+line)));\n console.log('? 3 4');\n iter++;\n break;\n case 3:\n nums.push(map[line])\n console.log('? 4 5');\n iter++;\n break; \n case 4:\n nums.push(map[line])\n iter++;\n solve();\n break;\n case 5:\n process.exit(0);\n }\n });\n\n\n})();\n"}, {"source_code": "\n(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n\n var arr = [4 , 8, 15, 16, 23, 42];\n var muls = [];\n\n for(var i = 2; i < 6; i++) {\n print('? 1 ' + i ); \n muls.push(read.number());\n }\n \n var first;\n for(var i = 0; i < 6; i++) {\n var ch = true;\n for(var j = 0; j < 4; j++) {\n if(arr.indexOf(muls[j] / arr[i]) === -1) {\n ch = false;\n break;\n }\n }\n if(ch) {\n first = arr[i];\n break;\n }\n }\n\n var res = [first];\n muls.forEach(v => res.push(v/first));\n arr.forEach(v => {\n if(res.indexOf(v) === -1) {\n res.push(v);\n }\n });\n\n print('! ' + res.join(' '));\n\n}());\n"}], "negative_code": [{"source_code": "\n(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n\n var arr = [4 , 8, 15, 16, 23, 42];\n var muls = [];\n\n for(var i = 2; i < 6; i++) {\n print('? 1 ' + i ); \n muls.push(read.number());\n }\n\n var first;\n for(var i = 0; i < 6; i++) {\n var ch = true;\n for(var j = 0; j < 4; j++) {\n if(arr.indexOf(muls[j] / arr[i]) === -1) {\n ch = false;\n break;\n }\n }\n if(ch) {\n first = arr[i];\n break;\n }\n }\n\n var res = [first];\n muls.forEach(v => res.push(v/first))\n\n arr.forEach(v => {\n if(res.indexof(v) === -1) {\n res.push(v);\n }\n });\n\n print(res.join(' '));\n\n}());"}], "src_uid": "c0f79d7ebcecc4eb7d07c372ba9be802"} {"nl": {"description": "You are given a positive integer $$$n$$$. You have to find $$$4$$$ positive integers $$$a, b, c, d$$$ such that $$$a + b + c + d = n$$$, and $$$\\gcd(a, b) = \\operatorname{lcm}(c, d)$$$.If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem $$$\\gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$, and $$$\\operatorname{lcm}(c, d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with integer $$$n$$$ ($$$4 \\le n \\le 10^9$$$) — the sum of $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$.", "output_spec": "For each test case output $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ such that $$$a + b + c + d = n$$$ and $$$\\gcd(a, b) = \\operatorname{lcm}(c, d)$$$.", "sample_inputs": ["5\n4\n7\n8\n9\n10"], "sample_outputs": ["1 1 1 1\n2 2 2 1\n2 2 2 2\n2 4 2 1\n3 5 1 1"], "notes": "NoteIn the first test case $$$\\gcd(1, 1) = \\operatorname{lcm}(1, 1) = 1$$$, $$$1 + 1 + 1 + 1 = 4$$$.In the second test case $$$\\gcd(2, 2) = \\operatorname{lcm}(2, 1) = 2$$$, $$$2 + 2 + 2 + 1 = 7$$$.In the third test case $$$\\gcd(2, 2) = \\operatorname{lcm}(2, 2) = 2$$$, $$$2 + 2 + 2 + 2 = 8$$$.In the fourth test case $$$\\gcd(2, 4) = \\operatorname{lcm}(2, 1) = 2$$$, $$$2 + 4 + 2 + 1 = 9$$$.In the fifth test case $$$\\gcd(3, 5) = \\operatorname{lcm}(1, 1) = 1$$$, $$$3 + 5 + 1 + 1 = 10$$$. "}, "positive_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n; j++){\n e = lines[j]- 3\n console.log(e+ ' ' + 1 + ' ' + 1 + ' '+ 1)\n }\n}); "}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\n\r\nvoid (function main() {\r\n const t = Number(inputs[0])\r\n for (let _ = 0; _ < t; _++) {\r\n const n = inputs[_ + 1]\r\n console.log([1, n - 3, 1, 1].join(' '))\r\n }\r\n})()\r\n"}, {"source_code": "let buf='';\r\n\r\nprocess.stdin.on('readable', function(){\r\n let chunk=process.stdin.read();\r\n if(chunk) buf+=chunk.toString();\r\n})\r\n\r\nprocess.stdin.on('end', function(){\r\n const {EOL}=require('os');\r\n let line=buf.split(EOL);\r\n let t=parseInt(line[0]);\r\n for(let _=1;_<=t;_++)\r\n {\r\n let n=parseInt(line[_]);\r\n let ans='';\r\n ans+=n-3+' ';\r\n ans+=1+' ';\r\n ans+=1+' ';\r\n ans+=1+' ';\r\n console.log(ans);\r\n }\r\n})"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n output(`${n - 3} 1 1 1`);\r\n }\r\n}\r\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n\tvar t = lines[0];\n\tvar n = 0;\n\tfor(i = 1; i <= t; i++){\n var s = lines[i];\n console.log(1, s - 3, 1, 1);\n\t}\n});\n\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n console.log(solve());\r\n }\r\n}\r\nfunction solve() {\r\n let n = parseInt(readLine());\r\n return `${n - 3} 1 1 1`;\r\n}\r\n"}, {"source_code": "'use strict';\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst l = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\n \nconst ra = ()=>readline().split(' ').map(a=>+a)\n \nconst MOD = 1e9+7;\n\nclass SegmTree {\n\n}\n \nconst calc = (n)=>{\n let ans = [1, n-3, 1, 1];\n return ans.join(' ');\n};\n \nfunction main() {\n let T = +readline()\n while (T--){\n let [n] = ra();\n l('ans')\n print(calc(n));\n }\n}\n \nE.calc = calc;"}, {"source_code": "var tests = readline();\r\n\r\nwhile(tests--) {\r\n var x = readline();\r\n \r\n print(x-3 + ' 1 1 1');\r\n}"}, {"source_code": "var total = +readline();\nwhile (total--) {\n var i = +readline();\n print(i - 3 + \" 1 1 1\");\n}"}], "negative_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n; j++){\n e = lines[j]- 3\n console.log(1+ ' ' + 1 + ' ' + 1 + ' '+ e)\n }\n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n for(j = 1; j <= n; j++){\n e = lines[j]- 3\n console.log(1+ ' ' + 1 + ' ' + 1 + ' '+ e)\n }\n}); \n "}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\n\r\nvoid (function main() {\r\n const t = Number(inputs[0])\r\n for (let _ = 0; _ < t; _++) {\r\n const n = inputs[_ + 1]\r\n console.log([1, 1, 1, n - 3].join(' '))\r\n }\r\n})()\r\n"}], "src_uid": "f9f803c6850da1838d62a0cf85bb13f2"} {"nl": {"description": "The Dogeforces company has $$$k$$$ employees. Each employee, except for lower-level employees, has at least $$$2$$$ subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 500$$$) — the number of lower-level employees. This is followed by $$$n$$$ lines, where $$$i$$$-th line contains $$$n$$$ integers $$$a_{i,1}, a_{i,2}, \\dots, a_{i,n}$$$ ($$$1 \\le a_{i,j} \\le 5000$$$) — salary of the common supervisor of employees with numbers $$$i$$$ and $$$j$$$. It is guaranteed that $$$a_{i,j} = a_{j,i}$$$. Note that $$$a_{i,i}$$$ is equal to the salary of the $$$i$$$-th employee.", "output_spec": "In the first line, print a single integer $$$k$$$ — the number of employees in the company. In the second line, print $$$k$$$ integers $$$c_1, c_2, \\dots, c_k$$$, where $$$c_i$$$ is the salary of the employee with the number $$$i$$$. In the third line, print a single integer $$$r$$$ — the number of the employee who is the head of the company. In the following $$$k-1$$$ lines, print two integers $$$v$$$ and $$$u$$$ ($$$1 \\le v, u \\le k$$$) — the number of the employee and his direct supervisor. Note that the lower-level employees have numbers from $$$1$$$ to $$$n$$$, and for the rest of the employees, you have to assign numbers from $$$n+1$$$ to $$$k$$$. If there are several correct company structures, you can print any of them.", "sample_inputs": ["3\n2 5 7\n5 1 7\n7 7 4"], "sample_outputs": ["5\n2 1 4 7 5 \n4\n1 5\n2 5\n5 4\n3 4"], "notes": "NoteOne of the possible structures in the first example: "}, "positive_code": [{"source_code": "let n = 0;\nlet a = [];\nlet employees = [];\nlet salaries = [];\nlet supervisors = [];\n\nconst traceRoot = ids => {\n if (ids.length === 1) return ids[0];\n\n let rootSalary = 0;\n for (const idu of ids)\n for (const idv of ids) {\n rootSalary = Math.max(rootSalary, a[idu][idv]);\n }\n\n let groups = [];\n for (let id of ids) {\n let found = false;\n for (let group of groups) {\n if (a[group[0]][id] < rootSalary) {\n found = true;\n group.push(id);\n break;\n }\n }\n if (!found) groups.push([id]);\n }\n const rootEmployee = employees.length;\n employees.push(rootEmployee);\n salaries.push(rootSalary);\n\n for (let group of groups) supervisors.push([traceRoot(group), rootEmployee]);\n\n return rootEmployee;\n};\n\nconst main = () => {\n n = readInt();\n for (let i = 0; i < n; i++) {\n const r = readListInt();\n a.push(r);\n }\n for (let i = 0; i < n; i++) {\n salaries.push(a[i][i]);\n employees.push(i);\n }\n\n const ceo = traceRoot(employees);\n\n console.log(employees.length);\n console.log(salaries.join(\" \"));\n console.log(ceo + 1);\n for (const supervisor of supervisors) {\n console.log(`${supervisor[0] + 1} ${supervisor[1] + 1}`);\n }\n};\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nprocess.stdin.on(\"data\", inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", () => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map(string => string.trim());\n main();\n});\n\nconst readLine = () => {\n return inputString[currentLine++];\n};\n\nconst readInt = () => {\n return parseInt(inputString[currentLine++]);\n};\n\nconst readListInt = () => {\n return inputString[currentLine++].split(\" \").map(s => parseInt(s));\n};\n"}], "negative_code": [], "src_uid": "ff8219b0e4fd699b1898500664087e90"} {"nl": {"description": "This is an easier version of the problem with smaller constraints.Korney Korneevich dag up an array $$$a$$$ of length $$$n$$$. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers $$$x \\ge 0$$$ such that there exists an increasing subsequence of the array $$$a$$$, in which the bitwise XOR of numbers is equal to $$$x$$$.It didn't take a long time for Korney Korneevich to find all such $$$x$$$, and he wants to check his result. That's why he asked you to solve this problem!A sequence $$$s$$$ is a subsequence of a sequence $$$b$$$ if $$$s$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.A sequence $$$s_1, s_2, \\ldots , s_m$$$ is called increasing if $$$s_1 < s_2 < \\ldots < s_m$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 500$$$) — the elements of the array $$$a$$$.", "output_spec": "In the first line print a single integer $$$k$$$ — the number of found $$$x$$$ values. In the second line print $$$k$$$ integers in increasing order $$$x_1, x_2, \\ldots x_k$$$ ($$$0 \\le x_1 < \\ldots < x_k$$$) — found $$$x$$$ values.", "sample_inputs": ["4\n4 2 2 4", "8\n1 0 1 7 12 5 3 2"], "sample_outputs": ["4\n0 2 4 6", "12\n0 1 2 3 4 5 6 7 10 11 12 13"], "notes": "NoteIn the first test case: To get value $$$x = 0$$$ it is possible to choose and empty subsequence To get value $$$x = 2$$$ it is possible to choose a subsequence $$$[2]$$$ To get value $$$x = 4$$$ it is possible to choose a subsequence $$$[4]$$$ To get value $$$x = 6$$$ it is possible to choose a subsequence $$$[2, 4]$$$ "}, "positive_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const ans = { 0: -1 }\n for (let i = 0; i < arr.length; i++) {\n const x = arr[i]\n for (let k = 0; k <= 512; k++) {\n if ((k in ans) && ans[k] < x) {\n ans[k ^ x] = Math.min(ans[k ^ x] || Infinity, x)\n }\n }\n }\n // console.log(ans)\n const ks = Object.keys(ans)\n return ks.length + '\\n' + ks.sort((a, b) => +a - +b).join(' ')\n}\n"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const ans = { 0: -1 }\n for (let i = 0; i < arr.length; i++) {\n const x = arr[i]\n for (let k = 0; k <= 500; k++) {\n if ((k in ans) && ans[k] < x) {\n ans[k ^ x] = Math.min(ans[k ^ x] || Infinity, x)\n }\n }\n }\n // console.log(ans)\n const ks = Object.keys(ans)\n return ks.length + '\\n' + ks.sort((a, b) => +a - +b).join(' ')\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const ans = { 0: 1 }\n let cur = { 0: 1 }\n for (let i = 0; i < arr.length; i++) {\n const x = arr[i]\n const next = {}\n for (let k = 0; k <= x; k++) {\n if (cur[k]) {\n next[k] = 1\n next[k ^ x] = 1\n ans[k] = 1\n ans[k ^ x] = 1\n }\n }\n cur = next\n // console.log(ans)\n }\n const ks = Object.keys(ans)\n return ks.length + '\\n' + ks.sort((a, b) => +a - +b).join(' ')\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const set = {}\n set[0] = 1\n const xor = []\n for (let i = 0; i < arr.length; i++) {\n xor[i] = [arr[i]]\n set[arr[i]] = 1\n for (let j = 0; j < i; j++) {\n if (arr[i] > arr[j]) {\n for (let k = 0; k < xor[j].length; k++) {\n const cur = arr[i] ^ xor[j][k]\n xor[i].push(cur)\n set[cur] = 1\n }\n }\n }\n }\n // console.log(xor)\n return Object.keys(set).sort((a, b) => +a - +b).join(' ')\n}\n"}], "src_uid": "6057052f1eb001da04e3415001cce228"} {"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 ≤ n ≤ 150) — 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 «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.", "output_spec": "Print a single integer — the final value of x.", "sample_inputs": ["1\n++X", "2\nX++\n--X"], "sample_outputs": ["1", "0"], "notes": null}, "positive_code": [{"source_code": " process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n \n let stdinInput = '';\n \n process.stdin.on('data', input => {\n stdinInput += input;\n })\n \n process.stdin.on('end', () => {\n main(stdinInput);\n })\n \n function main(data) {\n data = data.split('\\n');\n const n = data.shift();\n let x = 0;\n for (let i = 0; i < n; i += 1) {\n if (data[i].match(/-/)) x -= 1;\n else x += 1;\n } \n process.stdout.write(x + '');\n }"}, {"source_code": "n = readline();\nvar meghdar = 0;\nwhile(n--)\n{\n \t \n\ts = readline();\n\tvar k = s.indexOf(\"+\");\n\tif(k == -1){meghdar--}\n\telse{meghdar++}\n\t\n}\nprint(meghdar)"}, {"source_code": "const main = () => {\n const N = Number(readline());\n\n var result = 0;\n\n for (var i = 0; i < N; i++) {\n if (readline().indexOf(\"-\") >= 0) {\n result--;\n } else {\n result++;\n }\n }\n\n return result;\n};\n\nprint(main());"}, {"source_code": "function main() {\n const res = stdin.slice(1).reduce((s,x)=>{\n return s = (x[1] === \"+\") ? s+1 : s-1;\n },0)\n console.log(res)\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({input: process.stdin});\nvar stdin = [];\nrl.on('line', function (line) {\n stdin.push(line);});\nrl.on('close', main);\n"}, {"source_code": "input=readline();\ninput=input.split(' ').map(e=>parseInt(e));\nn=input[0]\nans=0;\nwhile(n--){\n tmp=readline();\n ans+=(tmp.indexOf('+')===-1)?-1:1;\n}\nprint(ans)"}, {"source_code": "var operations = readline();\nvar value = 0;\nfor(var i = 0; i < operations; i++) {\n if(readline().indexOf('+') !== -1) {\n value++;\n } else {\n value--;\n }\n}\nprint(value);"}, {"source_code": "const n = Number(readline());\nvar x = 0;\nvar s ;\nfor(var i = 0; i {\n if (input == \"\") {\n cs.close();\n }\n lines[line_number] = input.split(\" \")\n line_number += 1;\n}).on(\"close\", () => {\n main();\n process.exit();\n});\n\nfunction isOp(str) {\n return str.length === 1 && str.match(/[<=>]/);\n}\nfunction isChr(str) {\n return str.length === 1 && str.match(/[a-z]/i);\n}\nfunction isInt(str) {\n return str.length === 1 && !isNaN(str);\n}\n\nfunction print(str) {\n console.log(str);\n}\n\nfunction predict(test) {\n let op = \"\";\n let ops = [];\n let opVariables = [];\n let limits = [];\n for (let t of test) {\n // console.log(t);\n for (let i = 0; i < t.length; i++) {\n if (isOp(t[i])) {\n op = t[i];\n if (isOp(t[i + 1])) {\n op += t[i + 1];\n i += 1;\n }\n ops.push(op);\n op = \"\";\n } else if (isChr(t[i])) {\n // console.log(t[i])\n op = t[i];\n for (var j = i + 1; j < t.length; j++) {\n if (isChr(t[j]) || isInt(t[j])) {\n op += t[j];\n i = j;\n } else break;\n }\n opVariables.push(op);\n op = \"\";\n } else {\n if (i == 0 || (i > 0 && isOp(t[i - 1]))) {\n op = t[i];\n let j = i + 1;\n for (; j < t.length; j++) {\n if (isInt(t[j])) {\n op += t[j];\n i = j;\n } else break;\n }\n limits.push(op);\n op = \"\";\n }\n }\n }\n }\n\n let min = limits[0];\n let max = limits[1];\n\n let pvs = ops.map((o, i) => [o, opVariables[i]]);\n\n for (let pv of pvs) {\n if (pv[1] == undefined) {\n pv[1] = max;\n }\n // print(`${min} ${pv[0]} ${pv[1]} ?`)\n if (eval(`${min}${pv[0]}${pv[1]}`)) {\n // print(` ${min} ${pv[0]} ${pv[1]} true`)\n min = pv[1];\n } else {\n print(\"input error\");\n process.exit();\n }\n }\n}\n\nvar n\nfunction main() {\n n = parseInt(lines[0][0], 10)\n predict([\"1<=n<=150\"])\n\n var x = 0\n for (var i = 1; i <= n; i++) {\n c = lines[i][0]\n // print(c)\n if (c[0] == '+' || c[c.length-1] == '+')\n x += 1\n else if (c[0] == \"-\" || c[c.length - 1] == \"-\") \n x -= 1;\n \n }\n\n print(x)\n}\n"}, {"source_code": "var input = ''\nprocess.stdin.on('data', c => input += c)\nprocess.stdin.on('end', () => {\n console.log(input.split('\\r\\n').slice(1,-1).reduce((a, v) => v.includes('+') ? a+1:a-1, 0))\n})"}, {"source_code": "var num_lineas = readline(); // Leemos el número de lineas que debemos tratar\nvar sol = 0;\nvar linea;\n// Por cada linea propuesta:\nfor (var i = 0; i < num_lineas; i++) {\n linea = readline(); // Leemos la linea\n // Si la linea contiene '+' sumamos 1 a la solución, en caso contrario restamos 1\n if (linea.indexOf('+') > -1) {\n sol++;\n } else {\n sol--;\n }\n \n}\nprint(sol); // Imprimimos la solución"}, {"source_code": "var DEBUG = 0\n\nfunction prt(s) {\n (DEBUG ? console.log : print)(s);\n}\n\nvar a, x = 0;\nfunction solve(line) {\n if (a === undefined) {\n a = parseInt(line);\n return true;\n }\n if (line.charAt(1) === '-') {\n x--;\n } else {\n x++;\n }\n a--;\n if (a === 0) {\n prt(x);\n return false;\n }\n return true;\n}\n\nif (DEBUG) {\n var readline = require('readline');\n var rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n });\n rl.on('line', function(s){solve(s)});\n} else {\n while (solve(readline()));\n}\n"}, {"source_code": "var num=readline();\nvar x=0;\nfor(var i=0;i= ref); i = 1 <= ref ? ++j : --j) {\n if (readline().includes('++')) {\n tot++;\n } else {\n tot--;\n }\n }\n return print(tot);\n};\n\n\n function main() {\n return mainAux();\n }\n;\n\n//# sourceMappingURL=operator-282-a.js.map\n"}, {"source_code": "var num_lineas = readline(); // Leemos el número de lineas que debemos tratar\nvar sol = 0;\nvar linea;\n// Por cada linea propuesta:\nfor (var i = 0; i < num_lineas; i++) {\n linea = readline(); // Leemos la linea\n // Si la linea contiene '+' sumamos 1 a la solución, en caso contrario restamos 1\n if (linea.indexOf('+') > -1) {\n sol++;\n } else {\n sol--;\n }\n \n}\nprint(sol); // Imprimimos la solución"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet t = +readLine()\n\tlet x=0\n\twhile(t--){\n\t\tlet operator = readLine()\n\t\tswitch(operator){\n\t\t\tcase 'X++':\n\t\t\t\tx++\n\t\t\t\tbreak\n\t\t\tcase '++X':\n\t\t\t ++x\n\t\t\t break\n\t\t\tcase 'X--':\n\t\t\t\tx--\n\t\t\t\tbreak\n\t\t\tcase '--X':\n\t\t\t\t--x\n\t\t\t\tbreak\n\t\t}\n\t}\n\tconsole.log(x)\n}"}, {"source_code": "// https://codeforces.com/problemset/problem/282/A\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet data = [];\nrl.on('line', (input) => {\n data.push(input);\n});\n\nrl.on('close', () => {\n solve(data);\n});\n\nfunction solve(data) {\n let x = 0;\n\n for (let i = 1; i < data.length; i++) {\n const element = data[i];\n if (element.includes('++')) {\n x++;\n } else if (element.includes('--')) {\n x--;\n }\n }\n\n console.log(x);\n}\n"}, {"source_code": "\nlet _inputLines;\nlet _lineNumber = 0;\nlet inputReader = _inputReader ();\n\nfunction _main() {\n\t\n\t_inputLines = _inputData.trim().split('\\n').map((string) => {\n\t\treturn string.trim();\n\t});\n\t\n\tlet t = inputReader.readNumber();\n\tvar x = 0;\n\t\n\twhile (t--) {\n\t let tmp = inputReader.readLine();\n\t if (tmp[1] == \"+\") x++;\n\t else x--;\n\t}\n\t\n\tconsole.log(x);\n\n}\n\nvar _inputData = '';\nfunction cacheInput(data) {\n\t_inputData += data;\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', cacheInput).on('end', _main);\n\nfunction _inputReader () {\n\tfunction readNumber(){\n\t\treturn Number(_inputLines[_lineNumber++]);\n\t}\n\t\t\n\tfunction readLine(){\n\t\treturn _inputLines[_lineNumber++];\n\t}\n\t\t\n\t\n\treturn {\n\t\treadNumber,\n\t\treadLine,\n\t}\n}"}, {"source_code": "answer = 0;\nfor(triesQuantity = readline(); triesQuantity; triesQuantity--)\n {\n if (readline().indexOf('++') !== -1)\n {\n answer++; \n }\n else\n {\n answer--;\n }\n }\nprint(answer);"}, {"source_code": "var numero = readline();\nvar contador = 0;\nfor (var i = 0; i {\n data.push(input);\n});\n\nrl.on('close', () => {\n solve(data);\n});\n\nfunction solve(data) {\n let x = 0;\n\n for (let i = 1; i < data.length; i++) {\n const element = data[i];\n if (element.includes('++')) {\n x++;\n } else if (element.includes('--')) {\n x--;\n }\n }\n\n console.log(x);\n}\n"}, {"source_code": "\n\"use strict\";\nlet input = [];\nconst readline=require('readline');\nconst RL=readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nRL.on('line', (line)=>{\n input.push(line.trim());\n});\nRL.on('close', ()=>{\n const n = parseInt(input[0]);\n let answer=0;\n for(let i=1; i<=n; ++i){\n if(input[i].includes(\"++\")){\n answer++;\n } else{\n answer--;\n }\n }\n console.log(answer);\n});\n"}, {"source_code": "function main() {\n const res = stdin.slice(1).reduce((s,x)=>{\n return s = (x[1] === \"+\") ? s+1 : s-1;\n },0)\n console.log(res)\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({input: process.stdin});\nvar stdin = [];\nrl.on('line', function (line) {\n stdin.push(line);});\nrl.on('close', main);\n"}, {"source_code": "var n = readline();\nvar x = 0;\n\nfor(var i = 0; i < n; i++)\n{\n var statement = readline();\n if(statement[0] == \"+\" || statement[1] == \"+\" || statement[2] == \"+\")\n {\n x++\n }\n else\n {\n x--;\n }\n}\n\nprint(x);"}, {"source_code": "var n = readline()\nvar ans = 0\n\nfor(var i = 0; i < n; i++) {\n var exp = readline()\n if(exp[1] == \"-\"){\n ans--\n }else{\n ans++\n \n }\n}\nprint(ans)\n"}, {"source_code": "n = +readline();\n\nX = 0;\n\nwhile(n--){\n eval(readline())\n}\nprint(X)"}, {"source_code": "for(var i=0,x=parseInt(readline()),c=0;i parseInt(x));\n}\n\nreadLine.on(\"line\", (line) => input.push(line));\nreadLine.on(\"close\", () => {\n const length = input[0];\n let x = 0;\n for(let i = 1; i <= length; i ++){\n const string = String(input[i])\n if(string.indexOf('+') != -1){\n x++;\n } else if(string.indexOf('-') != -1){\n x--;\n }\n else {\n continue;\n }\n }\n console.log(x);\n});"}, {"source_code": "var statement = Number(readline());\nvar x = 0;\nwhile(statement--){\n var row = readline();\n\n if(row == \"X++\" || row == \"++X\"){\n x++; \n }else{\n x--;\n }\n\n}\n\nprint(x);\n"}, {"source_code": " process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n \n let stdinInput = '';\n \n process.stdin.on('data', input => {\n stdinInput += input;\n })\n \n process.stdin.on('end', () => {\n main(stdinInput);\n })\n \n function main(data) {\n data = data.split('\\n');\n const n = data.shift();\n let x = 0;\n for (let i = 0; i < n; i += 1) {\n if (data[i].match(/-/)) x -= 1;\n else x += 1;\n } \n process.stdout.write(x + '');\n }"}, {"source_code": "var n = readline();\nvar x = 0;\n\nfor (var i = 0; i < n; i++){\n var r = readline();\n if(r.includes('+')){\n x++;\n } else if (r.includes('-')){\n x--;\n }\n}\nprint(x);"}, {"source_code": "const n = Number(readline());\nvar x = 0;\nvar s ;\nfor(var i = 0; i -1;\n}\n\nfunction clearWhitespaces() {\n while (cursor < input.length && isWhitespace(input[cursor])) ++cursor; \n}\n\nfunction nextInt() {\n return parseInt(nextString());\n}\n\nfunction nextFloat() {\n return parseFloat(nextString());\n}\n\nfunction nextChar() {\n clearWhitespaces();\n if (cursor < input.length)\n return input[cursor++];\n return '';\n}\n\nfunction nextString() {\n let str = \"\";\n clearWhitespaces();\n while (cursor < input.length && !isWhitespace(input[cursor])) {\n str += input[cursor++];\n }\n return str;\n}\n"}, {"source_code": "/* TEST CASE\ninput\n1\n++X\noutput\n1\ninput\n2\nX++\n--X\noutput\n0\n\n */\nfunction main() {\n\tvar n = parseInt(readline());\n\tvar answer = 0;\n\tfor (var i = 0; i < n; i++) {\n\t\tvar s = readline();\n\t\tif (s == \"++X\" || s == \"X++\") {\n\t\t\tanswer++;\n\t\t} else {\n\t\t\tanswer--;\n\t\t}\n\t}\n\t\n\tprint(answer);\n}\n\nmain();"}, {"source_code": "var lines = readline();\nvar x = 0;\nfor (var i = 0; i < lines; i++) {\n\tvar line = readline().split(' ');\n\tif (line == '++X' || line == 'X++') {\n\t\tx++;\n\t} else {\n\t\tx--;\n\t}\n}\nprint(x);"}, {"source_code": "var n = readline();\nvar x = 0;\n\nfor (var i = 0; i < n; i++) {\n var addOrSubtract = readline()[1];\n if (addOrSubtract === '+') {\n x++;\n } else {\n x--;\n }\n}\nprint(x);"}, {"source_code": "var operations = readline();\nvar value = 0;\nfor(var i = 0; i < operations; i++) {\n if(readline().indexOf('+') !== -1) {\n value++;\n } else {\n value--;\n }\n}\nprint(value);"}, {"source_code": "'use strict';\n\nconst count = readline().split(/\\s+/g);\nconst n = count[0];\n\nlet answer = 0;\n\nfor(let i=0; i -1) {\n count++;\n } else if(input.indexOf(\"--\") > -1) {\n count --;\n }\n}\n\nprint(count);"}, {"source_code": "input=readline();\ninput=input.split(' ').map(e=>parseInt(e));\nn=input[0]\nans=0;\nwhile(n--){\n tmp=readline();\n ans+=(tmp.indexOf('+')===-1)?-1:1;\n}\nprint(ans)"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readAsInt(){\n return parseInt(readline());\n}\n\nfunction readAsIntList(){\n return readline().split(' ').filter(i => i).map(i => parseInt(i));\n}\n\n\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const n = readAsInt();\n let result = 0;\n for (let i = 0; i < n; i++) {\n result += readline().includes(\"++\") ? 1 : -1;\n }\n console.log(result);\n}\n\n"}, {"source_code": "var x= parseInt(readline());\nvar result=0;\nwhile(x--){\n var y =readline();\n \n for(var i=0; i= 1 && n <= 150)) {\n print(0);\n}\nelse {\n var x = 0;\n \n while (n-- > 0){\n var statement = readline();\n var variable = String(statement).match(/[a-zA-Z]+/)[0];\n var atBegin = statement[0] === variable;\n var symbol = atBegin ? statement[statement.length - 1] : statement[0];\n \n if (symbol === '+') {\n if (atBegin) x++;\n else ++x;\n } else {\n if (atBegin) x--;\n else --x;\n }\n }\n \n print(x);\n}"}, {"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nconst readLine=()=> inputString[currentLine++];\n/* ================================================ \n Main Solution Starts Here \n===================================================*/\n\nconst main=()=>{\n\tlet t = +readLine()\n\tlet x=0\n\twhile(t--){\n\t\tlet operator = readLine()\n\t\tswitch(operator){\n\t\t\tcase 'X++':\n\t\t\t\tx++\n\t\t\t\tbreak\n\t\t\tcase '++X':\n\t\t\t ++x\n\t\t\t break\n\t\t\tcase 'X--':\n\t\t\t\tx--\n\t\t\t\tbreak\n\t\t\tcase '--X':\n\t\t\t\t--x\n\t\t\t\tbreak\n\t\t}\n\t}\n\tconsole.log(x)\n}"}, {"source_code": "n = +readline();\n\nX = 0;\n\nwhile(n--){\n eval(readline())\n}\nprint(X)"}, {"source_code": "var input = readline();\ninput = input.split(' ');\n\nvar skaicius = 0;\n\nfor(var i = 0; i < parseInt(input); i++) {\n var line = readline();\n\n if(line.toLowerCase() == \"++x\" || line.toLowerCase() == \"x++\") {\n skaicius++;\n } else if (line.toLowerCase() == \"--x\" || line.toLowerCase() == \"x--\") {\n skaicius--;\n }\n}\n\nprint(skaicius);"}, {"source_code": "var num_lineas = readline(); // Leemos el número de lineas que debemos tratar\nvar sol = 0;\nvar linea;\n// Por cada linea propuesta:\nfor (var i = 0; i < num_lineas; i++) {\n linea = readline(); // Leemos la linea\n // Si la linea contiene '+' sumamos 1 a la solución, en caso contrario restamos 1\n if (linea.indexOf('+') > -1) {\n sol++;\n } else {\n sol--;\n }\n \n}\nprint(sol);"}, {"source_code": "// Generated by CoffeeScript 2.5.1\nvar lines, mainAux, print, readline, rl, rli, write;\n\nrl = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nprint = console.log;\n\nwrite = function(...args) {\n return process.stdout.write(args.join(' '));\n};\n\nlines = [];\n\nrl.on('line', function(line) {\n return lines.push(line);\n});\n\nrl.on('close', main);\n\nrli = 0;\n\nreadline = function() {\n return lines[rli++];\n};\n\nmainAux = function() {\n var i, j, numlines, ref, tot;\n numlines = readline();\n tot = 0;\n for (i = j = 1, ref = numlines; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) {\n if (readline().includes('++')) {\n tot++;\n } else {\n tot--;\n }\n }\n return print(tot);\n};\n\n\n function main() {\n return mainAux();\n }\n;\n\n//# sourceMappingURL=operator-282-a.js.map\n"}, {"source_code": "var n = readline();\nvar a = [];\n\nfor (var i = 0; i < n; i++) {\n a.push(readline());\n}\n\nvar count = 0;\n\na.forEach(function (j, o ,s) {\n if (j.indexOf('+') != -1) count++;\n else count--;\n});\n\n\nprint(count);"}, {"source_code": " process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n \n let stdinInput = '';\n \n process.stdin.on('data', input => {\n stdinInput += input;\n })\n \n process.stdin.on('end', () => {\n main(stdinInput);\n })\n \n function main(data) {\n data = data.split('\\n');\n const n = data.shift();\n let x = 0;\n for (let i = 0; i < n; i += 1) {\n if (data[i].match(/-/)) x -= 1;\n else x += 1;\n } \n process.stdout.write(x + '');\n }"}, {"source_code": "var n = readline();\nvar a;\nvar cnt = 0;\nfor(var i = 0; i < n; i++){\n a = readline();\n if(a == \"++X\" || a == \"X++\"){\n cnt++;\n }\n else{\n cnt--;\n }\n}\nwrite(cnt);"}, {"source_code": "let fs = require('fs')\n\nlet txt = fs.readFileSync(0, \"utf-8\").split(\"\\r\\n\").filter((data) => {\n return data.length > 0;\n});\n\nfor (let index = 0; index < txt.length; index++) {\n if (!isNaN(txt[index]*1)) {\n let tab = []\n for (let i = 1; i <= txt[index]; i++) {\n tab.push(txt[index + i]);\n }\n square(tab)\n }\n\n}\n\nfunction square(tab) {\n let score = 0;\n tab.forEach(element => {\n if(element[0]==\"+\" || element[1]==\"+\") {\n ++score;\n }else{\n --score;\n }\n });\n console.log(score);\n \n}"}, {"source_code": "var n = readline();//.split(\" \").map(function(x) { return parseInt(x); });\nn=parseInt(n);\nvar arr=[];\nfor (var i=0;i {\n return data.length > 0;\n});\n\nfor (let index = 0; index < txt.length; index++) {\n if (!isNaN(txt[index]*1)) {\n let tab = []\n for (let i = 1; i <= txt[index]; i++) {\n tab.push(txt[index + i]);\n }\n square(tab)\n }\n\n}\n\nfunction square(tab) {\n let score = 0;\n tab.forEach(element => {\n if(element[0]==\"+\" || element[1]==\"+\") {\n ++score;\n }else{\n --score;\n }\n });\n console.log(score);\n \n}"}, {"source_code": "var input = +readline();\nvar arrRequest = [];\nvar Arr = [];\nvar check = 0;\nvar x = 0;\nfor(var i = 0; i < input; i++){\n\tarrRequest[i] = readline().split('');\n\tArr[i] = arrRequest[i][1];\n}\nArr.forEach(function(val, index){\n\tif(val == '+')x++;\n\tif(val == '-')x--;\n})\nprint(x);"}, {"source_code": "function main() {\n var lines = readline();\n var x = 0;\n for (; lines > 0; lines--) {\n var operation = readline();\n if (operation[1] === '+') {\n x += 1;\n } else if (operation[1] === '-') {\n x -= 1;\n }\n }\n print(x);\n}\nmain()"}, {"source_code": "\n var lines = readline();\n var processes = [];\n var lineProcess = \"\";\n var x = 0;\n \n for(var i=0;i {\n inputString += inputStd;\n});\nprocess.stdin.on('end', function () {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((str) => {\n return str.trim();\n });\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let count = 0;\n for (let i = 0; i < n; i++) {\n let op = readLine();\n if (op === 'X++' || op === '++X') {\n count++;\n } else {\n count--;\n }\n }\n console.log(count);\n}\n"}, {"source_code": "for(var i=0,x=parseInt(readline()),c=0;i {\n inputString += inputStd;\n});\nprocess.stdin.on('end', function () {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((str) => {\n return str.trim();\n });\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let count = 0;\n for (let i = 0; i < n; i++) {\n let op = readLine();\n if (op === 'X++' || op === '++X') {\n count++;\n } else {\n count--;\n }\n }\n console.log(count);\n}\n"}, {"source_code": "var n = Number(readline());\nvar ans = 0;\nvar str = '';\n\nfor (var i = 0 ; i < n ; i++) {\n str = readline();\n\n for (var j = 0 ; j < 3 ; j++) {\n if (str[j] == '+') {\n ans++;\n break;\n }\n if(str[j] == '-') {\n ans--;\n break;\n }\n }\n}\n\nprint(ans);"}, {"source_code": "var value = +readline();\nvar count = 0\nfor (var i=0; i < value; i++) {\n var c = readline().split(\"\");\n if (c[0] === '+' || c[1] === '+' || c[2] === '+' ) {\n count++;\n } else count--\n}\nprint(count);"}, {"source_code": "readline()\n var result = 0\n\n var flag = true\n while (flag) {\n var line = readline()\n if (line) {\n var re = /[++]/\n re.test(line) ? result++ : result--\n // problems.push(line)\n } else {\n flag = false\n }\n }\n\n print(result)"}, {"source_code": "\nlet _inputLines;\nlet _lineNumber = 0;\nlet inputReader = _inputReader ();\n\nfunction _main() {\n\t\n\t_inputLines = _inputData.trim().split('\\n').map((string) => {\n\t\treturn string.trim();\n\t});\n\t\n\tlet t = inputReader.readNumber();\n\tvar x = 0;\n\t\n\twhile (t--) {\n\t let tmp = inputReader.readLine();\n\t if (tmp[1] == \"+\") x++;\n\t else x--;\n\t}\n\t\n\tconsole.log(x);\n\n}\n\nvar _inputData = '';\nfunction cacheInput(data) {\n\t_inputData += data;\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', cacheInput).on('end', _main);\n\nfunction _inputReader () {\n\tfunction readNumber(){\n\t\treturn Number(_inputLines[_lineNumber++]);\n\t}\n\t\t\n\tfunction readLine(){\n\t\treturn _inputLines[_lineNumber++];\n\t}\n\t\t\n\t\n\treturn {\n\t\treadNumber,\n\t\treadLine,\n\t}\n}"}, {"source_code": "n = readline();\nvar meghdar = 0;\nwhile(n--)\n{\n \t \n\ts = readline().replace(new RegExp('X' , 'g'), '')\n\tif(s == \"++\"){meghdar++}\n\telse{meghdar--}\n\t\n}\nprint(meghdar)"}, {"source_code": "function main() {\n var lines = readline();\n var x = 0;\n for (; lines > 0; lines--) {\n var operation = readline();\n if (operation[1] === '+') {\n x += 1;\n } else if (operation[1] === '-') {\n x -= 1;\n }\n }\n print(x);\n}\nmain()"}, {"source_code": "var n = parseInt(readline());\nvar x = 0;\nfor(var i = 0; i < n; i++){\n var w = readline(); \n if(w[0] == '+' || w[1] == '+') {\n x += 1\n }else {\n x -= 1 \n }\n}\nprint(x)"}, {"source_code": "n = readline();\nnumber = 0 ;\nfor (i = 0; i < n; i++) {\n a = readline();\n if(a == '++X' || a == 'X++') {\n number = number + 1;\n }\n \n if(a == '--X' || a == 'X--') {\n number = number - 1;\n }\n \n}\n\nprint(number)"}, {"source_code": "var n=parseInt(readline());\nvar x=0;\nfor(var i=0;i {\n inputString += inputStd;\n});\nprocess.stdin.on('end', function () {\n inputString = inputString\n .trim()\n .split('\\n')\n .map((str) => {\n return str.trim();\n });\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let count = 0;\n for (let i = 0; i < n; i++) {\n let op = readLine();\n if (op === 'X++' || op === '++X') {\n count++;\n } else {\n count--;\n }\n }\n console.log(count);\n}\n"}, {"source_code": "var line=readline().split(' ');\nvar n=parseInt(line[0]);\nvar ans=0;\n\nfor(var i=0;i 0) {\n\ts = readline()\n\tif (s.charAt(1) == '-')\n\t\tx ++\n\telse\n\t\tx --\n\tn --\n}\n\nprint(x)"}, {"source_code": "var numberOfTestCases = parseInt(readline());\n \nvar input = \"\";\n \nvar ans = 0\n \nfor(var i = 0 ; i < numberOfTestCases ; i++) {\n \ninput = readline().split(\" \");\n \nif (input[i] == \"X++\" || input[i] == \"++X\") ans++\nelse ans--\n}\n \nprint(ans)"}, {"source_code": "var numberOfTestCases = parseInt(readline());\n\nvar input = \"\";\n\nvar ans = 0;\n\nfor(var i = 0 ; i < numberOfTestCases ; i++) {\n\ninput = readline();\n\nif (input[i] == \"X++\" || input[i] == \"++X\") ans++;\nelse ans--;\n\n}\n\nprint(ans);"}, {"source_code": "var numberOfTestCases = parseInt(readline());\n\nvar input = \"\";\n\nvar ans = 0\n\nfor(var i = 0 ; i < numberOfTestCases ; i++) {\n\ninput = readline().split(\" \");\n\nif (input[i] == \"X++\" || input[i] == \"++X\") ans++\nelse ans--\n}\n\nprint(ans)"}, {"source_code": "var num_op = parseInt(readline());\nvar x = 0;\nwhile(num_op >0){\n var value = readline();\n if(value == \"++X\" || value == \"X++\" ) x++;\n if(value == \"--X\" || value == \"X--\" ) x++;\n num_op--;\n}\nprint(x);"}, {"source_code": "var nOpers = parseInt(readline());\nvar x = 0;\nvar operacion;\n\nfor(var i=0;i {\n const x = Number(readline());\n const arr = [];\n var count = 0;\n\n for (var i in [...Array(x).fill()]) {\n arr.push(readline().trim());\n }\n\n for (var b of arr) {\n if (b === 'X++') {\n count++;\n continue;\n }\n count--;\n }\n\n print(count);\n};\n\nmain()"}, {"source_code": "'use strict';\nconst n = parseInt(readline());\nvar x = 0;\n\nfor(let i = 0; i < n; i++) {\n if(readline().indexOf('+')){\n x++;\n } else {\n x--;\n }\n}\n\nwrite(x);"}, {"source_code": "var numero = readline();\nvar contador=0;\nvar x=0;\n\nfor (var i = 0; i 0 && i !== lines.length) {\n ans++\n continue\n }\n if(stmt.indexOf('--') === 0) {\n ans--\n continue\n }\n if(stmt.indexOf('--') > 0 && i !== lines.length) {\n ans--\n continue\n }\n}\n\nprint(ans)"}, {"source_code": "var lines = parseInt(readline())\nvar ans = 0\nfor(var i=0;i 0 && i < lines - 1) {\n ans++\n continue\n }\n if(stmt.indexOf('--') === 0) {\n ans--\n continue\n }\n if(stmt.indexOf('--') > 0 && i < lines - 1) {\n ans--\n continue\n }\n}\n\nprint(ans)"}, {"source_code": "// The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.\n\n// The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:\n\n// Operation ++ increases the value of variable x by 1.\n// Operation -- decreases the value of variable x by 1. \n\n// 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.\n\n// 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.\n\n// 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).\n// Input\n\n// The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme.\n\n// Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.\n// Output\n\n// Print a single integer — the final value of x.\n\nvar n = readline();\n\nvar x = 0;\nvar operations = [];\n\nvar temp;\nvar i;\nfor (i = 0; i < n; i++) {\n temp = readline();\n operations.push(temp);\n}\n\noperations.forEach(function(operation) {\n if (operation === 'X++' || operation === '++X') {\n x += 1;\n } else if (operation === 'X--' || operation === '--X') {\n x -= 1;\n }\n});\n\nprint(n);"}, {"source_code": "// The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.\n\n// The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:\n\n// Operation ++ increases the value of variable x by 1.\n// Operation -- decreases the value of variable x by 1. \n\n// 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.\n\n// 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.\n\n// 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).\n// Input\n\n// The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme.\n\n// Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.\n// Output\n\n// Print a single integer — the final value of x.\n\nconst n = readline();\n\n// let x = 0;\n// let operations = [];\n\n// for (let i = 0; i < n; i++) {\n// const temp = readline();\n// operations.push(temp);\n// }\n\n// operations.forEach(function(operation) {\n// if (operation === 'X++' || operation === '++X') {\n// x += 1;\n// } else if (operation === 'X--' || operation === '--X') {\n// x -= 1;\n// }\n// });\n\nprint(n);"}, {"source_code": "var n = parseInt(readline());\nvar X = 0;\nvar i;\nfor (i in n){\n eval(readline());\n}\nprint(X);"}, {"source_code": "var n = Number(readline());\nvar x = 0;\n\nfor (var i = 0; i < n; i++) {\n var codeLine = readline();\n\n if ( codeLine.indexOf('++') ) {\n x++;\n } else {\n x--;\n }\n}\n\nprint( x );\n"}, {"source_code": "var count = readline();\nvar num=0;\nfor(var i = 0; i -1) {\n sol++;\n } else {\n sol--;\n }\n \n}\nprint(sol);"}, {"source_code": "/**\n * @author Albert Hambardzumyan\n * @description Bit++.\n * Reference: http://codeforces.com/problemset/problem/282/A\n * Tags: implementation, 900\n */\n(function () {\n const iterations = readline()\n\n var x = 0\n for (var i = 0; i < iterations; i++) {\n const temp = readline()\n\n temp.charAt(0) === '+' || temp.charAt(2) === '+' ? x++ : x--\n }\n\n print(x)\n})()\n"}, {"source_code": "var n = readline()\nvar ans = 0\n\nfor(var i = 0; i < n; i++) {\n var exp = readline()\n var a = (exp[0] == \"-\")?ans--:ans++;\n}\n\nprint(ans)"}, {"source_code": "var n = readline()\nvar ans = 0\n\nfor(var i = 0; i < n; i++) {\n var exp = readline()\n print(exp[1])\n if(exp[1] == \"-\"){\n ans--\n }else{\n ans++\n \n }\n \n}\n\nprint(ans)"}, {"source_code": "function main(){\n var n = +readline();\n var x;\n while (n>0) {\n x = readline();\n if (x.includes(\"++\")) {\n x += +1 ;\n }\n if (x.includes(\"--\")) {\n x += -1 ;\n }\n n--;\n }\n print(x);\n}\n\nmain();\n"}, {"source_code": "function main(){\n var n = +readline();\n var x;\n var result = 0;\n while (n>0) {\n x = readline();\n if (x.includes(\"++\")) {\n result = +1 ;\n }\n if (x.includes(\"--\")) {\n result = -1 ;\n }\n n--;\n }\n print(result);\n}\n\nmain();\n"}, {"source_code": "function main(){\n var n = +readline();\n var x;\n while (n>0) {\n x = readline();\n if (x.includes(\"++\")) {\n x = x+1 ;\n }\n if (x.includes(\"--\")) {\n x = x-1 ;\n }\n n--;\n }\n print(x);\n}\n\nmain();\n"}, {"source_code": "var n = readline();\nvar x = 0;\n\nfor (var i = 0; i < n; i++){\n var r = readline();\n print(r);\n if(r.includes('+')){\n x++;\n } else if (r.includes('-')){\n x--;\n }\n}\nprint(x);"}, {"source_code": "var n=readline();\nvar ans;\nfor (var i=0; i{\n return s = x[1] === \"+\" ? s+1 : s-1;\n },0)\n console.log(res)\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({input: process.stdin});\nvar stdin = [];\nrl.on('line', function (line) {stdin.push(line);});\nrl.on('close', main);\n"}, {"source_code": "function main() {\n console.log(stdin);\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({input: process.stdin});\nvar stdin = [];\nrl.on('line', function (line) {stdin.push(line);});\nrl.on('close', main);\n"}, {"source_code": "// var stdin = \"\";\n// process.stdin.resume();\n// process.stdin.setEncoding(\"ascii\");\n// process.stdin.on(\"data\", function(data) {\n// stdin += data;\n// });\n// process.stdin.on(\"end\", function() {\n// main(stdin);\n// });\n\nconst debug = 0;\nconst stdin = `1\n\n++X\n`;\nmain(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n let currentLine = 0;\n let res = 0;\n const commandCount = readLine(stdin, currentLine);\n\n while (commandCount > currentLine) {\n ++currentLine;\n const command = readLine(stdin, currentLine).replace(\"X\", \"\");\n\n if (command === \"++\") {\n res += 1;\n } else if (command === \"--\") {\n res -= 1;\n }\n }\n\n console.log(res);\n}\n\nfunction readLine(str, line) {\n return str.split(/\\r?\\n/).filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "// var stdin = \"\";\n// process.stdin.resume();\n// process.stdin.setEncoding(\"ascii\");\n// process.stdin.on(\"data\", function(data) {\n// stdin += data;\n// });\n// process.stdin.on(\"end\", function() {\n// main(stdin);\n// });\n\nconst debug = 0;\nconst stdin = `2\n \nX++\n \n--X\n`;\nmain(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n let currentLine = 0;\n let res = 0;\n const commandCount = readLine(stdin, currentLine);\n\n while (commandCount > currentLine) {\n ++currentLine;\n const command = readLine(stdin, currentLine).replace(\"X\", \"\");\n\n if (command === \"++\") {\n res += 1;\n } else if (command === \"--\") {\n res -= 1;\n }\n }\n\n console.log(res);\n}\n\nfunction readLine(str, line) {\n return str.split(\"\\n\").filter(s => Boolean(s.trim()))[line];\n}\n"}, {"source_code": "var stdin = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\nprocess.stdin.on(\"data\", function(data) {\n stdin += data;\n});\nprocess.stdin.on(\"end\", function() {\n main(stdin);\n});\n\n// main(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n let currentLine = 0;\n let res = 0;\n const commandCount = readLine(stdin, currentLine);\n\n while (commandCount > currentLine) {\n ++currentLine;\n const command = readLine(stdin, currentLine).replace(\"X\", \"\");\n\n if (command === \"++\") {\n res += 1;\n } else if (command === \"--\") {\n res -= 1;\n }\n }\n\n console.log(res);\n}\n\nfunction readLine(str, line) {\n return str.split(\"\\n\")[line];\n}\n"}, {"source_code": "// var stdin = \"\";\n// process.stdin.resume();\n// process.stdin.setEncoding(\"ascii\");\n// process.stdin.on(\"data\", function(data) {\n// stdin += data;\n// });\n// process.stdin.on(\"end\", function() {\n// main(stdin);\n// });\n\nconst debug = 0;\nconst stdin = `1\n\n++X\n`;\nmain(stdin);\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n let currentLine = 0;\n let res = 0;\n const commandCount = readLine(stdin, currentLine);\n\n while (commandCount > currentLine) {\n ++currentLine;\n const command = readLine(stdin, currentLine).replace(\"X\", \"\");\n\n if (command === \"++\") {\n res += 1;\n } else if (command === \"--\") {\n res -= 1;\n }\n }\n\n console.log(res);\n}\n\nfunction readLine(str, line) {\n return str.split(\"\\n\").filter(Boolean)[line];\n}\n"}, {"source_code": "const readline = require('readline')\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet first = true;\nlet total = 0;\nrl.on('line', line => {\n if (first === true) {\n total = parseInt(line);\n first = false;\n }\n input = line;\n solution(input, total);\n});\n\nrl.on('close', () => {\n console.log(total);\n});\n\nfunction solution(input) {\n const operator = input[1];\n\n if (operator === '+') {\n total += 1;\n } else if (operator === '-') {\n total -= 1;\n }\n}"}, {"source_code": "\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s){\n process.stdout.write(s);\n}\n\nfunction println(s){\n console.log(s);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n // var n = readline().split(' ');\n // for(var i=0; i {\n if (i !== 1) arr.push(lineInput);\n i++;\n});\n\n// when all file readed\nrl.on(\"close\", () => {\n let result = 0;\n for (let index = 0; index < arr.length; index++) {\n if (arr[index].indexOf(\"++\") > -1) result++;\n if (arr[index].indexOf(\"--\") > -1) result--;\n }\n console.log(result);\n});\n"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\n// read each line\nlet i = 0;\nlet arr = [];\nrl.on(\"line\", (lineInput) => {\n if (i !== 1) arr.push(lineInput);\n i++;\n});\n\n// when all file readed\nrl.on(\"close\", () => {\n let result = 0;\n arr.forEach(function (el) {\n if (el.indexOf(\"++\") > -1) result++;\n if (el.indexOf(\"--\") > -1) result--;\n });\n console.log(result);\n});\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let n = parseInt(readLine());\n let arr = [];\n let ans = 0;\n for (let i = 0; i < n; i++) {\n arr.push(readLine());\n if (arr[0].indexOf('-') != -1) {\n ans--;\n } else ans++;\n }\n console.log(ans);\n}"}], "src_uid": "f3cf7726739290b280230b562cac7a74"} {"nl": {"description": "You have a card deck of $$$n$$$ cards, numbered from top to bottom, i. e. the top card has index $$$1$$$ and bottom card — index $$$n$$$. Each card has its color: the $$$i$$$-th card has color $$$a_i$$$.You should process $$$q$$$ queries. The $$$j$$$-th query is described by integer $$$t_j$$$. For each query you should: find the highest card in the deck with color $$$t_j$$$, i. e. the card with minimum index; print the position of the card you found; take the card and place it on top of the deck. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$; $$$1 \\le q \\le 3 \\cdot 10^5$$$) — the number of cards in the deck and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 50$$$) — the colors of cards. The third line contains $$$q$$$ integers $$$t_1, t_2, \\dots, t_q$$$ ($$$1 \\le t_j \\le 50$$$) — the query colors. It's guaranteed that queries ask only colors that are present in the deck.", "output_spec": "Print $$$q$$$ integers — the answers for each query.", "sample_inputs": ["7 5\n2 1 1 4 3 3 1\n3 2 1 1 4"], "sample_outputs": ["5 2 3 1 5"], "notes": "NoteDescription of the sample: the deck is $$$[2, 1, 1, 4, \\underline{3}, 3, 1]$$$ and the first card with color $$$t_1 = 3$$$ has position $$$5$$$; the deck is $$$[3, \\underline{2}, 1, 1, 4, 3, 1]$$$ and the first card with color $$$t_2 = 2$$$ has position $$$2$$$; the deck is $$$[2, 3, \\underline{1}, 1, 4, 3, 1]$$$ and the first card with color $$$t_3 = 1$$$ has position $$$3$$$; the deck is $$$[\\underline{1}, 2, 3, 1, 4, 3, 1]$$$ and the first card with color $$$t_4 = 1$$$ has position $$$1$$$; the deck is $$$[1, 2, 3, 1, \\underline{4}, 3, 1]$$$ and the first card with color $$$t_5 = 4$$$ has position $$$5$$$. "}, "positive_code": [{"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n const [n, queries] = readLine().split(' ').map(Number);\r\n\r\n const arr = readLine().split(' ').map(Number);\r\n\r\n const colors = readLine().split(' ').map(Number); //query colors.\r\n\r\n c(n,queries,arr,colors)\r\n\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction c(n,q,a,t)\r\n{\r\n const N = 60;\r\n\r\n let pos = Array(N).fill(-1); \r\n for (let i = 0; i < n; i++) {\r\n if (pos[a[i]] < 0) pos[a[i]] = i;\r\n }\r\n let res = [];\r\n for (let k = 0; k < q; k++) {\r\n res.push(pos[t[k]] + 1);\r\n for (let i = 1; i < 60; i++) {\r\n if (pos[i] >= 0 && pos[i] < pos[t[k]]) {\r\n pos[i]++;\r\n }\r\n }\r\n pos[t[k]] = 0;\r\n }\r\n return console.log(res.join(' '))\r\n}\r\n\r\nmodule.exports = c;"}, {"source_code": "// 04/12/21 afternoon \r\n \r\n///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst N = 60;\r\nconst solve = (n, q, a, t) => {\r\n // let pos = Array(n).fill(-1);\r\n let pos = Array(N).fill(-1); // 05/09/21 evening fix bug of N\r\n for (let i = 0; i < n; i++) {\r\n if (pos[a[i]] < 0) pos[a[i]] = i;\r\n }\r\n let res = [];\r\n for (let k = 0; k < q; k++) {\r\n res.push(pos[t[k]] + 1);\r\n for (let i = 1; i < 60; i++) {\r\n if (pos[i] >= 0 && pos[i] < pos[t[k]]) {\r\n pos[i]++;\r\n }\r\n }\r\n pos[t[k]] = 0;\r\n }\r\n pr(res.join(\" \"))\r\n};\r\n \r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[0][1], input[1], input[2])\r\n });\r\n};\r\n \r\nmain()"}, {"source_code": "// 04/12/21 afternoon \r\n\r\n///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst N = 60;\r\nconst solve = (n, q, a, t) => {\r\n // let pos = Array(n).fill(-1);\r\n let pos = Array(N).fill(-1); // 05/09/21 evening fix bug of N\r\n for (let i = 0; i < n; i++) {\r\n if (pos[a[i]] < 0) pos[a[i]] = i;\r\n }\r\n let res = '';\r\n for (let k = 0; k < q; k++) {\r\n res += pos[t[k]] + 1;\r\n res += ' '\r\n // pr(pos, pos[t[k]], t[k])\r\n for (let i = 1; i < 60; i++) {\r\n if (pos[i] >= 0 && pos[i] < pos[t[k]]) {\r\n pos[i]++;\r\n }\r\n }\r\n pos[t[k]] = 0;\r\n }\r\n pr(res)\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[0][1], input[1], input[2])\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nclass Node {\r\n constructor(val) {\r\n this.val = val;\r\n this.next = null;\r\n this.prev = null;\r\n }\r\n}\r\nclass Dl {\r\n constructor() {\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n push(val) {\r\n if (!this.head) this.head = this.tail = new Node(val);\r\n else {\r\n let newn = new Node(val);\r\n this.tail.next = newn;\r\n newn.prev = this.tail;\r\n this.tail = newn;\r\n }\r\n }\r\n shift(val) {\r\n let newN = new Node(val);\r\n newN.next = this.head;\r\n this.head.prev = newN;\r\n this.head = newN;\r\n }\r\n remove(val) {\r\n let ind = 1,\r\n p = this.head;\r\n while (p) {\r\n if (p.val === val) {\r\n if (p.prev === null) return ind;\r\n else if (p.next === null) {\r\n this.shift(p.val);\r\n this.tail = p.prev;\r\n this.tail.next = null;\r\n return ind;\r\n } else {\r\n this.shift(p.val);\r\n p.prev.next = p.next;\r\n p.next.prev = p.prev;\r\n return ind;\r\n }\r\n }\r\n p = p.next;\r\n ind++;\r\n }\r\n }\r\n}\r\nconst solve = () => {\r\n let t = 1;\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let q = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let list = new Dl();\r\n for (let i = 0; i < n; i++) list.push(arr[i]);\r\n let res = \"\";\r\n for (let i = 0; i < k; i++) res += list.remove(q[i]) + \" \";\r\n console.log(res);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "const readline = require(\"readline\");\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nlet input = [];\r\nrl.on('line', line => {\r\n input.push(line);\r\n})\r\nrl.on('close', line => {\r\n var set = new Array(51).fill(Infinity); // index is card number, value is highest position.\r\n var a = input[1].split(\" \").map((i) => {\r\n return Number(i);\r\n });\r\n var query = input[2].split(\" \").map((i) => {\r\n return Number(i);\r\n });\r\n for (let i = 0; i < a.length; i++) {\r\n set[a[i]] = Math.min(i + 1, set[a[i]]);\r\n }\r\n var result = [];\r\n for (let i = 0; i < query.length; i++) {\r\n var index = set[query[i]];\r\n result.push(index);\r\n for (var j = 1; j <= 50; j++) {\r\n if (set[j] < index) {\r\n set[j] += 1;\r\n }\r\n }\r\n set[query[i]] = 1;\r\n }\r\n console.log(result.join(\" \"));\r\n})"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nvar maxN = 2 * 1e5 + 10\r\nvar mod = BigInt(1e9 + 7)\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n // const xx = readline();\r\n // Array(Number(xx)).fill(1).map((t, i) => {\r\n // var n = parseInt(readline());\r\n var [n, qq] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n // var [x, y] = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var q = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n var colors = new Array(51)\r\n for (let j = 0; j < 51; j++) {\r\n colors[j] = -1\r\n }\r\n\r\n for (let j = 0; j < a.length; j++) {\r\n if (colors[a[j]] === -1) colors[a[j]] = j\r\n }\r\n var res = ''\r\n for (let i = 0; i < q.length; i++) {\r\n res = res + (colors[q[i]]+1) + ' '\r\n for (let j = 0; j < 51; j++) {\r\n if (colors[j] < colors[q[i]] && colors[j] !== -1) colors[j] += 1\r\n }\r\n colors[q[i]] = 0\r\n }\r\n console.log(res)\r\n\r\n // })\r\n}\r\n\r\n"}], "negative_code": [{"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n const [n, queries] = readLine().split(' ').map(Number);\r\n\r\n const arr = readLine().split(' ').map(Number);\r\n\r\n const colors = readLine().split(' ').map(Number); //query colors.\r\n\r\n c(n,queries,arr,colors)\r\n\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction c(n,q,a,t)\r\n{\r\n const N = 50;\r\n\r\n let pos = Array(N).fill(-1); \r\n for (let i = 0; i < n; i++) {\r\n if (pos[a[i]] < 0) pos[a[i]] = i;\r\n }\r\n let res = [];\r\n for (let k = 0; k < q; k++) {\r\n res.push(pos[t[k]] + 1);\r\n for (let i = 1; i < 60; i++) {\r\n if (pos[i] >= 0 && pos[i] < pos[t[k]]) {\r\n pos[i]++;\r\n }\r\n }\r\n pos[t[k]] = 0;\r\n }\r\n return console.log(res.join(' '))\r\n}\r\n\r\nmodule.exports = c;"}, {"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n const [n, queries] = readLine().split(' ').map(Number);\r\n\r\n const arr = readLine().split(' ').map(Number);\r\n\r\n const colors = readLine().split(' ').map(Number); //query colors.\r\n\r\n c(n,queries,arr,colors)\r\n\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction c(n,q,a,t)\r\n{\r\n const N = 50;\r\n\r\n let pos = Array(N).fill(-1); \r\n for (let i = 0; i < n; i++) {\r\n if (pos[a[i]] < 0) pos[a[i]] = i;\r\n }\r\n let res = [];\r\n for (let k = 0; k < q; k++) {\r\n res.push(pos[t[k]] + 1);\r\n for (let i = 1; i < 51; i++) {\r\n if (pos[i] >= 0 && pos[i] < pos[t[k]]) {\r\n pos[i]++;\r\n }\r\n }\r\n pos[t[k]] = 0;\r\n }\r\n return console.log(res.join(' '))\r\n}\r\n\r\nmodule.exports = c;"}, {"source_code": "\r\n'use-strict'\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n \r\nlet data = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n \r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n \r\n let [n,q] = get_ints();\r\n let a = get_ints();\r\n let c = get_ints();\r\n let ans = [];\r\n var idx = 0;\r\n for(let i = 0 ; i < q; i++)\r\n {\r\n let a_new = [];\r\n const color = c[i];\r\n for(let j = 0 ; j < n; j++)\r\n {\r\n if(a[j] === color)\r\n {\r\n a_new.unshift(color)\r\n ans.push(j+1);\r\n //console.log('a_new = ', a_new, 'a.slice(j+1) = ', a.slice(j+1))\r\n //print(a_new.concat(a.slice(j+1)))\r\n idx = j;\r\n break;\r\n }\r\n else \r\n {\r\n a_new.push(a[j])\r\n }\r\n }\r\n a = a_new.concat(a.slice(idx+1));\r\n }\r\n print(ans);\r\n});\r\n \r\nfunction print(c){\r\n return console.log(c);\r\n}\r\n \r\nfunction get_ints() { \r\n return readLine().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}"}, {"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n, q, a, t) => {\r\n let pos = Array(n).fill(-1);\r\n for (let i = 0; i < n; i++) {\r\n if (pos[a[i]] < 0) pos[a[i]] = i;\r\n }\r\n let res = '';\r\n for (let k = 0; k < q; k++) {\r\n res += pos[t[k]] + 1;\r\n res += ' '\r\n for (let i = 1; i < 60; i++) {\r\n if (pos[i] >= 0 && pos[i] < pos[t[k]]) {\r\n pos[i]++;\r\n }\r\n }\r\n pos[t[k]] = 0;\r\n }\r\n pr(res)\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[0][1], input[1], input[2])\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n, q, a, t) => {\r\n let pos = Array(n).fill(-1);\r\n for (let i = 0; i < n; i++) {\r\n if (pos[a[i]] < 0) pos[a[i]] = i;\r\n }\r\n let res = [];\r\n for (let k = 0; k < q; k++) {\r\n res.push(pos[t[k]] + 1);\r\n for (let i = 1; i < 60; i++) {\r\n if (pos[i] >= 0 && pos[i] < pos[t[k]]) {\r\n pos[i]++;\r\n }\r\n }\r\n pos[t[k]] = 0;\r\n }\r\n pr(res.join(\" \"))\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[0][1], input[1], input[2])\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nclass Node {\r\n constructor(val) {\r\n this.val = val;\r\n this.next = null;\r\n this.prev = null;\r\n }\r\n}\r\nclass Dl {\r\n constructor() {\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n push(val) {\r\n if (!this.head) this.head = this.tail = new Node(val);\r\n else {\r\n let newn = new Node(val);\r\n newn.prev = this.tail;\r\n this.tail = this.tail.next = newn;\r\n }\r\n }\r\n shift(val) {\r\n let newN = new Node(val);\r\n newN.next = this.head;\r\n this.head = newN;\r\n }\r\n remove(val) {\r\n let ind = 1,\r\n p = this.head;\r\n while (p) {\r\n if (p.val === val) {\r\n if (p.prev === null) return ind;\r\n else if (p.next === null) {\r\n this.shift(p.val);\r\n p.prev = null;\r\n this.tail = p.prev;\r\n return ind;\r\n } else {\r\n this.shift(p.val);\r\n p.prev.next = p.next;\r\n p.next.prev = p.prev;\r\n return ind;\r\n }\r\n break;\r\n }\r\n p = p.next;\r\n ind++;\r\n }\r\n }\r\n}\r\nconst solve = () => {\r\n let t = 1;\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let q = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let list = new Dl();\r\n for (let i = 0; i < n; i++) list.push(arr[i]);\r\n let res = \"\";\r\n for (let i = 0; i < k; i++) res += list.remove(q[i]) + \" \";\r\n console.log(res);\r\n }\r\n};\r\nsolve();\r\n"}], "src_uid": "26aef004295df530352485ce53b47364"} {"nl": {"description": "An array is beautiful if both of the following two conditions meet: there are at least $$$l_1$$$ and at most $$$r_1$$$ elements in the array equal to its minimum; there are at least $$$l_2$$$ and at most $$$r_2$$$ elements in the array equal to its maximum. For example, the array $$$[2, 3, 2, 4, 4, 3, 2]$$$ has $$$3$$$ elements equal to its minimum ($$$1$$$-st, $$$3$$$-rd and $$$7$$$-th) and $$$2$$$ elements equal to its maximum ($$$4$$$-th and $$$5$$$-th).Another example: the array $$$[42, 42, 42]$$$ has $$$3$$$ elements equal to its minimum and $$$3$$$ elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) — the number of test cases. Each test case consists of one line containing four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$ and $$$r_2$$$ ($$$1 \\le l_1 \\le r_1 \\le 50$$$; $$$1 \\le l_2 \\le r_2 \\le 50$$$).", "output_spec": "For each test case, print one integer — the minimum possible number of elements in a beautiful array.", "sample_inputs": ["7\n\n3 5 4 6\n\n5 8 5 5\n\n3 3 10 12\n\n1 5 3 3\n\n1 1 2 2\n\n2 2 1 1\n\n6 6 6 6"], "sample_outputs": ["4\n5\n13\n3\n3\n3\n6"], "notes": "NoteOptimal arrays in the test cases of the example: $$$[1, 1, 1, 1]$$$, it has $$$4$$$ minimums and $$$4$$$ maximums; $$$[4, 4, 4, 4, 4]$$$, it has $$$5$$$ minimums and $$$5$$$ maximums; $$$[1, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2]$$$, it has $$$3$$$ minimums and $$$10$$$ maximums; $$$[8, 8, 8]$$$, it has $$$3$$$ minimums and $$$3$$$ maximums; $$$[4, 6, 6]$$$, it has $$$1$$$ minimum and $$$2$$$ maximums; $$$[3, 4, 3]$$$, it has $$$2$$$ minimums and $$$1$$$ maximum; $$$[5, 5, 5, 5, 5, 5]$$$, it has $$$6$$$ minimums and $$$6$$$ maximums. "}, "positive_code": [{"source_code": "var limit = parseInt(readline());\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var caseArray = readline().split(\" \");\r\n var l1 = parseInt(caseArray[0]);\r\n var r1 = parseInt(caseArray[1]);\r\n var l2 = parseInt(caseArray[2]);\r\n var r2 = parseInt(caseArray[3]);\r\n var result = l1;\r\n if (l1 < l2)\r\n {\r\n if (r1 >= l2)\r\n {\r\n result = l2;\r\n }\r\n else\r\n {\r\n result = l1 + l2;\r\n }\r\n }\r\n if (l1 > l2)\r\n {\r\n if (l1 <= r2)\r\n {\r\n result = l1;\r\n }\r\n else \r\n {\r\n result = l1 + l2;\r\n }\r\n }\r\n print(result);\r\n}"}, {"source_code": "var t = +readline();\r\n \r\nfor(var i = 0; i< t; i ++) {\r\n var a = readline().split(' ').map((t) => +t);\r\n\r\n print(Task1(a));\r\n \r\n}\r\n\r\nfunction Task1(arr){\r\n\r\n var l1 = arr[0];\r\n var r1 = arr[1];\r\n var l2 = arr[2];\r\n var r2 = arr[3];\r\n var res = l1 + l2;\r\n if (l1 <= l2 && l2 <= r1) res = l2;\r\n if (l2 <= l1 && l1 <= r2) res = l1;\r\n return res;\r\n\r\n}"}, {"source_code": "//import { readline, print } from '@ip-algorithmics/codeforces-io';\r\nvar t = +readline();\r\nwhile (t--) {\r\n var _a = readline().split(' ').map(function (v) { return +v; }), l1 = _a[0], r1 = _a[1], l2 = _a[2], r2 = _a[3];\r\n var ans = void 0;\r\n if (r1 >= l2 && r2 >= l1) {\r\n ans = Math.max(l1, l2);\r\n }\r\n else {\r\n ans = l1 + l2;\r\n }\r\n print(ans);\r\n}\r\n"}, {"source_code": "let ryan = '';//.map(Numaer).sort(function(a, a){return a - a})\nprocess.stdin.on('data', c => ryan += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = ryan.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n; j++){\n var k = lines[j].split(' ').map(Number), a = k[0], b = k[1], c = k[2], d = k[3]\n \n if(Math.max(a, c) <= Math.min(b, d)){\n console.log(Math.max(a, c));\n }else{\n console.log(a + c);\n }\n }\n});\n \n \n \n\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var a = lines[i].split(' ').map(Number);\n var l1 = a[0], r1 = a[1], l2 = a[2], r2 = a[3];\n if(Math.max(l1, l2) <= Math.min(r1, r2)){\n console.log(Math.max(l1, l2));\n }else{\n console.log(l1 + l2);\n }\n }\n});\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let [l1, r1, l2, r2] = readline().split(' ').map(Number);\r\n\r\n if (r1 < l2 || r2 < l1) {\r\n output(l1 + l2);\r\n } else {\r\n output(Math.max(l1, l2));\r\n }\r\n }\r\n}\r\n"}, {"source_code": "let text = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', str => {\n if (str === '\\r\\n' || str === '\\n') {\n process.stdin.emit('end');\n } else {\n text += str;\n }\n});\n\nprocess.stdin.on('end', () => {\n const input = text.trim().replace(/\\r/g, '').split('\\n');\n const total = +input[0];\n\n for (let i = 1; i <= total; i++) {\n console.log(solve(input[i]));\n }\n\n process.exit();\n});\n\nfunction solve(str) {\n let [l1, r1, l2, r2] = str.split(' ').map(ele => +ele);\n if (r1 >= l2 && l1 <= r2) {\n return Math.max(l1, l2);\n }\n return l1 + l2;\n}\n\n\n\n\t\t\t\t\t \t\t \t \t \t \t \t\t\t \t\t"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(arr) {\n const [a, b, c, d] = arr\n if (a > c) return solve([c, d, a, b])\n if (c <= b) {\n return c\n } else {\n return a + c\n }\n}\n"}, {"source_code": "'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet [inputString, currentLine] = ['', 0];\r\nprocess.stdin.on('data', inputStdin => inputString += inputStdin);\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => string.trim());\r\n main();\r\n});\r\nconst input = () => inputString[currentLine++];\r\n\r\nconst main = () => {\r\n let tc = parseInt(input());\r\n while(tc--){\r\n const a = Array(51).fill(0);\r\n const [l1, r1, l2, r2] = input().split(' ').map(Number);\r\n for(let i = l1; i <= r1; i++){\r\n a[i] += 1;\r\n }\r\n for(let i = l2; i <= r2; i++){\r\n a[i] += 1;\r\n }\r\n let two = false;\r\n for(let i = 1; i < 51; i++){\r\n if(a[i] === 2) two = true;\r\n }\r\n let ans = l1+l2;\r\n if(two){\r\n for(let i = 1; i < 51; i++){\r\n if(a[i] === 2){\r\n ans = Math.min(ans, i);\r\n break;\r\n }\r\n }\r\n }\r\n console.log(ans);\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(a) {\r\n const [l1, r1, l2, r2] = a;\r\n if (l1 <= l2) {\r\n if (r1 >= l2) {\r\n return l2;\r\n } else {\r\n return l1 + l2;\r\n }\r\n } else {\r\n if (l1 <= r2) {\r\n return l1;\r\n } else {\r\n return l1 + l2;\r\n }\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(a));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n \nconst calc = ()=>{\n // READING:\n let [l1, r1, l2, r2] = ra();\n LT({l1, r1, l2, r2}) \n for (let i=1; i<=100; i++){\n for (let j=0; j<=i; j++){\n let min_cnt = j;\n let max_cnt = i-j;\n if (j==0){\n min_cnt = i;\n max_cnt = i;\n }\n if (l1<=min_cnt && min_cnt<=r1)\n if (l2<=max_cnt && max_cnt<=r2)\n return i;\n }\n }\n throw 'error';\n};\n "}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\n/*---------------------------------------------------*/\n\nconst calc = ()=>{\n /* read */\n let [l1, r1, l2, r2] = ra();\n\n /* solve */\n let result = 0;\n\n if (l1 <= l2 && l2 <= r1) {\n return l2;\n }\n if (l2 <= l1 && l1 <= r2) {\n return l1;\n }\n\n return l1 + l2;\n};\n\nfunction main() {\n let T = +readline();\n let out = [];\n for (let t = 1; t <= T; t++){\n out.push(calc());\n // process.stdout.write(`${calc(n, a)}\\n`);\n }\n process.stdout.write(out.join('\\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"}], "negative_code": [], "src_uid": "c783eaf1bf7e4e7321406431030d5aab"} {"nl": {"description": "There is a new attraction in Singapore Zoo: The Infinite Zoo.The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled $$$1,2,3,\\ldots$$$. There is a directed edge from vertex $$$u$$$ to vertex $$$u+v$$$ if and only if $$$u\\&v=v$$$, where $$$\\&$$$ denotes the bitwise AND operation. There are no other edges in the graph.Zookeeper has $$$q$$$ queries. In the $$$i$$$-th query she will ask you if she can travel from vertex $$$u_i$$$ to vertex $$$v_i$$$ by going through directed edges.", "input_spec": "The first line contains an integer $$$q$$$ ($$$1 \\leq q \\leq 10^5$$$) — the number of queries. The $$$i$$$-th of the next $$$q$$$ lines will contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \\leq u_i, v_i < 2^{30}$$$) — a query made by Zookeeper.", "output_spec": "For the $$$i$$$-th of the $$$q$$$ queries, output \"YES\" in a single line if Zookeeper can travel from vertex $$$u_i$$$ to vertex $$$v_i$$$. Otherwise, output \"NO\". You can print your answer in any case. For example, if the answer is \"YES\", then the output \"Yes\" or \"yeS\" will also be considered as correct answer.", "sample_inputs": ["5\n1 4\n3 6\n1 6\n6 2\n5 5"], "sample_outputs": ["YES\nYES\nNO\nNO\nYES"], "notes": "NoteThe subgraph on vertices $$$1,2,3,4,5,6$$$ is shown below. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n let u = rn(),\r\n v = rn();\r\n if (u > v) return 'NO';\r\n if (u === v) return 'YES';\r\n if (u % 2 === 0 && v % 2 === 1) return 'NO';\r\n const count = num => {\r\n let cnt = 0;\r\n while (num) {\r\n cnt++;\r\n num -= num & -num;\r\n }\r\n return cnt;\r\n };\r\n if (count(u) < count(v)) return 'NO';\r\n let a = 0,\r\n b = 0;\r\n for (let i = 0; i < 32; i++) {\r\n if (1 << i > v) break;\r\n if (v & 1 << i) a++;\r\n if (u & 1 << i) b++;\r\n if (a > b) return 'NO';\r\n }\r\n return 'YES';\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= 100) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n //\r\n Array(Number(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [u, v] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n if (u > v) return console.log('NO')\r\n\r\n var ans = true\r\n var count = 0\r\n\r\n for (let i = 0; i < 40; i++) {\r\n if (u >> i & 1) count++\r\n\r\n if (v >> i & 1) {\r\n if(count<=0) ans = false\r\n count--\r\n }\r\n }\r\n console.log(ans?'YES':'NO')\r\n\r\n })\r\n}\r\n\r\nfunction checkString(a) {\r\n // console.log(a)\r\n var count = 0\r\n var res = true\r\n for (let i = 0; i < a.length; i++) {\r\n if (a[i] === '(') count++\r\n else {\r\n count--\r\n if (count < 0) res = false\r\n }\r\n }\r\n if (count !== 0) res = false\r\n\r\n return res\r\n\r\n}"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n let u = rn(),\r\n v = rn();\r\n if (u > v) return 'NO';\r\n if (u === v) return 'YES';\r\n if (u % 2 === 0 && v % 2 === 1) return 'NO';\r\n const count = num => {\r\n let cnt = 0;\r\n while (num) {\r\n cnt++;\r\n num -= num & -num;\r\n }\r\n return cnt;\r\n };\r\n if (count(u) < count(v)) return 'NO';\r\n while (u) {\r\n if (v & 1 && !(u & 1)) return 'NO';\r\n v >>= 1;\r\n u >>= 1;\r\n }\r\n return 'YES';\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= 100) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const rn = () => Number(read());\r\n const u = rn(),\r\n v = rn();\r\n if (u > v) return 'NO';\r\n if (u === v) return 'YES';\r\n if (u % 2 === 0 && v % 2 === 1) return 'NO';\r\n const count = num => {\r\n let cnt = 0;\r\n while (num) {\r\n cnt++;\r\n num -= num & -num;\r\n }\r\n return cnt;\r\n };\r\n if (count(u) < count(v)) return 'NO';\r\n return 'YES';\r\n}\r\n\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < 100) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= 100) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n //\r\n Array(Number(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [u, v] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n if (u > v) return console.log('NO')\r\n\r\n var ans = true\r\n var count = 0\r\n\r\n for (let i = 0; i < 40; i++) {\r\n if (u >> i & 1) count++\r\n\r\n if (v >> i & 1) {\r\n if(count<0) {\r\n ans = false\r\n break\r\n }\r\n count--\r\n }\r\n }\r\n console.log(ans?'YES':'NO')\r\n\r\n })\r\n}\r\n\r\nfunction checkString(a) {\r\n // console.log(a)\r\n var count = 0\r\n var res = true\r\n for (let i = 0; i < a.length; i++) {\r\n if (a[i] === '(') count++\r\n else {\r\n count--\r\n if (count < 0) res = false\r\n }\r\n }\r\n if (count !== 0) res = false\r\n\r\n return res\r\n\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 1002\r\n\r\nfunction main() {\r\n const x = readline();\r\n //\r\n Array(Number(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [u, v] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n\r\n if (u > v) return console.log('NO')\r\n\r\n var ans = true\r\n var count = 0\r\n\r\n for (let i = 0; i < 40; i++) {\r\n if (u >> i & 1) count++\r\n\r\n if (v >> i & 1) {\r\n if(count<0) ans = false\r\n count--\r\n }\r\n }\r\n console.log(ans?'YES':'NO')\r\n\r\n })\r\n}\r\n\r\nfunction checkString(a) {\r\n // console.log(a)\r\n var count = 0\r\n var res = true\r\n for (let i = 0; i < a.length; i++) {\r\n if (a[i] === '(') count++\r\n else {\r\n count--\r\n if (count < 0) res = false\r\n }\r\n }\r\n if (count !== 0) res = false\r\n\r\n return res\r\n\r\n}"}], "src_uid": "a4e605859608d0c730ecbbee9ffc92d7"} {"nl": {"description": "A bracketed sequence is called correct (regular) if by inserting \"+\" and \"1\" you can get a well-formed mathematical expression from it. For example, sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word \"correct\" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $$$l$$$ nanoseconds, where $$$l$$$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for \"))((\" he can choose the substring \")(\" and do reorder \")()(\" (this operation will take $$$2$$$ nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^6$$$) — the length of Dima's sequence. The second line contains string of length $$$n$$$, consisting of characters \"(\" and \")\" only.", "output_spec": "Print a single integer — the minimum number of nanoseconds to make the sequence correct or \"-1\" if it is impossible to do so.", "sample_inputs": ["8\n))((())(", "3\n(()"], "sample_outputs": ["6", "-1"], "notes": "NoteIn the first example we can firstly reorder the segment from first to the fourth character, replacing it with \"()()\", the whole sequence will be \"()()())(\". And then reorder the segment from the seventh to eighth character, replacing it with \"()\". In the end the sequence will be \"()()()()\", while the total time spent is $$$4 + 2 = 6$$$ nanoseconds."}, "positive_code": [{"source_code": "const processData = (lines) => {\n const s = lines[1].split('')\n\n let balance = 0\n\n // const prefix = []\n let acc = 0\n let neg = false\n let sum = 0\n let peak = 0\n for (let j =0; j i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const init = () => {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n let inputString = '';\n let currentLine = 0;\n\n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n\n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main(); \n });\n\n global.readline = () => {\n return inputString[currentLine++];\n }\n};\n\nif (typeof readline === 'undefined') {\n init();\n}\n\nconst print = (...args) => {\n console.log(...args);\n};\n\nconst isBalanced = (s) => {\n let r_cnt = 0;\n let l_cnt = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] === ')') r_cnt++;\n if (s[i] === '(') l_cnt++;\n }\n return r_cnt === l_cnt;\n};\n\nconst main = () => {\n let n = parseInt(readline());\n let s = readline();\n if (!isBalanced(s)) return print(-1);\n\n let needs = false;\n let l_cnt = 0;\n let r_cnt = 0;\n let left = n;\n let cnt = 0;\n for (let i = 0; i < n; i++) {\n if (s[i] === ')') r_cnt++;\n if (s[i] === '(') l_cnt++;\n // print({ r_cnt, l_cnt, left, i, needs });\n if (r_cnt > l_cnt) {\n left = Math.min(left, i);\n needs = true;\n } else if (needs && r_cnt === l_cnt) {\n needs = false;\n cnt += i - left + 1;\n left = n;\n }\n }\n print(cnt)\n};\n"}, {"source_code": "function main(raw) {\n var lines = raw.trim().split(\"\\n\").map(function (l) { return l.trim(); });\n var l = parseInt(lines.shift(), 10);\n console.log(solve(l, lines.shift()));\n}\nfunction solve(l, s) {\n var cnt = 0;\n var cval = 0;\n var countingwrong = false;\n var failcnt = 0;\n for (var i = 0; i < l; i++) {\n if (s[i] === \"(\") {\n cval++;\n }\n else {\n cval--;\n }\n if (countingwrong) {\n if (cval === 0) {\n failcnt++;\n cnt += failcnt;\n failcnt = 0;\n countingwrong = false;\n }\n else {\n failcnt++;\n }\n }\n else if (cval < 0) {\n countingwrong = true;\n failcnt++;\n }\n }\n if (cval !== 0) {\n return -1;\n }\n return cnt;\n}\n(function () {\n var d = \"\";\n process.stdin.on(\"data\", function (c) { return d += c; });\n process.stdin.on(\"end\", function () { return main(d); });\n})();\n"}, {"source_code": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var n = +readline();\n var str = readline();\n\n var bracketsSum = 0;\n var wrongBracketsSum = 0;\n for (var i = 0; i < str.length; i++) {\n if (str[i] === \"(\") {\n if (bracketsSum === -1) {\n wrongBracketsSum++;\n }\n bracketsSum++;\n }\n if (str[i] === \")\") {\n bracketsSum--;\n }\n if (bracketsSum < 0) {\n wrongBracketsSum++;\n }\n }\n if (bracketsSum !== 0) {\n print(-1);\n return;\n }\n print(wrongBracketsSum);\n}\nmain()"}], "negative_code": [{"source_code": "const processData = (lines) => {\n const s = lines[1].split('')\n\n let balance = 0\n\n const prefix = []\n let acc = 0\n let neg = false\n let sum = 0\n let peak = 0\n for (let j =0; j i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const processData = (lines) => {\n const s = lines[1].split('')\n\n let balance = 0\n\n // const prefix = []\n let acc = 0\n let neg = false\n let sum = 0\n let peak = 0\n for (let j =0; j i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var n = +readline();\n var str = readline();\n\n var bracketsSum = 0;\n var wrongBracketsSum = 0;\n for (var i = 0; i < str.length; i++) {\n if (str[i] === \"(\") {\n if (bracketsSum === -1) {\n wrongBracketsSum++;\n }\n bracketsSum++;\n }\n if (str[i] === \")\") {\n bracketsSum--;\n }\n if (bracketsSum < 0) {\n wrongBracketsSum++;\n }\n }\n if (bracketsSum !== 0) {\n print(-1);\n }\n print(wrongBracketsSum);\n}\nmain()"}], "src_uid": "e3275cd360d8f46cbbae03dfa86b924a"} {"nl": {"description": "Bakry faced a problem, but since he's lazy to solve it, he asks for your help.You are given a tree of $$$n$$$ nodes, the $$$i$$$-th node has value $$$a_i$$$ assigned to it for each $$$i$$$ from $$$1$$$ to $$$n$$$. As a reminder, a tree on $$$n$$$ nodes is a connected graph with $$$n-1$$$ edges.You want to delete at least $$$1$$$, but at most $$$k-1$$$ edges from the tree, so that the following condition would hold:For every connected component calculate the bitwise XOR of the values of the nodes in it. Then, these values have to be the same for all connected components.Is it possible to achieve this condition?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \\leq t \\leq 5 \\cdot 10^4)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ $$$(2 \\leq k \\leq n \\leq 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ..., a_n$$$ $$$(1 \\leq a_i \\leq 10^9)$$$. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\leq u_i, v_i \\leq n$$$, $$$u_i\\neq v_i$$$), which means that there's an edge between nodes $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, you should output a single string. If you can delete the edges according to the conditions written above, output \"YES\" (without quotes). Otherwise, output \"NO\" (without quotes). You can print each letter of \"YES\" and \"NO\" in any case (upper or lower).", "sample_inputs": ["5\n2 2\n1 3\n1 2\n5 5\n3 3 3 3 3\n1 2\n2 3\n1 4\n4 5\n5 2\n1 7 2 3 5\n1 2\n2 3\n1 4\n4 5\n5 3\n1 6 4 1 2\n1 2\n2 3\n1 4\n4 5\n3 3\n1 7 4\n1 2\n2 3"], "sample_outputs": ["NO\nYES\nNO\nYES\nNO"], "notes": "NoteIt can be shown that the objection is not achievable for first, third, and fifth test cases.In the second test case, you can just remove all the edges. There will be $$$5$$$ connected components, each containing only one node with value $$$3$$$, so the bitwise XORs will be $$$3$$$ for all of them.In the fourth test case, this is the tree: .You can remove an edge $$$(4,5)$$$The bitwise XOR of the first component will be, $$$a_1 \\oplus a_2 \\oplus a_3 \\oplus a_4 = 1 \\oplus 6 \\oplus 4 \\oplus 1 = 2$$$ (where $$$\\oplus$$$ denotes the bitwise XOR). The bitwise XOR of the second component will be, $$$a_5 = 2$$$. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, a, b) {\r\n let t = a.reduce((a, b) => a ^ b, 0);\r\n if (t === 0) return 'YES';\r\n if (m < 3) return 'NO';\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n e[idx] = j, d[j]++, ne[idx] = h[i], h[i] = idx++;\r\n };\r\n for (let [u, v] of b) {\r\n add(u - 1, v - 1);\r\n add(v - 1, u - 1);\r\n }\r\n const vis = new Array(n);\r\n let res = 0;\r\n const dfs1 = RTI(i => {\r\n vis[i] = 1;\r\n const inside = () => {\r\n let params = [];\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k];\r\n if (vis[j]) continue;\r\n params.push([j]);\r\n }\r\n return params;\r\n };\r\n const after = (...result) => {\r\n let ans = result.reduce((a, b) => a ^ b, 0) ^ a[i];\r\n if (ans === t) {\r\n res++;\r\n ans = 0;\r\n }\r\n return ans;\r\n };\r\n return [inside, after];\r\n });\r\n dfs1(0);\r\n return res >= 2 ? 'YES' : 'NO';\r\n}\r\nfunction RTI(fn) {\r\n let res;\r\n const createNode = args => {\r\n return {\r\n args,\r\n result: [],\r\n curIndex: 0\r\n };\r\n };\r\n const dfs = (...args) => {\r\n const root = createNode([args]);\r\n root.cb = result => res = result;\r\n const callStack = [root];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (curCall && curCall.args.length === curCall.curIndex) {\r\n var _curCall$cb, _curCall;\r\n const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall) curCall.result[curCall.curIndex++] = res;\r\n }\r\n if (!curCall) break;\r\n const {\r\n args,\r\n curIndex\r\n } = curCall;\r\n {\r\n const res = fn(...args[curIndex]);\r\n const [inside, after] = res;\r\n let nextCall = inside();\r\n const node = createNode(nextCall);\r\n node.cb = after;\r\n callStack.push(node);\r\n }\r\n }\r\n return res;\r\n };\r\n return dfs;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(n, m, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, arr, edges))\n }\n// })()\n})\n\nfunction solve(n, k, arr, edges) {\n const xor = arr.reduce((s, x) => s ^ x, 0)\n if (!xor) return 'YES'\n if (k - 1 < 2) return 'NO'\n// console.log(xor)\n const adj = {}\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n })\n return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'\n}\nfunction dfs(adj, r, visited, arr, target) {\n const stack = [[r, 0, -1]]\n const xor = []\n let found = 0\n let cut = 0\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n cut++\n xor[u] = arr[u - 1]\n nb.forEach(v => {\n if (v !== p) xor[u] ^= xor[v]\n })\n if (xor[u] === target) {\n found++\n // console.log('found', cut, arr.length)\n if (found === 2) return true\n xor[u] = 0\n }\n stack.pop()\n }\n }\n // console.log(xor)\n return false\n}\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, a, b) {\r\n let t = a.reduce((a, b) => a ^ b, 0);\r\n if (t === 0) return 'YES';\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n e[idx] = j, d[j]++, ne[idx] = h[i], h[i] = idx++;\r\n };\r\n for (let [u, v] of b) {\r\n add(u - 1, v - 1);\r\n add(v - 1, u - 1);\r\n }\r\n const vis = new Array(n);\r\n let res = 0;\r\n const dfs1 = RTI(i => {\r\n vis[i] = 1;\r\n const inside = () => {\r\n let params = [];\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k];\r\n if (vis[j]) continue;\r\n params.push([j]);\r\n }\r\n return params;\r\n };\r\n const after = (...result) => {\r\n let ans = result.reduce((a, b) => a ^ b, 0) ^ a[i];\r\n if (ans === t) {\r\n res++;\r\n ans = 0;\r\n }\r\n return ans;\r\n };\r\n return [inside, after];\r\n });\r\n dfs1(0);\r\n return res >= 2 ? 'YES' : 'NO';\r\n}\r\nfunction RTI(fn) {\r\n let res;\r\n const createNode = args => {\r\n return {\r\n args,\r\n result: [],\r\n curIndex: 0\r\n };\r\n };\r\n const dfs = (...args) => {\r\n const root = createNode([args]);\r\n root.cb = result => res = result;\r\n const callStack = [root];\r\n while (callStack.length) {\r\n let curCall = callStack[callStack.length - 1];\r\n while (curCall && curCall.args.length === curCall.curIndex) {\r\n var _curCall$cb, _curCall;\r\n const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);\r\n callStack.pop();\r\n curCall = callStack[callStack.length - 1];\r\n if (curCall) curCall.result[curCall.curIndex++] = res;\r\n }\r\n if (!curCall) break;\r\n const {\r\n args,\r\n curIndex\r\n } = curCall;\r\n {\r\n const res = fn(...args[curIndex]);\r\n const [inside, after] = res;\r\n let nextCall = inside();\r\n const node = createNode(nextCall);\r\n node.cb = after;\r\n callStack.push(node);\r\n }\r\n }\r\n return res;\r\n };\r\n return dfs;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(n, m, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, a, b) {\r\n let t = a.reduce((a, b) => a ^ b, 0);\r\n if (t === 0) return 'YES';\r\n const h = new Array(n).fill(-1),\r\n e = [],\r\n ne = [],\r\n d = new Array(n).fill(0);\r\n let idx = 0;\r\n const add = (i, j) => {\r\n e[idx] = j, d[j]++, ne[idx] = h[i], h[i] = idx++;\r\n };\r\n for (let [u, v] of b) {\r\n add(u - 1, v - 1);\r\n add(v - 1, u - 1);\r\n }\r\n const vis = new Array(n);\r\n let res = 0;\r\n const dfs = i => {\r\n vis[i] = 1;\r\n let ans = 0;\r\n for (let k = h[i]; k !== -1; k = ne[k]) {\r\n const j = e[k];\r\n if (vis[j]) continue;\r\n let sum = dfs(j);\r\n if (sum === t) {\r\n res++;\r\n sum = 0;\r\n }\r\n ans ^= sum;\r\n if (ans === t) {\r\n res++;\r\n ans = 0;\r\n }\r\n }\r\n return ans ^ a[i];\r\n };\r\n dfs(0);\r\n return res > 2 ? 'YES' : 'NO';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const b = [];\r\n let tmp = n - 1;\r\n while (tmp--) {\r\n b.push((await read()).split(' ').map(Number));\r\n }\r\n res[i] = solve(n, m, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, arr, edges))\n }\n// })()\n})\n\nfunction solve(n, k, arr, edges) {\n const xor = arr.reduce((s, x) => s ^ x, 0)\n if (!xor) return 'YES'\n// console.log(xor)\n const adj = {}\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n })\n return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'\n}\nfunction dfs(adj, r, visited, arr, target) {\n const stack = [[r, 0, -1]]\n const xor = []\n let found = 0\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n xor[u] = arr[u - 1]\n nb.forEach(v => {\n if (v !== p) xor[u] ^= xor[v]\n })\n if (xor[u] === target) {\n found++\n if (found === 2 && u !== r) return true\n xor[u] = 0\n }\n stack.pop()\n }\n }\n // console.log(xor)\n return false\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, arr, edges))\n }\n// })()\n})\n\nfunction solve(n, k, arr, edges) {\n const xor = arr.reduce((s, x) => s ^ x, 0)\n if (!xor) return 'YES'\n// console.log(xor)\n const adj = {}\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n })\n return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'\n}\nfunction dfs(adj, r, visited, arr, target) {\n const stack = [[r, 0, -1]]\n const xor = []\n let found = 0\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n xor[u] = arr[u - 1]\n nb.forEach(v => {\n if (v !== p) xor[u] ^= xor[v]\n })\n if (xor[u] === target) {\n found++\n if (found === 2) return true\n xor[u] = 0\n }\n stack.pop()\n }\n }\n // console.log(xor)\n return false\n}\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))\n l += n - 1\n console.log(solve(n, k, arr, edges))\n }\n// })()\n})\n\nfunction solve(n, k, arr, edges) {\n const xor = arr.reduce((s, x) => s ^ x, 0)\n if (!xor) return 'YES'\n\n const adj = {}\n edges.forEach(([a, b]) => {\n adj[a] = adj[a] || []\n adj[b] = adj[b] || []\n adj[a].push(b)\n adj[b].push(a)\n })\n return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'\n}\nfunction dfs(adj, r, visited, arr, target) {\n const stack = [[r, 0, -1]]\n const xor = []\n let found = 0\n while (stack.length) {\n const [u, i, p] = stack[stack.length - 1]\n visited[u] = 1\n\n const nb = adj[u] || []\n if (!i) {\n // first visited\n }\n if (i < nb.length) {\n stack[stack.length - 1][1]++\n const v = nb[i]\n if (v !== p) {\n stack.push([v, 0, u])\n }\n } else {\n // last visited\n xor[u] = arr[u]\n nb.forEach(v => {\n if (v !== p) xor[u] ^= xor[v]\n })\n if (xor[u] === target) {\n found++\n if (found === 2) return true\n xor[u] = 0\n }\n stack.pop()\n }\n }\n return false\n}\n"}], "src_uid": "ad61d92fde608b304c0362420c2ae6dc"} {"nl": {"description": "You have an array of integers (initially empty).You have to perform $$$q$$$ queries. Each query is of one of two types: \"$$$1$$$ $$$x$$$\" — add the element $$$x$$$ to the end of the array; \"$$$2$$$ $$$x$$$ $$$y$$$\" — replace all occurrences of $$$x$$$ in the array with $$$y$$$. Find the resulting array after performing all the queries.", "input_spec": "The first line contains a single integer $$$q$$$ ($$$1 \\le q \\le 5 \\cdot 10^5$$$) — the number of queries. Next $$$q$$$ lines contain queries (one per line). Each query is of one of two types: \"$$$1$$$ $$$x$$$\" ($$$1 \\le x \\le 5 \\cdot 10^5$$$); \"$$$2$$$ $$$x$$$ $$$y$$$\" ($$$1 \\le x, y \\le 5 \\cdot 10^5$$$). It's guaranteed that there is at least one query of the first type.", "output_spec": "In a single line, print $$$k$$$ integers — the resulting array after performing all the queries, where $$$k$$$ is the number of queries of the first type.", "sample_inputs": ["7\n1 3\n1 1\n2 1 2\n1 2\n1 1\n1 2\n2 1 3", "4\n1 1\n1 2\n1 1\n2 2 2", "8\n2 1 4\n1 1\n1 4\n1 2\n2 2 4\n2 4 3\n1 2\n2 2 7"], "sample_outputs": ["3 2 2 3 2", "1 2 1", "1 3 3 7"], "notes": "NoteIn the first example, the array changes as follows:$$$[]$$$ $$$\\rightarrow$$$ $$$[3]$$$ $$$\\rightarrow$$$ $$$[3, 1]$$$ $$$\\rightarrow$$$ $$$[3, 2]$$$ $$$\\rightarrow$$$ $$$[3, 2, 2]$$$ $$$\\rightarrow$$$ $$$[3, 2, 2, 1]$$$ $$$\\rightarrow$$$ $$$[3, 2, 2, 1, 2]$$$ $$$\\rightarrow$$$ $$$[3, 2, 2, 3, 2]$$$.In the second example, the array changes as follows:$$$[]$$$ $$$\\rightarrow$$$ $$$[1]$$$ $$$\\rightarrow$$$ $$$[1, 2]$$$ $$$\\rightarrow$$$ $$$[1, 2, 1]$$$ $$$\\rightarrow$$$ $$$[1, 2, 1]$$$.In the third example, the array changes as follows:$$$[]$$$ $$$\\rightarrow$$$ $$$[]$$$ $$$\\rightarrow$$$ $$$[1]$$$ $$$\\rightarrow$$$ $$$[1, 4]$$$ $$$\\rightarrow$$$ $$$[1, 4, 2]$$$ $$$\\rightarrow$$$ $$$[1, 4, 4]$$$ $$$\\rightarrow$$$ $$$[1, 3, 3]$$$ $$$\\rightarrow$$$ $$$[1, 3, 3, 2]$$$ $$$\\rightarrow$$$ $$$[1, 3, 3, 7]$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n\tinputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n\tinputString = inputString\r\n\t\t.trim()\r\n\t\t.split(\"\\n\")\r\n\t\t.map((string) => {\r\n\t\t\treturn string.trim();\r\n\t\t});\r\n\r\n\tmain();\r\n});\r\n\r\nfunction readLine() {\r\n\treturn inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n\tvar q = +readLine();\r\n\tvar queries = [];\r\n\tfor (let i = 0; i < q; i++) {\r\n\t\tqueries.push(readLine().split(\" \").map(Number));\r\n\t}\r\n\r\n\tlet value = [];\r\n\tlet nax = 500000;\r\n\tfor (let i = 0; i <= nax; i++) {\r\n\t\tvalue.push(i);\r\n\t}\r\n\r\n\tlet ans = [];\r\n\tfor (let i = q - 1; i >= 0; i--) {\r\n\t\tif (queries[i][0] == 1) {\r\n\t\t\tans.push(value[queries[i][1]]);\r\n\t\t} else {\r\n\t\t\tvalue[queries[i][1]] = value[queries[i][2]];\r\n\t\t}\r\n\t}\r\n\tans.reverse();\r\n\tconsole.log(ans.join(\" \"));\r\n}\r\n"}], "negative_code": [{"source_code": " \"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n\tinputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n\tinputString = inputString\r\n\t\t.trim()\r\n\t\t.split(\"\\n\")\r\n\t\t.map((string) => {\r\n\t\t\treturn string.trim();\r\n\t\t});\r\n\r\n\tmain();\r\n});\r\n\r\nfunction readLine() {\r\n\treturn inputString[currentLine++];\r\n}\r\n\r\nfunction find(req, values) {\r\n\tif (values[req] == req) {\r\n\t\treturn req;\r\n\t}\r\n\treturn (values[req] = find(values[req], values));\r\n}\r\nfunction main() {\r\n\tvar q = +readLine();\r\n\tvar queries = [];\r\n\tfor (let i = 0; i < q; i++) {\r\n\t\tqueries.push(readLine().split(\" \").map(Number));\r\n\t}\r\n\r\n\tlet value = [];\r\n\tlet nax = 500000;\r\n\tfor (let i = 0; i <= nax; i++) {\r\n\t\tvalue.push(i);\r\n\t}\r\n\r\n\tlet ans = [];\r\n\tfor (let i = q - 1; i >= 0; i--) {\r\n\t\tif (queries[i][0] == 1) {\r\n\t\t\tans.push(find(queries[i][1], value));\r\n\t\t} else {\r\n\t\t\tvalue[find(queries[i][1], value)] = find(queries[i][2], value);\r\n\t\t}\r\n\t}\r\n\tans.reverse();\r\n\tconsole.log(ans.join(\" \"));\r\n}"}], "src_uid": "cb86d0b26ee542fc75e274fcfe3f3660"} {"nl": {"description": "You are given a sequence $$$a=[a_1,a_2,\\dots,a_n]$$$ consisting of $$$n$$$ positive integers.Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $$$a[l,r]$$$ a segment of the sequence $$$a$$$ with the left end in $$$l$$$ and the right end in $$$r$$$, i.e. $$$a[l,r]=[a_l, a_{l+1}, \\dots, a_r]$$$.For example, if $$$a=[31,4,15,92,6,5]$$$, then $$$a[2,5]=[4,15,92,6]$$$, $$$a[5,5]=[6]$$$, $$$a[1,6]=[31,4,15,92,6,5]$$$ are segments.We split the given sequence $$$a$$$ into segments so that: each element is in exactly one segment; the sums of elements for all segments are equal. For example, if $$$a$$$ = [$$$55,45,30,30,40,100$$$], then such a sequence can be split into three segments: $$$a[1,2]=[55,45]$$$, $$$a[3,5]=[30, 30, 40]$$$, $$$a[6,6]=[100]$$$. Each element belongs to exactly segment, the sum of the elements of each segment is $$$100$$$.Let's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is $$$3$$$.Find the minimum thickness among all possible splits of the given sequence of $$$a$$$ into segments in the required way.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. Each test case is described by two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2000$$$) — the length of the sequence $$$a$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$) — elements of the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.", "output_spec": "For each test case, output one integer — the minimum possible thickness of a split of the sequence $$$a$$$ into segments. Note that there always exist a split, you can always consider whole sequence as one segment.", "sample_inputs": ["4\n\n6\n\n55 45 30 30 40 100\n\n4\n\n10 23 7 13\n\n5\n\n10 55 35 30 65\n\n6\n\n4 1 1 1 1 4"], "sample_outputs": ["3\n4\n2\n3"], "notes": "NoteThe split in the first test case is explained in the statement, it can be shown that it is optimal.In the second test case, it is possible to split into segments only by leaving a single segment. Then the thickness of this split is equal to the length of the entire sequence, that is, $$$4$$$.In the third test case, the optimal split will be $$$[10, 55], [35, 30], [65]$$$. The thickness of the split equals to $$$2$$$.In the fourth test case possible splits are: $$$[4] + [1, 1, 1, 1] + [4]$$$; $$$[4, 1, 1] + [1, 1, 4]$$$. "}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst sqrt = (n) => {\r\n let low = 1n,\r\n high = n,\r\n ans;\r\n while (low <= high) {\r\n let mid = (low + high) / 2n;\r\n if (mid * mid <= n) {\r\n ans = mid;\r\n low = mid + 1n;\r\n } else high = mid - 1n;\r\n }\r\n return ans;\r\n};\r\n\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n const helper = (l, r, sum) => {\r\n let s = 0,\r\n dis = -1;\r\n while (r < n) {\r\n s += arr[r];\r\n if (s === sum) {\r\n s = 0;\r\n dis = Math.max(r - l + 1, dis);\r\n r++;\r\n l = r;\r\n } else r++;\r\n }\r\n\r\n return s === 0 ? dis : -1;\r\n };\r\n if (arr.length === 1) {\r\n console.log(1);\r\n continue;\r\n }\r\n let sum = arr[0],\r\n ans = Infinity;\r\n for (let i = 1; i < n; i++) {\r\n let k = helper(i, i, sum);\r\n if (k !== -1) ans = Math.min(ans, Math.max(i, k));\r\n sum += arr[i];\r\n }\r\n console.log(ans === Infinity ? n : ans);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "/*\r\n** Template\r\n*/\r\n\r\n// Common Template Starts //\r\n//*\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n let t = parseInt(readline())\r\n while (t--) {\r\n let n = parseInt(readline())\r\n let a = readline().split(' ').map(Number)\r\n console.log(solve(n, a))\r\n }\r\n}\r\n// Driver Function Ends //\r\n\r\n// MAIN LOGIC\r\nconst solve = (n, a) => {\r\n let total = 0\r\n let res = n\r\n for (let i = 0; i < n; i++) {\r\n total += a[i]\r\n let ans = i + 1\r\n let sum = 0\r\n let found = true\r\n let k = i\r\n\r\n for (let j = i + 1; j < n; j++) {\r\n if (sum + a[j] == total) {\r\n ans = Math.max(ans, (j - k))\r\n k = j\r\n sum = 0\r\n } else if ((sum + a[j]) < total) {\r\n sum += a[j]\r\n } else {\r\n found = false\r\n break\r\n }\r\n }\r\n\r\n if (found && sum == 0) res = Math.min(ans, res)\r\n\r\n }\r\n return res\r\n}\r\n\r\n\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const sum = Array(n)\n for (let i = 0; i < arr.length; i++) {\n sum[i] = arr[i]\n if (i) sum[i] += sum[i - 1]\n }\n let r = n\n for (let i = 1; i <= arr.length; i++) {\n const s = sum[i - 1]\n if (sum[n - 1] % s) continue\n let p = i\n let ok = true\n let temp = i\n while (p < n) {\n let j = p\n let now = arr[j]\n while (now < s && j + 1 < n) {\n now += arr[++j]\n }\n if (now !== s) {\n ok = false\n break\n }\n temp = Math.max(temp, j - p + 1)\n // console.log(s, ok, temp, '-', p, j, now)\n p = j + 1\n }\n if (ok) r = Math.min(r, temp)\n }\n return r\n}\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n);\r\n let res = n,\r\n t = 0;\r\n next: for (let i = 0; i < n; i++) {\r\n let ans = i + 1,\r\n sum = 0,\r\n pre = i + 1;\r\n t += a[i];\r\n for (let j = i + 1; j < n; j++) {\r\n sum += a[j];\r\n if (sum === t) {\r\n sum = 0;\r\n ans = Math.max(ans, j - pre + 1);\r\n pre = j + 1;\r\n } else if (sum > t) {\r\n continue next;\r\n }\r\n }\r\n if (sum === 0 && pre === n) {\r\n res = Math.min(res, ans);\r\n }\r\n }\r\n return res;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst sqrt = (n) => {\r\n let low = 1n,\r\n high = n,\r\n ans;\r\n while (low <= high) {\r\n let mid = (low + high) / 2n;\r\n if (mid * mid <= n) {\r\n ans = mid;\r\n low = mid + 1n;\r\n } else high = mid - 1n;\r\n }\r\n return ans;\r\n};\r\n\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n const helper = (l, r, sum) => {\r\n let s = 0,\r\n dis = -1;\r\n while (r < n) {\r\n s += arr[r];\r\n if (s === sum) {\r\n s = 0;\r\n dis = Math.max(r - l + 1, dis);\r\n r++;\r\n l = r;\r\n }\r\n r++;\r\n }\r\n\r\n return dis;\r\n };\r\n let sum = arr[0],\r\n ans = Infinity;\r\n for (let i = 1; i < n; i++) {\r\n let k = helper(i, i, sum);\r\n if (k !== -1) ans = Math.min(ans, k);\r\n sum += arr[i];\r\n }\r\n console.log(ans === Infinity ? n : ans);\r\n }\r\n};\r\nsolve();\r\n"}], "src_uid": "1ca582e932ac93ae2e1555deb16e3c3c"} {"nl": {"description": "There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.", "input_spec": "The first line contains the positive integer n (1 ≤ n ≤ 200 000) — the number of particles. The second line contains n symbols \"L\" and \"R\". If the i-th symbol equals \"L\", then the i-th particle will move to the left, otherwise the i-th symbol equals \"R\" and the i-th particle will move to the right. The third line contains the sequence of pairwise distinct even integers x1, x2, ..., xn (0 ≤ xi ≤ 109) — the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order. ", "output_spec": "In the first line print the only integer — the first moment (in microseconds) when two particles are at the same point and there will be an explosion. Print the only integer -1, if the collision of particles doesn't happen. ", "sample_inputs": ["4\nRLRL\n2 4 6 10", "3\nLLR\n40 50 60"], "sample_outputs": ["1", "-1"], "notes": "NoteIn the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3. In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point."}, "positive_code": [{"source_code": "var nbOfElement = Number(readline());\nvar direction = readline();\nvar elements = readline()\n .split(' ')\n .map(Number);\n\nvar pair = [];\nfor (var i = 1; i < nbOfElement; ++i) {\n if (direction[i - 1] === 'R' && direction[i] === 'L') {\n pair.push([i - 1, i]);\n }\n}\n\nvar smallestPair = Infinity;\nfor (var i = 0; i < pair.length; i++) {\n smallestPair = Math.min(\n smallestPair,\n Math.round((elements[pair[i][1]] - elements[pair[i][0]]) / 2)\n );\n}\n\nif (pair.length === 0) {\n print(-1);\n} else {\n print(smallestPair);\n}"}, {"source_code": "var n=parseInt(readline());\nvar d=readline();\nd += \"E\";\nvar pos=readline().split(' ');\nvar mn = 1000000000;\nfunction go(el, i, a){\n\tif(d[i] == 'R' && d[i+1] == 'L'){\n\t\tmn = Math.min(mn, (a[i+1] - a[i])/2);\n\t};\n};\npos.forEach(go);\nif(mn != 1000000000){\n\tprint(mn);\n} else {\n\tprint(-1);\n};"}, {"source_code": "var print = this.print || require('lol-io').print; //print --> outputs result and adds (enter)\nvar write = this.write || require('lol-io').write; //write --> creates output.txt with output\nvar readline = this.readline || require('lol-io').readline; //readline --> reads unread line of input.txt\n\nvar n, map, position, ans = [];\n\nn = Number(readline());\nmap = readline().replace(/\\r$/, '').split('');\nposition = readline().replace(/\\r$/, '').split(' ').map(Number);\n\nfor (i = 0; i < n - 1; i++) {\n\n if (map[i] !== map[i + 1] && map[i] === 'R') {\n\n ans.push(Math.abs(position[i] - position[i + 1]) / 2);\n } else if (map === map[i + 1] && map[i] === 'L') {\n\n ans.push(position[i + 1] - position[i]);\n } else if (map === map[i + 1] && map[i] === 'R') {\n\n ans.push(position[i] - position[i + 1]);\n } \n}\n\nans = ans.filter(x => x > 0);\n\nif (ans.length === 0) {\n \n write(-1);\n} else {\n\n write(Math.min(...ans));\n}"}, {"source_code": "(function() {\n var n = parseInt(readline());\n var dir = readline();\n var arr = readline().split(\" \").map(Number);\n \n var min = Infinity;\n \n for (var i = 0; i < dir.length - 1; i++) {\n if (dir[i] === 'R' && dir[i + 1] === 'L') {\n var low = (arr[i + 1] - arr[i]) / 2;\n if (low < min) {\n min = low;\n }\n }\n }\n \n print(min === Infinity? -1: min);\n \n})();"}, {"source_code": "function rda(){ return readline().split(\" \").map(Number); };\nfunction rdn(){ return +readline(); };\n\nvar n = rdn();\nvar coms = readline().split(\"\");\nvar x = rda();\n\nvar ans = Infinity;\nfor(var i = 0; i < n-1; i++){\n if(coms[i] == \"R\" && coms[i+1] == \"L\"){\n ans = Math.min(ans, (x[i+1]-x[i])/2);\n }\n}\nans = (ans == Infinity) ? -1 : ans;\n\nwrite(ans);"}], "negative_code": [{"source_code": "(function() {\n var n = parseInt(readline());\n var dir = readline();\n var arr = readline().split(\" \").map(Number);\n \n var min = Infinity;\n \n for (var i = 0; i < dir.length - 1; i++) {\n if (dir[i] === 'R' && dir[i + 1] === 'L') {\n var low = (arr[i + 1] - arr[i]) / 2;\n if (low < min) {\n min = low;\n }\n }\n }\n \n print(min);\n \n})();"}, {"source_code": "(function() {\n var n = parseInt(readline());\n var dir = readline();\n var arr = readline().split(\" \").map(Number);\n \n var min = Infinity;\n var collision = [];\n \n while(dir.length) {\n var found = dir.indexOf('RL');\n collision.push(found);\n dir = dir.slice(found + 2);\n }\n \n if (!collision.length) {\n print(-1);\n return;\n }\n \n collision.forEach((col) => {\n var dist = (arr[col + 1] - arr[col])/ 2;\n if (dist < min) {\n min = dist;\n }\n });\n \n print(min);\n \n})();"}, {"source_code": "(function() {\n var n = parseInt(readline());\n var dir = readline();\n var arr = readline().split(\" \").map(Number);\n \n var min = Infinity;\n var collision = [];\n \n while(dir.length) {\n var found = dir.indexOf('RL');\n if (found === -1) {\n break;\n }\n collision.push(found);\n dir = dir.slice(found + 2);\n }\n \n if (!collision.length) {\n print(-1);\n return;\n }\n \n collision.forEach((col) => {\n var dist = (arr[col + 1] - arr[col])/ 2;\n if (dist < min) {\n min = dist;\n }\n });\n \n print(min);\n \n})();"}], "src_uid": "ff0843cbd7c3a07c7d7d0be46b03a700"} {"nl": {"description": "After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.Help guys determine the winner photo by the records of likes.", "input_spec": "The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 1 000 000), where ai is the identifier of the photo which got the i-th like.", "output_spec": "Print the identifier of the photo which won the elections.", "sample_inputs": ["5\n1 3 2 2 1", "9\n100 200 300 200 100 300 300 100 200"], "sample_outputs": ["2", "300"], "notes": "NoteIn the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second). Thus, the winner is the photo with identifier 2, as it got: more likes than the photo with id 3; as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier. "}, "positive_code": [{"source_code": "var likesCount = parseInt(readline());\nvar likes = readline().split(' ').map(function (x) {return parseInt(x)})\n\nvar winnerId = -1\nvar map = {}\n\nfor (var i = 0; i < likesCount; i++) {\n\tvar photoId = likes[i]\n\n\tif (map[photoId] === undefined) {\n\t\tmap[photoId] = 0\n\t}\n\tvar newLikesCount = ++map[photoId]\n\n\tif (winnerId === -1) {\n\t\twinnerId = photoId\n\t} else {\n\t\tif (newLikesCount > map[winnerId]) {\n\t\t\twinnerId = photoId\n\t\t}\n\t}\n}\n\nprint(winnerId);"}, {"source_code": "var count = readline();\nvar data = readline().split(\" \");\nvar db = {};\nvar maxId = data[0];\ndata.forEach(function (v, c) {\n c = db[v] ? ++db[v] : (db[v] = 1);\n if (db[maxId] < c) { maxId = v }\n});\nprint(maxId);"}, {"source_code": "var l = readline().split(' ');\nvar n = +l[0];\nvar a = readline().split(' ');\nvar dat = {\n};\nvar max = 0;\nfor (var i = 0; i < a.length; i++) {\n\tdat[a[i]] = dat[a[i]] ? dat[a[i]] + 1 : 1;\n\tmax = dat[a[i]] > max ? dat[a[i]] : max;\n}\nvar list = [];\nfor(var i in dat){\n\tif(dat[i]==max){\n\t\tlist.push(i);\n\t}\n}\n\nfor (var i = a.length - 1; i >= 0; i--) {\n\tif(list.length == 1){\n\t\tbreak;\n\t}\n\tvar index = list.indexOf(a[i]);\n\tif(index!=-1){\n\t\tlist.splice(index,1);\n\t}\n}\nprint(list[0]);"}, {"source_code": "var likes = readline().split(' '),\nlikeIds = readline().split(' '),\nlastBiggest = {\n id: likeIds[0],\n count: 1\n},\nlikeObj = {};\nlikeIds.map(function(el){\n likeObj[el] = typeof likeObj[el] !== \"undefined\" ? likeObj[el]+1 : 1;\n if (lastBiggest.count < likeObj[el]) {\n lastBiggest = {\n id: el,\n count: likeObj[el]\n }\n }\n});\nprint(lastBiggest.id);"}, {"source_code": "var readInt = () => parseInt(readline())\nvar readIntArray = () => readline().split(' ').map(item => parseInt(item))\nArray.prototype.fill = function(value) {\n for (var i = 0; i < this.length; i++)\n this[i] = value\n return this\n}\nvar n = readInt()\nvar l = readIntArray()\nvar l2 = []\nl.forEach((i, index) => l2[i-1]={\n index: index, \n count: l2[i-1] ? l2[i-1].count+1 : 1\n})\nl2 = l2.filter(i => i)\nvar max = Math.max(...l2.map(i => i.count))\nvar ii = l2.filter(i => i.count === max).map(i => i.index)\nprint(l[Math.min(...ii)])"}], "negative_code": [], "src_uid": "e4a2354159fc4cab7088e016cf17ae6c"} {"nl": {"description": "Polycarp has an array $$$a$$$ consisting of $$$n$$$ integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $$$n-1$$$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally: If it is the first move, he chooses any element and deletes it; If it is the second or any next move: if the last deleted element was odd, Polycarp chooses any even element and deletes it; if the last deleted element was even, Polycarp chooses any odd element and deletes it. If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2000$$$) — the number of elements of $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "Print one integer — the minimum possible sum of non-deleted elements of the array after end of the game.", "sample_inputs": ["5\n1 5 7 8 2", "6\n5 1 2 4 6 3", "2\n1000000 1000000"], "sample_outputs": ["0", "0", "1000000"], "notes": null}, "positive_code": [{"source_code": "const readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction readLines(number, cb) {\n const lines = [];\n rl.on('line', function(line) {\n lines.push(line);\n if (lines.length === number) {\n rl.close();\n cb(lines);\n }\n });\n};\n\nfunction doIt(lines) {\n const n = parseInt(lines[0]);\n const numbers = lines[1].split(\" \").map(x => parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort((x,y)=>x-y);\n odd.sort((x,y)=> x-y);\n let num = 0;\n if (even.length > odd.length) {\n for (i=0; i even.length) {\n for (i=0; i {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number).sort((a, b) => a - b);\n const even = arr.filter(x => x % 2 === 0);\n const odd = arr.filter(x => x % 2 === 1);\n let sum = arr.reduce((a, b) => a + b, 0);\n\n while (even.length && odd.length) {\n sum -= even.pop();\n sum -= odd.pop();\n }\n\n const max = Math.max(even.pop() || 0, odd.pop() || 0);\n sum -= max;\n\n console.log(sum);\n\n // const arr = d.split(' ').map(Number);\n // arr.sort((a, b) => a - b);\n // let ans = arr.reduce((a, b) => a + b, 0);\n // const even = [];\n // const odd = [];\n\n // for (let i = 0; i < arr.length; i++) {\n // if (arr[i] % 2 === 0) {\n // even.push(arr[i]);\n // }\n // else {\n // odd.push(arr[i]);\n // }\n // }\n\n // if (even.length > odd.length) {\n // ans -= even.pop();\n\n // while (even.length && odd.length) {\n // ans -= odd.pop();\n // ans -= even.pop();\n // }\n // }\n // else if (odd.length > even.length) {\n // ans -= odd.pop();\n\n // while (even.length && odd.length) {\n // ans -= even.pop();\n // ans -= odd.pop();\n // }\n // }\n // else {\n // while (even.length && odd.length) {\n // ans -= even.pop();\n // ans -= odd.pop();\n // }\n // }\n\n // console.log(ans);\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n arr.sort((a, b) => a - b);\n let ans = arr.reduce((a, b) => a + b, 0);\n const even = [];\n const odd = [];\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) {\n even.push(arr[i]);\n }\n else {\n odd.push(arr[i]);\n }\n }\n\n if (even.length > odd.length) {\n ans -= even.pop();\n\n while (even.length && odd.length) {\n ans -= odd.pop();\n ans -= even.pop();\n }\n }\n else if (odd.length > even.length) {\n ans -= odd.pop();\n\n while (even.length && odd.length) {\n ans -= even.pop();\n ans -= odd.pop();\n }\n }\n else {\n while (even.length && odd.length) {\n ans -= even.pop();\n ans -= odd.pop();\n }\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "\nvar stdin = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding('ascii');\nprocess.stdin.on('data', function (data) { stdin += data; });\nprocess.stdin.on('end', function () { main(stdin); });\n\nvar stdin_row = 0, stdin_rows;\nfunction readLine() { if (!stdin_rows) stdin_rows = stdin.split(\"\\n\"); return stdin_rows[stdin_row++]; } // to trim ?\nfunction readLineVals() { return readLine().trim().split(/\\s+/); }\n\nconst debug = 0\nvar log = console.log;\nvar dbg = debug ? console.log : _ => {};\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n\tvar n = readLine() * 1;\n\tvar vals = readLineVals();\n\tif (n!=vals.length)\n\t\tthrow \"input parsing pb \"+n+\" \"+vals;\n\n\tvar odd = [], even = [];\n\tfor (var i =0; i b-a)\n\teven = even.sort((a,b)=> b-a)\n\tdbg(odd)\n\tdbg(even)\n\n\tnoff = Math.min(odd.length, even.length);\n\todd = odd.slice(noff)\n\teven = even.slice(noff)\n\tdbg(odd)\n\tdbg(even)\n\n\tif (odd.length>0)\n\t\tremains = odd;\n\telse\n\t\tremains = even;\n\tremains.shift();\n\tdbg(remains)\n\n\tvar sum = remains.reduce((x, acc) => { return x*1+acc*1}, 0);\n\tlog(sum)\n\n\n}"}, {"source_code": "readline();\nvar numbers=readline().split(' ').map(i=>i*1);\n\nvar odd=numbers.filter(i => i%2==0);\nvar even = numbers.filter(i => i%2==1);\nvar diff= Math.abs(odd.length-even.length)\n\nif(diff>1){\n\tvar bigger= odd.length>even.length? odd : even;\n\tbigger=bigger.sort((a,b)=>a-b).slice(0, diff-1);\n\tprint(bigger.reduce((s,c)=>s+c, 0));\n}\nelse{\n\tprint(0);\n}"}], "negative_code": [{"source_code": "const readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction readLines(number, cb) {\n const lines = [];\n rl.on('line', function(line) {\n lines.push(line);\n if (lines.length === number) {\n rl.close();\n cb(lines);\n }\n });\n};\n\nfunction doIt(lines) {\n const n = parseInt(lines[0]);\n const numbers = lines[1].split(\" \").map(x => parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n let num = 0;\n if (even.length > odd.length + 1) {\n for (i=0; i even.length +1){\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n if (n === 2000) {\n console.log(even.length, odd.length);\n }\n let num = 0;\n if (even.length > odd.length) {\n for (i=0; i even.length) {\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n let num = 0;\n if (even.length > odd.length) {\n for (i=0; i even.length) {\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n if (n === 2000 && numbers[0] !=376688) {\n console.log(even.length, \" \", odd.length);\n }\n let num = 0;\n if (even.length > odd.length) {\n for (i=0; i even.length) {\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n let num = 0;\n if (even.length > odd.length + 1) {\n for (i=0; i even.length +1) {\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n let num = 0;\n if (even.length > odd.length + 1) {\n for (i=0; i even.length +1) {\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort((x,y)=>x-y);\n odd.sort((x,y)=> x-y);\n let num = 0;\n console.log(even);\n console.log(odd);\n if (even.length > odd.length) {\n for (i=0; i even.length) {\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n if (n === 2000 && numbers[0] !=376688 && numbers[0]!=740590) {\n console.log(even.length, \" \", odd.length);\n }\n let num = 0;\n if (even.length > odd.length) {\n for (i=0; i even.length) {\n for (i=0; i parseInt(x));\n const even = [];\n const odd = [];\n numbers.forEach(element => {\n if (element%2 === 0) \n even.push(element);\n else \n odd.push(element);\n });\n even.sort();\n odd.sort();\n let num = 0;\n if (even.length > odd.length+1) {\n for (i=0; i even.length +1){\n for (i=0; i {};\n\n/////////////// ignore above this line ////////////////////\n\nfunction main(stdin) {\n\tvar n = readLine() * 1;\n\tvar vals = readLineVals();\n\tif (n!=vals.length)\n\t\tthrow \"input parsing pb \"+n+\" \"+vals;\n\n\tvar odd = [], even = [];\n\tfor (var i =0; i b-1)\n\teven = even.sort((a,b)=> b-1)\n\tnoff = Math.min(odd.length, even.length);\n\tdbg(odd)\n\tdbg(even)\n\n\todd = odd.slice(noff)\n\teven = even.slice(noff)\n\tdbg(odd)\n\tdbg(even)\n\n\tif (odd.length>0)\n\t\tremains = odd;\n\telse\n\t\tremains = even;\n\tremains.pop();\n\tdbg(remains)\n\n\tvar sum = remains.reduce((x, acc) => { return x*1+acc*1}, 0);\n\tlog(sum)\n\n\n}"}], "src_uid": "b80fed46a9e2356dad03dd3ec01523d4"} {"nl": {"description": "You are playing a computer game. In this game, you have to fight $$$n$$$ monsters.To defend from monsters, you need a shield. Each shield has two parameters: its current durability $$$a$$$ and its defence rating $$$b$$$. Each monster has only one parameter: its strength $$$d$$$.When you fight a monster with strength $$$d$$$ while having a shield with current durability $$$a$$$ and defence $$$b$$$, there are three possible outcomes: if $$$a = 0$$$, then you receive $$$d$$$ damage; if $$$a > 0$$$ and $$$d \\ge b$$$, you receive no damage, but the current durability of the shield decreases by $$$1$$$; if $$$a > 0$$$ and $$$d < b$$$, nothing happens. The $$$i$$$-th monster has strength $$$d_i$$$, and you will fight each of the monsters exactly once, in some random order (all $$$n!$$$ orders are equiprobable). You have to consider $$$m$$$ different shields, the $$$i$$$-th shield has initial durability $$$a_i$$$ and defence rating $$$b_i$$$. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given $$$n$$$ monsters in random order.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$) — the number of monsters and the number of shields, respectively. The second line contains $$$n$$$ integers $$$d_1$$$, $$$d_2$$$, ..., $$$d_n$$$ ($$$1 \\le d_i \\le 10^9$$$), where $$$d_i$$$ is the strength of the $$$i$$$-th monster. Then $$$m$$$ lines follow, the $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i \\le n$$$; $$$1 \\le b_i \\le 10^9$$$) — the description of the $$$i$$$-th shield.", "output_spec": "Print $$$m$$$ integers, where the $$$i$$$-th integer represents the expected damage you receive with the $$$i$$$-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction $$$\\dfrac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. You have to print the value of $$$x \\cdot y^{-1} \\bmod 998244353$$$, where $$$y^{-1}$$$ is the inverse element for $$$y$$$ ($$$y \\cdot y^{-1} \\bmod 998244353 = 1$$$).", "sample_inputs": ["3 2\n1 3 1\n2 1\n1 2", "3 3\n4 2 6\n3 1\n1 2\n2 3"], "sample_outputs": ["665496237\n1", "0\n8\n665496236"], "notes": null}, "positive_code": [{"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i < b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = b - 1; i >= a; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\D+/).map(v => +v); r = 0;\n let n = inp[r++], m = inp[r++];\n let d = inp.slice(r, r = r + n).sort((a, b) => a - b);\n let s = []; s[-1] = s[-2] = 0;\n For(0, n, i => { s[i] = d[i] + s[i - 1] });\n For(0, m, i => {\n let a = inp[r++], b = inp[r++];\n let i1 = 0, i2 = n - 1, ii;\n while (i1 < i2) {\n ii = (i1 + i2 + 1) >> 1;\n if (d[ii] < b) i1 = ii;\n else i2 = ii - 1;\n }\n if (d[n - 1] < b) return console.log(0);\n if (d[0] >= b) i1 = -1;\n let big = n - 1 - i1;\n if (a > big) {\n return console.log(0);\n }\n // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])\n let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)\n let y = BigInt(big) * BigInt(big + 1);\n if (x == 0) {\n return console.log(0);\n }\n let xy = gcd(x, y);\n x = x / xy;\n // y = y / xy;\n // console.log(x,y)\n // console.log(x * mod(y, 998244351n, 998244353n) % 998244353n + '');\n [y] = extendedEuclid(+(y / xy + ''), 998244353);\n console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')\n });\n // let n = inp[r++];\n // let a = inp.slice(r, r += n);\n // let end = Array(n);\n // let maxEnd = Array(n);\n // let next = Array(n);\n // let m = {}\n // For(0, n, i => {\n // if (m[a[i]] !== undefined) next[m[a[i]]] = i;\n // m[a[i]] = i;\n // });\n // console.log(n, a);\n})();"}], "negative_code": [{"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i < b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = b - 1; i >= a; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\D+/).map(v => +v); r = 0;\n let n = inp[r++], m = inp[r++];\n let d = inp.slice(r, r = r + n).sort((a, b) => a - b);\n let s = []; s[-1] = s[-2] = 0;\n For(0, n, i => { s[i] = d[i] + s[i - 1] });\n For(0, m, i => {\n let a = inp[r++], b = inp[r++];\n let i1 = 0, i2 = n - 1, ii;\n while (i1 < i2) {\n ii = (i1 + i2 + 1) >> 1;\n if (d[ii] < b) i1 = ii;\n else i2 = ii - 1;\n }\n if (d[0] >= b) i1 = -1;\n let big = n - 1 - i1;\n if (a > big) {\n return console.log(0);\n }\n // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])\n let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)\n let y = BigInt(big) * BigInt(big + 1);\n if (x == 0) {\n return console.log(0);\n }\n let xy = gcd(x, y);\n x = x / xy;\n [y] = extendedEuclid(+(y / xy + ''), 998244353);\n console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')\n });\n // let n = inp[r++];\n // let a = inp.slice(r, r += n);\n // let end = Array(n);\n // let maxEnd = Array(n);\n // let next = Array(n);\n // let m = {}\n // For(0, n, i => {\n // if (m[a[i]] !== undefined) next[m[a[i]]] = i;\n // m[a[i]] = i;\n // });\n // console.log(n, a);\n})();"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i < b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = b - 1; i >= a; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\D+/).map(v => +v); r = 0;\n let n = inp[r++], m = inp[r++];\n let d = inp.slice(r, r = r + n).sort((a, b) => a - b);\n let s = []; s[-1] = s[-2] = 0;\n For(0, n, i => { s[i] = d[i] + s[i - 1] });\n For(0, m, i => {\n let a = inp[r++], b = inp[r++];\n let i1 = 0, i2 = n - 1, ii;\n while (i1 < i2) {\n ii = (i1 + i2 + 1) >> 1;\n if (d[ii] < b) i1 = ii;\n else i2 = ii - 1;\n }\n if (d[n - 1] < b) return; console.log(0);\n if (d[0] >= b) i1 = -1;\n let big = n - 1 - i1;\n if (a > big) {\n return console.log(0);\n }\n // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])\n let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)\n let y = BigInt(big) * BigInt(big + 1);\n if (x == 0) {\n return console.log(0);\n }\n let xy = gcd(x, y);\n x = x / xy;\n // y = y / xy;\n // console.log(x,y)\n // console.log(x * mod(y, 998244351n, 998244353n) % 998244353n + '');\n [y] = extendedEuclid(+(y / xy + ''), 998244353);\n console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')\n });\n // let n = inp[r++];\n // let a = inp.slice(r, r += n);\n // let end = Array(n);\n // let maxEnd = Array(n);\n // let next = Array(n);\n // let m = {}\n // For(0, n, i => {\n // if (m[a[i]] !== undefined) next[m[a[i]]] = i;\n // m[a[i]] = i;\n // });\n // console.log(n, a);\n})();"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i < b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = b - 1; i >= a; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\D+/).map(v => +v); r = 0;\n let n = inp[r++], m = inp[r++];\n let d = inp.slice(r, r = r + n).sort((a, b) => a - b);\n let s = []; s[-1] = s[-2] = 0;\n For(0, n, i => { s[i] = d[i] + s[i - 1] });\n For(0, m, i => {\n let a = inp[r++], b = inp[r++];\n let i1 = 0, i2 = n - 1, ii;\n while (i1 < i2) {\n ii = (i1 + i2 + 1) >> 1;\n if (d[ii] < b) i1 = ii;\n else i2 = ii - 1;\n }\n if (d[0] >= b) i1 = -1;\n let big = n - 1 - i1;\n if (a > big) {\n return console.log(0);\n }\n // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])\n let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)\n let y = BigInt(big) * BigInt(big + 1);\n if (x == 0) {\n return console.log(0);\n }\n let xy = gcd(x, y);\n x = x / xy;\n [y] = extendedEuclid(+(y / xy + ''), 998244353);\n console.log(x * (BigInt(y) + 998244353n) % 998244353n + '')\n });\n // let n = inp[r++];\n // let a = inp.slice(r, r += n);\n // let end = Array(n);\n // let maxEnd = Array(n);\n // let next = Array(n);\n // let m = {}\n // For(0, n, i => {\n // if (m[a[i]] !== undefined) next[m[a[i]]] = i;\n // m[a[i]] = i;\n // });\n // console.log(n, a);\n})();"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, cb) {\n let res;\n if (a < b) {\n for (let i = a; i < b; i++) {\n if ((res = cb(i)) !== undefined) return res;\n }\n } else {\n for (let i = b - 1; i >= a; i--) {\n if ((res = cb(i)) !== undefined) return res;\n }\n }\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\D+/).map(v => +v); r = 0;\n let n = inp[r++], m = inp[r++];\n let d = inp.slice(r, r = r + n).sort((a, b) => a - b);\n let s = []; s[-1] = s[-2] = 0;\n For(0, n, i => { s[i] = d[i] + s[i - 1] });\n For(0, m, i => {\n let a = inp[r++], b = inp[r++];\n let i1 = 0, i2 = n - 1, ii;\n while (i1 < i2) {\n ii = (i1 + i2 + 1) >> 1;\n if (d[ii] < b) i1 = ii;\n else i2 = ii - 1;\n }\n if (d[n - 1] < b) return console.log(0);\n if (d[0] >= b) i1 = -1;\n let big = n - 1 - i1;\n if (a > big) {\n return console.log(0);\n }\n // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])\n let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)\n let y = BigInt(big) * BigInt(big + 1);\n if (x == 0) {\n return console.log(0);\n }\n let xy = gcd(x, y);\n x = x / xy;\n // y = y / xy;\n // console.log(x,y)\n // console.log(x * mod(y, 998244351n, 998244353n) % 998244353n + '');\n [y] = extendedEuclid(+(y / xy + ''), 998244353);\n console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')\n });\n // let n = inp[r++];\n // let a = inp.slice(r, r += n);\n // let end = Array(n);\n // let maxEnd = Array(n);\n // let next = Array(n);\n // let m = {}\n // For(0, n, i => {\n // if (m[a[i]] !== undefined) next[m[a[i]]] = i;\n // m[a[i]] = i;\n // });\n // console.log(n, a);\n})();"}], "src_uid": "ccf4ac6b61b48604b7d9f49b7daaeb0f"} {"nl": {"description": "Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \\times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \\le n, m \\le 1000; 1 \\le q \\le 2 \\cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i \\le n; 1 \\le y_i \\le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).", "output_spec": "Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.", "sample_inputs": ["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"], "sample_outputs": ["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"], "notes": null}, "positive_code": [{"source_code": "var n, m, q;\r\n var nmq = readline().split(' ').map(x=>parseInt(x));\r\n\r\n n = nmq[0];\r\n m = nmq[1];\r\n q = nmq[2];\r\n\r\n var desk = [];\r\n for (var i = 0; i < n; i++) {\r\n var row = readline().split('').map(x=> x == '.' ? 0 : 1);\r\n desk.push(row);\r\n }\r\n\r\n function hToC(h) {\r\n return desk[(h-1) % n][Math.floor((h-1) / n)];\r\n }\r\n\r\n function cToH(r, c) {\r\n return c * n + r + 1;\r\n }\r\n\r\n var head = 0;\r\n for (var r = 0; r < n; r++) {\r\n for (var c = 0; c < m; c++) {\r\n head += desk[r][c];\r\n }\r\n }\r\n var ops = 0;\r\n for (var i = 1; i <= head; i++) {\r\n if (!hToC(i)) {\r\n ops++;\r\n }\r\n }\r\n\r\n function remove(x, y) {\r\n desk[x][y] = 0;\r\n \r\n if (cToH(x, y) > head && !hToC(head)) {\r\n ops--;\r\n }\r\n if (cToH(x, y) < head && hToC(head)) {\r\n ops++;\r\n }\r\n head--;\r\n }\r\n\r\n function add(x, y) {\r\n head++;\r\n desk[x][y] = 1;\r\n if (cToH(x, y) == head) {\r\n } else {\r\n if (cToH(x, y) > head && !hToC(head)) {\r\n ops++;\r\n }\r\n if (hToC(head) && cToH(x, y) < head) {\r\n ops--;\r\n }\r\n }\r\n }\r\n\r\n for (var i = 0; i < q; i++) {\r\n var xy = readline().split(' ').map(x=>parseInt(x));\r\n var x = xy[0] - 1;\r\n var y = xy[1] - 1;\r\n if (desk[x][y]) {\r\n remove(x, y);\r\n } else {\r\n add(x, y);\r\n }\r\n\r\n print(ops);\r\n }"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst cnk = (n, k) => {\n let res = 1;\n for (let i = 1; i <= k; i++)\n res = res * (n - k + i) / i;\n return Math.round(res + 0.01);\n}\n\n\nconst sumab = (a, b) => {\n let x = (b - a + 1);\n let y = a + b;\n if (x % 2 === 0) {\n x = Math.round(x / 2);\n } else {\n y = Math.round(y / 2);\n }\n return BigInt(x) * BigInt(y);\n}\n\n\n\nconst calc = (n, m, q, grid, queries)=>{\n let total = 0, outside = 0;\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (grid[i][j] === '*') {\n total++;\n }\n }\n }\n\n let tX = total % n;\n let tY = Math.floor(total / n);\n // console.log(`DEBUG tx ${tX} ty ${tY}`);\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (grid[i][j] === '*') {\n if (j > tY) outside++;\n if (j === tY && i >= tX) outside++;\n }\n }\n }\n\n // console.log(`DEBUG outside`, outside);\n\n for (let [x, y] of queries) {\n x--; y--;\n // console.log(`DEBUG x ${x} y ${y}`);\n // console.log(`DEBUG old tx ${tX} ty ${tY}`);\n let toggledOn = false;\n if (grid[x][y] === '*') {\n grid[x][y] = '.';\n total--;\n\n if (y > tY) outside--;\n if (y === tY && x >= tX) outside--;\n\n tX = total % n;\n tY = Math.floor(total / n);\n\n\n if (grid[tX][tY] === '*') {\n outside++;\n }\n } else {\n toggledOn = true;\n total++;\n\n if (grid[tX][tY] === '*') {\n outside--;\n }\n tX = total % n;\n tY = Math.floor(total / n);\n\n grid[x][y] = '*';\n\n if (y > tY) outside++;\n if (y === tY && x >= tX) outside++;\n \n }\n // console.log(`DEBUG toggledOn`, toggledOn);\n // console.log(`DEBUG new tx ${tX} ty ${tY}`);\n // console.log(`DEBUG total`, total);\n console.log(outside);\n }\n\n\n // return outside;\n};\n\nfunction main() {\n // let T = +readline();\n // for (let t = 1; t <= T; t++){\n let [n, m, q] = ra();\n let grid = [];\n for (let i = 0; i < n; i++) {\n grid.push(readline().split('')); \n }\n let queries = [];\n for (let i = 0; i < q; i++) {\n queries.push(ra()); \n }\n // console.log(`${calc(n, m, q, grid, queries)}`);\n calc(n, m, q, grid, queries);\n // }\n}\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "'use strict';\n\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst lines = []\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst L = process.env.DEBUG ? console.log : ()=>{};\n \nconst pcalc = function(){\n print(calc.apply(null, arguments)); }\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\n\n// SOLUTION\n \nconst calc = (n, m, q, A, Q)=>{\n let F = [];\n let SUM = 0;\n for (let i=0; i{\n let result = 0;\n for (let i=x; i>=0; i = (i & (i+1))-1){\n for (let j=y; j>=0; j = (j & (j+1))-1){\n result += F[i][j];\n }\n }\n return result;\n };\n let inc = (x, y, delta)=>{\n for (let i=x; i0){\n ans += sum(n-1, columns-1);\n }\n ans += sum(SUM%n-1, columns)\n ans -= sum(SUM%n-1, columns-1)\n print(SUM-ans)\n }\n};\n \nfunction main() {\n let T = 1||+readline()\n while (T--){\n let [n, m, q] = ra();\n let A = [];\n for (let i=0; i {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, m, q] = lines[l++].trim().split(' ').map(Number)\n const grid = lines.slice(l, l + n).map(str => str.trim().split(''))\n l += n\n const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))\n l += q\n output[i] = solve(n, m, grid, qs)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, m, grid, qs) {\n const es = []\n let total = 0\n for (let j = 0; j < m; j++) {\n es[j] = 0\n for (let i = 0; i < n; i++) {\n if (grid[i][j] === '.') es[j]++\n if (grid[i][j] === '*') total++\n }\n }\n return qs.map(([r, c]) => {\n r--\n c--\n //\n if (grid[r][c] === '.') {\n grid[r][c] = '*'\n es[c]--\n total++\n } else {\n grid[r][c] = '.'\n es[c]++\n total--\n }\n //\n const k = Math.floor(total / n)\n const rest = total % n\n let ans = k * n\n for (let j = 0; j < k; j++) {\n ans -= es[j]\n }\n for (let i = 0; i < rest; i++) {\n if (grid[i][k] === '*') ans++\n }\n // console.log(total, k, rest, ';', ans)\n return total - ans\n }).join('\\n')\n}\n"}], "negative_code": [{"source_code": "var n, m, q;\r\n var nmq = readline().split(' ').map(x=>parseInt(x));\r\n\r\n n = nmq[0];\r\n m = nmq[1];\r\n q = nmq[2];\r\n\r\n var desk = [];\r\n for (var i = 0; i < n; i++) {\r\n var row = readline().split('').map(x=> x == '.' ? 0 : 1);\r\n desk.push(row);\r\n }\r\n\r\n function hToC(h) {\r\n return desk[(h-1) % n][Math.floor((h-1) / n)];\r\n }\r\n\r\n function cToH(r, c) {\r\n return c * n + r + 1;\r\n }\r\n\r\n var head = 0;\r\n for (var r = 0; r < n; r++) {\r\n for (var c = 0; c < m; c++) {\r\n head += desk[r][c];\r\n }\r\n }\r\n var ops = 0;\r\n for (var i = 1; i <= head; i++) {\r\n if (!hToC(i)) {\r\n ops++;\r\n }\r\n }\r\n\r\n function remove(x, y) {\r\n desk[x][y] = 0;\r\n \r\n if (cToH(x, y) > head) {\r\n ops--;\r\n }\r\n if (cToH(x, y) < head && hToC(head)) {\r\n ops++;\r\n }\r\n head--;\r\n }\r\n\r\n function add(x, y) {\r\n head++;\r\n desk[x][y] = 1;\r\n if (cToH(x, y) == head) {\r\n } else {\r\n if (cToH(x, y) > head && !hToC(head)) {\r\n ops++;\r\n }\r\n if (hToC(head) && cToH(x, y) < head) {\r\n ops--;\r\n }\r\n }\r\n }\r\n\r\n for (var i = 0; i < q; i++) {\r\n var xy = readline().split(' ').map(x=>parseInt(x));\r\n var x = xy[0] - 1;\r\n var y = xy[1] - 1;\r\n if (desk[x][y]) {\r\n remove(x, y);\r\n } else {\r\n add(x, y);\r\n }\r\n\r\n print(ops);\r\n }"}], "src_uid": "9afb205f542c0d8ba4f7fa03faa617ae"} {"nl": {"description": "Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. 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 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 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 = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.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, b. Query p, b means that you need to perform the assignment ap = b. 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 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.", "output_spec": "Print m integers — 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": "\n\n\nconst segTree = [];\nconst inputArr = [];\n\nfunction updateSegElement(n, lastOpt) {\n if (lastOpt == 0) { //last operation was xor\n segTree[n] = segTree[2 * n + 1] | segTree[2 * n + 2];\n return 1; //or applied on this level, on next xor will applied\n } else {\n segTree[n] = segTree[2 * n + 1] ^ segTree[2 * n + 2];\n return 0; //xor applied on this level, on next or will applied\n }\n}\n\nfunction buildTree(n, s, e) {\n if (s == e) {\n segTree[n] = inputArr[s];\n return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied\n } else {\n const mid = Math.floor((s + e) / 2);\n //co => child operation applied xor or or, for xor return 0 for or return 1\n const col = buildTree(2 * n + 1, s, mid);\n const cor = buildTree(2 * n + 2, mid + 1, e);\n if (col != cor)\n throw new Error(\"calculation on previous level not similar\");\n return updateSegElement(n, col);\n }\n}\n\nfunction updateTree(n, s, e, idx, val) {\n if (s == e) {\n segTree[n] = val\n inputArr[idx] = val\n return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied\n } else {\n const mid = Math.floor((s + e) / 2);\n var lsOpt\n if (idx >= s && idx <= mid) {\n lsOpt = updateTree(2 * n + 1, s, mid, idx, val);\n } else {\n lsOpt = updateTree(2 * n + 2, mid + 1, e, idx, val);\n }\n return updateSegElement(n, lsOpt)\n }\n}\n\n\nfunction main(input) {\n if (input) {\n const inLine = input.split(\"\\n\")\n const input_arr = inLine[1].split(\" \")\n input_arr.forEach(e => {\n inputArr.push(parseInt(e, 0))\n });\n\n //Prepare segment tree\n for (var i = 0; i < inputArr.length * 2; i++) {\n segTree.push(0)\n }\n\n buildTree(0, 0, inputArr.length-1);\n for (var i = 2; i < inLine.length-1; i++) {\n const lineIn = inLine[i].split(\" \");\n updateTree(0, 0, inputArr.length - 1, parseInt(lineIn[0]) - 1, parseInt(lineIn[1]));\n process.stdout.write(\"\" + segTree[0] + \"\\n\");\n }\n }\n}\n\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n try {\n main(stdin_input);\n } catch (e) {\n console.log(\"Error occured\", e)\n }\n});"}], "negative_code": [{"source_code": "\n\n\nconst segTree = [];\nconst inputArr = [];\n\nfunction updateSegElement(n, lastOpt) {\n if (lastOpt == 0) { //last operation was xor\n segTree[n] = segTree[2 * n + 1] | segTree[2 * n + 2];\n return 1; //or applied on this level, on next xor will applied\n } else {\n segTree[n] = segTree[2 * n + 1] ^ segTree[2 * n + 2];\n return 0; //xor applied on this level, on next or will applied\n }\n}\n\nfunction buildTree(n, s, e) {\n if (s == e) {\n segTree[n] = inputArr[s];\n return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied\n } else {\n const mid = Math.floor((s + e) / 2);\n //co => child operation applied xor or or, for xor return 0 for or return 1\n const col = buildTree(2 * n + 1, s, mid);\n const cor = buildTree(2 * n + 2, mid + 1, e);\n if (col != cor)\n throw new Error(\"calculation on previous level not similar\");\n return updateSegElement(n, col);\n }\n}\n\nfunction updateTree(n, s, e, idx, val) {\n if (s == e) {\n segTree[n] = val\n inputArr[idx] = val\n return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied\n } else {\n const mid = Math.floor((s + e) / 2);\n var lsOpt\n if (idx >= s && idx <= mid) {\n lsOpt = updateTree(2 * n + 1, s, mid, idx, val);\n } else {\n lsOpt = updateTree(2 * n + 2, mid + 1, e, idx, val);\n }\n return updateSegElement(n, lsOpt)\n }\n}\n\n\nfunction main(input) {\n if (input) {\n const inLine = input.split(\"\\n\")\n const input_arr = inLine[1].split(\" \")\n input_arr.forEach(e => {\n inputArr.push(parseInt(e, 0))\n });\n\n //Prepare segment tree\n for (var i = 0; i < inputArr.length * 2; i++) {\n segTree.push(0)\n }\n\n buildTree(0, 0, inputArr.length-1);\n for (var i = 2; i < inLine.length; i++) {\n const lineIn = inLine[i].split(\" \");\n updateTree(0, 0, inputArr.length - 1, parseInt(lineIn[0]) - 1, parseInt(lineIn[1]));\n process.stdout.write(\"\" + segTree[0] + \"\\n\");\n }\n }\n}\n\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n try {\n main(stdin_input);\n } catch (e) {\n console.log(\"Error occured\", e)\n }\n});"}], "src_uid": "40d1ea98aa69865143d44432aed4dd7e"} {"nl": {"description": "A card pyramid of height $$$1$$$ is constructed by resting two cards against each other. For $$$h>1$$$, a card pyramid of height $$$h$$$ is constructed by placing a card pyramid of height $$$h-1$$$ onto a base. A base consists of $$$h$$$ pyramids of height $$$1$$$, and $$$h-1$$$ cards on top. For example, card pyramids of heights $$$1$$$, $$$2$$$, and $$$3$$$ look as follows: You start with $$$n$$$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?", "input_spec": "Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains a single integer $$$n$$$ ($$$1\\le n\\le 10^9$$$) — the number of cards. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^9$$$.", "output_spec": "For each test case output a single integer — the number of pyramids you will have constructed in the end.", "sample_inputs": ["5\n3\n14\n15\n24\n1"], "sample_outputs": ["1\n2\n1\n3\n0"], "notes": "NoteIn the first test, you construct a pyramid of height $$$1$$$ with $$$2$$$ cards. There is $$$1$$$ card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height $$$2$$$, with no cards remaining.In the third test, you build one pyramid of height $$$3$$$, with no cards remaining.In the fourth test, you build one pyramid of height $$$3$$$ with $$$9$$$ cards remaining. Then you build a pyramid of height $$$2$$$ with $$$2$$$ cards remaining. Then you build a final pyramid of height $$$1$$$ with no cards remaining.In the fifth test, one card is not enough to build any pyramids."}, "positive_code": [{"source_code": "'use strict';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(str => str.trim());\n\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nconst cache = [0, 2];\n\nfunction getMaximumPyramids(n) {\n let total = 0;\n let remaining = n;\n while (remaining >= 2) {\n getNextPyramid();\n total++;\n }\n return total;\n\n function getNextPyramid(h = 1) {\n let required = 2;\n while (required <= remaining){\n required = getRequiredCards(++h);\n }\n remaining -= cache[h-1];\n return h-1;\n }\n\n function getRequiredCards(h) {\n if (h == 1) return 2;\n else {\n const req = (h * 2) + (h - 1) + (cache[h - 1] || getRequiredCards(h - 1));\n cache[h] = req;\n return req;\n }\n }\n}\n\n\n\nfunction main() {\n const n = parseInt(readLine(), 10);\n for (let i = 0; i < n; i++) {\n const result = getMaximumPyramids(parseInt(readLine(), 10));\n console.log(result)\n }\n return;\n}\n"}, {"source_code": "// Input\n'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction mandatoryCards(n) { return (3*n*n + n)/2; }\n\nfunction processPyramids(remaining, nbPyramids) {\n if (remaining <= 1) return nbPyramids;\n var maxHeight = 1;\n while(mandatoryCards(maxHeight) <= remaining ) maxHeight++;\n return processPyramids(remaining-mandatoryCards(maxHeight-1), nbPyramids+1);\n}\n\n//main\nfunction main() {\n var nbOfTestCases = parseInt(readline());\n \n for (var i=0 ; i {\n let max = 0;\n let card = +line;\n if (first) {\n first = false\n } else {\n while (card > 1) {\n let maxCard = 2;\n let maxDeck = 1;\n if (maxCard === card) {\n card -= maxCard;\n max++;\n } else {\n while(true) {\n let newMaxDeck = maxDeck + 1;\n let newMaxCard = maxCard + maxDeck + newMaxDeck * 2;\n if (newMaxCard > card) {\n card -= maxCard;\n max++;\n break;\n } else {\n maxCard = newMaxCard;\n maxDeck = newMaxDeck;\n }\n }\n }\n }\n process.stdout.write(`${max}\\n`);\n }\n})"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar outputCount = 0;\n\t\tvar n = nextInt();\n\t\twhile(n >= 2){\n\t\t\tvar count = 1;\n\t\t\twhile(true){\n\t\t\t\tvar req = count * 2 + (count - 1);\n\t\t\t\tif(n < req){\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tn -= req;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\toutputCount++;\n\t\t}\n\t\toutput[i] = outputCount;\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const cases = readline();\n var i;\n for (i = 0; i < cases; i++) {\n const line = readline();\n var a = parseInt(line.split(\" \")[0]);\n\n solve(a);\n }\n}\n\nfunction solve(a) {\n var towers = 0;\n\n if (a < 2) {\n console.log(0);\n return;\n }\n\n while (a > 1) {\n var floor = 1;\n a -= 2;\n while (a >= cardsForFloor(floor+1)) {\n a -= cardsForFloor(floor+1);\n floor++;\n }\n towers++;\n }\n\n console.log(towers);\n}\n\nconst cache = [0, 2];\n\nfunction cardsForFloor(floor) {\n if (!(floor in cache)) {\n cache[floor] = ((floor)*2 + (floor -1));\n }\n\n return cache[floor];\n}"}, {"source_code": "//Card Constructions\n\nconst {EOL} = require('os');\n\nlet inp = '';\n\nprocess.stdin.on('data', c => inp += c);\n\nprocess.stdin.on('end', () => {\n let lines = inp.split(EOL);\n \n let t = +lines[0];\n\n let o = {};\n\n let f = (n) => {\n \t\n \tif(n < 2) {\n \t\treturn 0;\n \t}\n\n \tlet k = Math.sqrt(2 * n / 3);\n \tfor(let i = 1; i <= k + 1; i++) {\n\n \t\tlet r;\n\n \t\tif(o[i]) {\n \t\t\tr = o[i];\n \t\t} else {\n \t\t\to[i] = (i * ((3 * i) + 1)) / 2;\n \t\t\tr = o[i];\n \t\t}\n\n \t\tif(r > n) {\n \t\t\treturn 1 + f(n - (((3 * Math.pow(i - 1, 2)) + (i - 1)) / 2));\n \t\t}\n \t}\n }\n\n for(let i = 0; i < t; i++) {\n \tlet n = +lines[i + 1];\n\n \tprocess.stdout.write(f(n) + '\\n');\n }\n\n return;\n});"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i 2) {\n let sum = 2\n let pos = 0\n while (sum <= a) {\n pos++\n sum += 2 + (pos)*3\n // console.log(sum)\n }\n sum -= 2 + (pos)*3\n acc++\n a -= sum\n }\n if (a === 2) {\n acc++\n }\n console.log(acc)\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "// node template.js < A-small.in > A-small.out\n\nfunction main() {\n var tests = 1;\n tests = nextInt();\n\n for (let t = 1; t <= tests; t++) {\n let N = nextInt();\n let result = 0;\n while (N >= 2) {\n let cost = find(N);\n N -= cost;\n result++;\n }\n\n print(result);\n }\n}\n\nfunction find(N) {\n let l = 1, r = N, res = 0;\n while (l <= r) {\n let m = Math.floor((l+r) >> 1);\n if (3*m*(m+1)/2-m <= N) {\n l = m+1;\n res = 3*m*(m+1)/2-m;\n } else {\n r = m-1;\n }\n // console.log(l, r, m, 3*m*(m+1)/2-m);\n }\n return res;\n}\n\n// ------- Template ------------------\nfunction newTensor(dimensions, value) {\n let res = [];\n let dim = dimensions[0], subdim = dimensions.slice(1);\n if (subdim.length == 0) {\n for(let i = 0; i < dim; i++) {\n res.push(value);\n }\n } else {\n for(let i = 0; i < dim; i++) {\n res.push(newTensor(subdim, value));\n }\n }\n return res;\n}\n\nif (!String.prototype.startsWith) {\n Object.defineProperty(String.prototype, 'startsWith', {\n value: function(search, rawPos) {\n var pos = rawPos > 0 ? rawPos|0 : 0;\n return this.substring(pos, pos + search.length) === search;\n }\n });\n}\nif (!String.prototype.endsWith) {\n String.prototype.endsWith = function(search, this_len) {\n if (this_len === undefined || this_len > this.length) {\n this_len = this.length;\n }\n return this.substring(this_len - search.length, this_len) === search;\n };\n}\n\nvar curTokens = [], curToken = 0;\n\nfunction next() {\n while (curToken >= curTokens.length) {\n curTokens = readline().split(/[\\s]+/);\n curToken = 0;\n }\n return curTokens[curToken++];\n}\n\nfunction nextInt() {\n return parseInt(next());\n}\n\n// code for nodejs\nvar inputBuffer = '', curLine = 0;\n\nfunction readline() {\n return inputBuffer[curLine++];\n}\n\nfunction print(data) {\n process.stdout.write(data + '\\n');\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n inputBuffer += chunk;\n});\n\nprocess.stdin.on('end', function () {\n inputBuffer = inputBuffer.split(/[\\s]+/);\n main();\n});"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 3\n1 3\n100000 100000\n2 2\n\n\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r 1) {\n counter++;\n let h = 0;\n while((3*h*h + h) / 2 <= remaining) {\n h++;\n }\n h--;\n let usedCard = (3*h*h + h) / 2;\n remaining = remaining - usedCard;\n }\n\n console.log(counter);\n }\n}"}, {"source_code": "var t = parseInt(readline());\nfor (var tc = 0; tc < t; tc++) {\n var n = parseInt(readline());\n var currentFloor = 0;\n var nextFloor = 0;\n var count = 0;\n while (n >= 2) {\n var i = 1;\n if (n == 2) {\n count++;\n break;\n } else {\n while (nextFloor - i <= n) {\n currentFloor += i * 3;\n nextFloor = currentFloor + (i + 1) * 3;\n i++;\n }\n n -= currentFloor - i + 1;\n currentFloor = 0;\n nextFloor = 0;\n count++;\n }\n }\n print(count);\n}\n"}], "negative_code": [{"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n 3\n 14\n 15\n 24\n 1\n\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r value) {\n console.log(i-1);\n break;\n }\n }\n }\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 3\n1 3\n100000 100000\n2 2\n\n\n**/\n\nfunction main() {\n var range = readline();\n\n for(var r=0;r value) {\n console.log(counter);\n break;\n }\n\n counter++;\n }\n }\n}"}], "src_uid": "02062d1afe85e3639edddedceac304f4"} {"nl": {"description": "You are given a string $$$s$$$ consisting of lowercase Latin letters \"a\", \"b\" and \"c\" and question marks \"?\".Let the number of question marks in the string $$$s$$$ be $$$k$$$. Let's replace each question mark with one of the letters \"a\", \"b\" and \"c\". Here we can obtain all $$$3^{k}$$$ possible strings consisting only of letters \"a\", \"b\" and \"c\". For example, if $$$s = $$$\"ac?b?c\" then we can obtain the following strings: $$$[$$$\"acabac\", \"acabbc\", \"acabcc\", \"acbbac\", \"acbbbc\", \"acbbcc\", \"accbac\", \"accbbc\", \"accbcc\"$$$]$$$.Your task is to count the total number of subsequences \"abc\" in all resulting strings. Since the answer can be very large, print it modulo $$$10^{9} + 7$$$.A subsequence of the string $$$t$$$ is such a sequence that can be derived from the string $$$t$$$ after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string \"baacbc\" contains two subsequences \"abc\" — a subsequence consisting of letters at positions $$$(2, 5, 6)$$$ and a subsequence consisting of letters at positions $$$(3, 5, 6)$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ $$$(3 \\le n \\le 200\\,000)$$$ — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters \"a\", \"b\" and \"c\" and question marks\"?\".", "output_spec": "Print the total number of subsequences \"abc\" in all strings you can obtain if you replace all question marks with letters \"a\", \"b\" and \"c\", modulo $$$10^{9} + 7$$$.", "sample_inputs": ["6\nac?b?c", "7\n???????", "9\ncccbbbaaa", "5\na???c"], "sample_outputs": ["24", "2835", "0", "46"], "notes": "NoteIn the first example, we can obtain $$$9$$$ strings: \"acabac\" — there are $$$2$$$ subsequences \"abc\", \"acabbc\" — there are $$$4$$$ subsequences \"abc\", \"acabcc\" — there are $$$4$$$ subsequences \"abc\", \"acbbac\" — there are $$$2$$$ subsequences \"abc\", \"acbbbc\" — there are $$$3$$$ subsequences \"abc\", \"acbbcc\" — there are $$$4$$$ subsequences \"abc\", \"accbac\" — there is $$$1$$$ subsequence \"abc\", \"accbbc\" — there are $$$2$$$ subsequences \"abc\", \"accbcc\" — there are $$$2$$$ subsequences \"abc\". So, there are $$$2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24$$$ subsequences \"abc\" in total."}, "positive_code": [{"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn, init) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);\n if (b < a) return [];\n let arr = Array(b - a + 1).fill(0);\n if (init) init(arr);\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nlet MOD = 998244353\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + MOD) % MOD;\n}\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let n = +$(), s = $()\n let a = Array(n).fill(0), ab = Array(n).fill(0), abc = Array(n).fill(0), k = 1;\n let MOD = 1e9 + 7;\n if (s[0] == 'a') a[0] = 1\n else if (s[0] == '?') (a[0] = 1, k = 3)\n For(1, n - 1, i => {\n if (s[i] == 'a') {\n a[i] = (a[i - 1] + k) % MOD;\n ab[i] = ab[i - 1];\n abc[i] = abc[i - 1];\n } else if (s[i] == 'b') {\n a[i] = a[i - 1];\n ab[i] = (ab[i - 1] + a[i - 1]) % MOD;\n abc[i] = abc[i - 1];\n } else if (s[i] == 'c') {\n a[i] = a[i - 1];\n ab[i] = ab[i - 1]\n abc[i] = (abc[i - 1] + ab[i - 1]) % MOD;\n } else {\n a[i] = (3 * a[i - 1] + k) % MOD;\n ab[i] = (3 * ab[i - 1] + a[i - 1]) % MOD\n abc[i] = (3 * abc[i - 1] + ab[i - 1]) % MOD\n k = (k * 3) % MOD\n }\n })\n log(abc[n - 1])\n}\n"}], "negative_code": [], "src_uid": "45d8827bfee3afeeed79741a2c3b0a0f"} {"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 — 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, h, v, e (1 ≤ d, h, v, e ≤ 104), where: d — the diameter of your cylindrical cup, h — the initial level of water in the cup, v — the speed of drinking process from the cup in milliliters per second, e — 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 — 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 - 4. 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": "var input = readline().split(' ').map(Number);\n\nvar d = input[0];\nvar h = input[1];\nvar v = input[2];\nvar e = input[3];\n\nvar pi = Math.PI;\n\nvar t = - ((pi * Math.pow(d,2) * h) / (e * pi * Math.pow(d,2) - (4 * v)));\n\nif (t < 0) {\n\tprint('NO');\n} else {\n\tprint('YES');\n\tprint(t);\n}\n\n"}, {"source_code": "var a = readline().split(\" \");\nvar d = parseInt(a[0]);\nvar h = parseInt(a[1]);\nvar v = parseInt(a[2]);\nvar e = parseInt(a[3]);\n\nvar V = h * (((d * d) / 4) * Math.PI);\n\nvar RainSpeed = e * (((d * d) / 4) * Math.PI);\nif(RainSpeed >= v) print(\"NO\"); else{\n print(\"YES\");\n print(V / (v - RainSpeed));\n}"}, {"source_code": "var input = readline().split(' ').map(function (item) {\n return parseInt(item);\n});\nvar d = input[0], h = input[1], v = input[2], e = input[3];\nvar hDecRate = (4*v)/(Math.PI*d*d);\nif(hDecRate <= e){\n print(\"NO\");\n} else {\n var rate = hDecRate - e;\n print(\"YES\");\n print(h/rate);\n}"}, {"source_code": "function getInput() {\n var line = readline();\n var lines = [line];\n while (line = readline()) {\n lines.push(line);\n }\n return lines;\n}\n\nfunction main() {\n const input = getInput().pop().split(' ').map(item => Number(item));\n // diam\n const d = input[0];\n // height\n var h = input[1];\n // speed -\n const v = input[2];\n // speed +\n const e = input[3];\n \n // s = pi*r^2\n const s = Math.PI * Math.pow(d / 2, 2);\n const spOur = v / s;\n \n if (e > spOur) {\n print('NO')\n } else {\n var t = h / (spOur - e);\n print('YES')\n print(t)\n }\n}\n\nmain();"}], "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 × n 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 ≤ n ≤ 2000). Each of the next n lines contains n integers aij (0 ≤ aij ≤ 109) — 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, y1, x2, y2 (1 ≤ x1, y1, x2, y2 ≤ n), 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": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction printValues() {\n\tvar parts = [];\n\tfor (var i = 0; i < arguments.length; i += 2) {\n\t\tparts.push(arguments[i]+' = '+arguments[i+1]);\n\t}\n\tprint(parts.join(', '));\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tgrid = [];\n\tfor (var i = 0; i < n; ++i) {\n\t\tgrid.push(tokenizeIntegers(readline()));\n\t}\n\n\tfunction compute_total(r, c, dr, dc) {\n\t\tvar total = 0;\n\t\twhile (r >= 0 && r < n && c >= 0 && c < n) {\n\t\t\ttotal += grid[r][c];\n\t\t\tr += dr;\n\t\t\tc += dc;\n\t\t}\n\t\treturn total;\n\t}\n\tvar down_top = new Array(n), down_side = new Array(n),\n\t\tup_side = new Array(n), up_bottom = new Array(n);\n\tfor (var i = 0; i < n; ++i) {\n\t\tdown_top[i] = compute_total(0, i, 1, 1);\n\t\tdown_side[i] = compute_total(i, 0, 1, 1);\n\t\tup_side[i] = compute_total(i, 0, -1, 1);\n\t\tup_bottom[i] = compute_total(n-1, i, -1, 1);\n\t}\n\n\tbest_info = [[-1, -1, -1], [-1, -1, -1]];\n\tfor (var r = 0; r < n; ++r) {\n\t\tfor (var c = 0; c < n; ++c) {\n\t\t\tif (r < c) {\n\t\t\t\tvar down = down_top[c-r];\n\t\t\t} else {\n\t\t\t\tvar down = down_side[r-c];\n\t\t\t}\n\t\t\tif (r+c < n) {\n\t\t\t\tvar up = up_side[r+c];\n\t\t\t} else {\n\t\t\t\tvar up = up_bottom[r+c-n+1];\n\t\t\t}\n\t\t\tvar info = best_info[(r+c)%2],\n\t\t\t\ttotal = down + up - grid[r][c];\n\t\t\tif (total > info[0]) {\n\t\t\t\tinfo[0] = total;\n\t\t\t\tinfo[1] = r;\n\t\t\t\tinfo[2] = c;\n\t\t\t}\n\t\t}\n\t}\n\tprint(best_info[0][0] + best_info[1][0]);\n\tprint(best_info[0][1]+1, best_info[0][2]+1, best_info[1][1]+1, best_info[1][2]+1);\n}\n\nmain();\n"}], "negative_code": [], "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$$$) — 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": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n let tmp=0, q=0, lrds=[];\n\n rl.on('line', (input) => {\n if (tmp==0) {q=Number(input); tmp++;}\n else {\n if (tmp<=q){\n let lrd=input.split(' ').map(a=>{return Number(a)}); \n lrds.push(lrd);\n tmp++;}\n }\n if (tmp>q){ rl.close(); therest();}\n return 0;}\n);\n\nlet therest=function() {\n\n let res=[];\n for (let i=0; ir) {res.push(d);\n console.log(d);}\n else {\n if (r%d==0) console.log(r+d);\n else console.log(Math.ceil(r/d)*d)\n }\n//console.log(lrds[i]);\n\n }\n//console.log(T, pairs)\n}\n//console.log(lngth, str);}\n\n /*\n rl.question('What do you think of Node.js? ', (answer) => {\n // TODO: Log the answer in a database\n console.log(`Thank you for your valuable feedback: ${answer}`);\n \n rl.close();\n });*/"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet l = 0;\nlet n = 0\n\nrl.on('line', (input) => {\n if (l === 0) {\n n = parseInt(input)\n } else {\n if (l === n)\n rl.close();\n\n arr = input.split(' ').map(function (item) {\n return parseInt(item, 10);\n });\n\n if(arr[0]>arr[2]){\n console.log(arr[2])\n } else if(arr[1] {\n if (l === 0) {\n n = parseInt(input)\n } else {\n if (l === n)\n rl.close();\n\n arr = input.split(' ').map(function (item) {\n return parseInt(item, 10);\n });\n\n if(arr[0]>arr[2]){\n console.log(arr[2])\n } else if(arr[1] {\n if (l === 0) {\n n = parseInt(input)\n } else {\n if (l === n)rl.close();\n arr = input.split(' ').map(function (item) {\n return parseInt(item, 10);\n });\n\n if(arr[0]>arr[2]){\n console.log(arr[2])\n } else if(arr[1]c || bc || bd){print(d);}\n\t\telse{r++;print(Math.ceil(r/d)*d);}\n\t}\n"}, {"source_code": "function main() {\n var q = +readline();\n r = [];\n\n for(var i = 0; i < q; i++) {\n var t = readline().split(' ');\n r.push({ l: +t[0], r: +t[1], d: +t[2]});\n }\n \n var res = [];\n\n r.forEach(function(item) {\n \n if(item.l > item.d) {\n res.push(item.d);\n }\n else {\n var f = Math.ceil(item.r / item.d);\n if(item.r % item.d == 0)\n f++;\n res.push(f * item.d);\n }\n });\n\n res.forEach(function(g) {\n print(g);\n })\n}\n\nmain();"}, {"source_code": "var q = +readline();\n\nvar i = 0;\nvar arr = [];\nwhile(i < q) {\n\tarr[i] = readline().split(' ');\n\ti++;\n}\ni = 0;\n\nwhile(i < q) {\n arr[i][0] = +arr[i][0];\n arr[i][1] = +arr[i][1];\n arr[i][2] = +arr[i][2];\n\n\tif((arr[i][2] >= arr[i][0] && arr[i][2] <= arr[i][1]) && (arr[i][2] >= arr[i][0] || arr[i][2] <= arr[i][0])) {\n\t\tprint(+(+arr[i][1] + (+arr[i][2] - +arr[i][1]%+arr[i][2])));\n } else {\n\t\tprint(arr[i][2]);\n }\n\n i++;\n}"}, {"source_code": "var q = +readline();\n\nvar i = 0;\nvar arr = [];\nwhile(i < q) {\n\tarr[i] = readline().split(' ');\n\ti++;\n}\ni = 0;\n\nwhile(i < q) {\n arr[i][0] = +arr[i][0];\n arr[i][1] = +arr[i][1];\n arr[i][2] = +arr[i][2];\n\n\tif(arr[i][2] < arr[i][0] || arr[i][2] > arr[i][1]) {\n\t\tprint(arr[i][2]);\n } else {\n print(+(+arr[i][1] + (+arr[i][2] - +arr[i][1]%+arr[i][2])));\n }\n\n i++;\n}"}, {"source_code": "var q = parseInt(readline());\n\nfor (var i = 0; i < q; i++) {\n var _ = readline().split(' ').map(Number);\n\n var l = _[0];\n var r = _[1];\n var d = _[2];\n\n if (d < l || d > r) {\n print(d);\n } else {\n var minToBreakFree = Math.floor(r / d);\n print(d * (minToBreakFree + 1));\n }\n}\n"}, {"source_code": "var q = readline()\nfor(var i=0; i r) {\n print(d)\n } else {\n print((Math.floor(r/d) + 1) * d)\n }\n}"}, {"source_code": "var n = readline();\nfor(i=0;i r) {\n print(d)\n } else {\n print((Math.floor(r/d) + 1) * d)\n }\n}"}, {"source_code": "function calc(l, r, d) {\n if (d < l || d > r) {\n return d;\n }\n \n return d * Math.ceil(r / d) === r ? r + d : d * Math.ceil(r / d);\n}\n\nvar q = parseInt(readline());\nvar lrd,l,r,d;\n\nfor (var i = 0; i< q; i++) {\n lrd = readline().split(\" \");\n // print(lrd);\n l = parseInt(lrd[0]);\n r = parseInt(lrd[1]);\n d = parseInt(lrd[2]);\n \n print(calc(l, r, d));\n}\n"}], "negative_code": [{"source_code": "//var input = readline()\nvar t = parseInt(readline())\n\nfor(var i=0; ic) print(c)\n else if(a == c) print(s)\n else {\n if(s%c == 0) {\n print(s)\n }\n }\n}\n\n\n//"}, {"source_code": "var q=parseInt(readline());\n\t\tfor(var i=0;id){\n\t\t\t\tvar y=l-1;\n\t\t\twhile(y%d!==0){y--;}print(y);}\n\t\t\t}\n\t\t"}, {"source_code": "\t\tvar q=parseInt(readline());\n\t\tfor(var i=0;i arr[i][0]) {\n\t\tprint(arr[i][2]*2);\n } else if(arr[i][2] == arr[i][0] && arr[i][1]%arr[i][0] === 0) {\n\t\tprint((arr[i][1]+arr[i][2]));\n } else {\n\t\tprint(arr[i][2]);\n }\n\n\n i++;\n}"}, {"source_code": "var q = +readline();\n\nvar i = 0;\nvar arr = [];\n\nwhile(i < q) {\n\tarr[i] = readline().split(' ');\n\ti++;\n}\ni = 0;\n\nwhile(i < q) {\narr[i][0] = +arr[i][0];\narr[i][1] = +arr[i][1];\narr[i][2] = +arr[i][2];\n\tif(arr[i][2] == arr[i][1]) {\n\t\tprint(arr[i][2]*2);\n } else if(arr[i][2] == arr[i][0] && arr[i][1]%arr[i][0] === 0) {\n\t\tprint((arr[i][1]+arr[i][2]));\n } else if(!(arr[i][2] < arr[i][0]) && arr[i][1]%arr[i][0] !== 0) {\n\t\tprint(+(+arr[i][1] + (+arr[i][2] - +arr[i][1]%+arr[i][2])));\n } else {\n\t\tprint(arr[i][2]);\n }\n\n\n i++;\n}"}, {"source_code": "var q = +readline();\n\nvar i = 0;\nvar arr = [];\n\nwhile(i < q) {\n\tarr[i] = readline().split(' ');\n\ti++;\n}\ni = 0;\n\nwhile(i < q) {\narr[i][0] = +arr[i][0];\narr[i][1] = +arr[i][1];\narr[i][2] = +arr[i][2];\n\tif(arr[i][2] <= arr[i][1] && arr[i][2] > arr[i][0]) {\n\t\tprint(arr[i][2]*2);\n } else if(arr[i][2] == arr[i][0] && arr[i][1]%arr[i][0] === 0) {\n\t\tprint((arr[i][1]+arr[i][2]));\n } else if(!(arr[i][2] < arr[i][0]) && arr[i][1]%arr[i][0] !== 0) {\n\t\tprint(+(+arr[i][1] + (+arr[i][2] - +arr[i][1]%+arr[i][2])));\n } else {\n\t\tprint(arr[i][2]);\n }\n\n\n i++;\n}"}, {"source_code": "var q = +readline();\n\nvar i = 0;\nvar arr = [];\n\nwhile(i < q) {\n\tarr[i] = readline().split(' ');\n\ti++;\n}\ni = 0;\n\nwhile(i < q) {\narr[i][0] = +arr[i][0];\narr[i][1] = +arr[i][1];\narr[i][2] = +arr[i][2];\n\tif(arr[i][2] >= arr[i][1] && arr[i][2] > arr[i][0]) {\n\t\tprint(arr[i][2]*2);\n } else if(arr[i][2] == arr[i][0] && arr[i][1]%arr[i][0] === 0) {\n\t\tprint((arr[i][1]+arr[i][2]));\n } else if(!(arr[i][2] < arr[i][0]) && arr[i][1]%arr[i][0] !== 0) {\n\t\tprint(+(+arr[i][1] + (+arr[i][2] - +arr[i][1]%+arr[i][2])));\n } else {\n\t\tprint(arr[i][2]);\n }\n\n\n i++;\n}"}, {"source_code": "var q = readline()\nfor(var i=0; i r) {\n print(d)\n } else {\n print((Math.floor(r/d) + 1) * d)\n }\n}"}, {"source_code": "var n = readline().split(' ');\nfor(i=0;ir) && (j%d == 0)) {\n print(j + \"\\n\");\n }\n }\n}"}, {"source_code": "var n = readline().split(' ');\nfor(i=0;i r) {\n print(d)\n } else {\n print((Math.floor(r/d) + 1) * d)\n }\n}"}, {"source_code": "var n = readline().split(' ');\nfor(i=0;ir) && (j%d == 0)) {\n print(j);\n }\n }\n}"}, {"source_code": "var n = readline().split(' ');\nfor(i=0;ir) && (j%d == 0)) {\n print(j + \"\\n\");\n break;\n }\n }\n}"}], "src_uid": "091e91352973b18040e2d57c46f2bf8a"} {"nl": {"description": "This is the easy version of the problem. The only difference is that in this version $$$k = 0$$$.There is an array $$$a_1, a_2, \\ldots, a_n$$$ of $$$n$$$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.Moreover, it is allowed to do at most $$$k$$$ such operations before the division: choose a number in the array and change its value to any positive integer. But in this version $$$k = 0$$$, so it is not important.What is the minimum number of continuous segments you should use if you will make changes optimally?", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 1000)$$$  — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$k = 0$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^7$$$). It's 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  — the answer to the problem.", "sample_inputs": ["3\n\n5 0\n\n18 6 2 4 1\n\n5 0\n\n6 8 1 24 8\n\n1 0\n\n1"], "sample_outputs": ["3\n2\n1"], "notes": "NoteIn the first test case the division may be as follows: $$$[18, 6]$$$ $$$[2, 4]$$$ $$$[1]$$$ "}, "positive_code": [{"source_code": "// Generated by CoffeeScript 2.4.1\nvar A, K, N, _, a, dp, i, j, k, l, len, len1, len2, m, min, n, nr, nrs, o, p, q, ref, ref1, ref2, sq, squares, used, xxx;\n\nnrs = function() {\n var i, k, len, ref, results;\n ref = readline().split(' ');\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(parseInt(i));\n }\n return results;\n};\n\nnr = function() {\n return nrs()[0];\n};\n\n\nfunction range(start, stop, step) {\n if (stop == null) {\n stop = start || 0\n start = 0\n }\n if (!step) step = stop < start ? -1 : 1\n\n var length = Math.max(Math.ceil((stop - start) / step), 0)\n var range = Array(length) \n\n for (var idx = 0; idx < length; idx++, start += step) range[idx] = start\n\n return range;\n}\n;\n\nmin = function(lst) {\n var best, item, k, len;\n best = lst[0];\n for (k = 0, len = lst.length; k < len; k++) {\n item = lst[k];\n best = item < best ? item : best;\n }\n return best;\n};\n\nn = 10000000;\n\nsquares = (function() {\n var k, results;\n results = [];\n for (i = k = 1; k < 3162; i = ++k) {\n results.push(i * i);\n }\n return results;\n})();\n\np = (function() {\n var k, ref, results;\n results = [];\n for (i = k = 0, ref = n + 1; (0 <= ref ? k < ref : k > ref); i = 0 <= ref ? ++k : --k) {\n results.push(i);\n }\n return results;\n})();\n\nfor (i = k = 1, ref = n + 1; (1 <= ref ? k < ref : k > ref); i = 1 <= ref ? ++k : --k) {\n if (p[i] === i) {\n for (l = 0, len = squares.length; l < len; l++) {\n sq = squares[l];\n if (i * sq > n) {\n break;\n }\n p[i * sq] = i;\n }\n }\n}\n\nfor (_ = m = 0, ref1 = nr(); (0 <= ref1 ? m < ref1 : m > ref1); _ = 0 <= ref1 ? ++m : --m) {\n xxx = nrs();\n N = xxx[0];\n K = xxx[1];\n A = (function() {\n var len1, o, ref2, results;\n ref2 = nrs();\n results = [];\n for (o = 0, len1 = ref2.length; o < len1; o++) {\n a = ref2[o];\n results.push(p[a]);\n }\n return results;\n })();\n dp = (function() {\n var len1, o, ref2, results;\n ref2 = range(K + 1);\n results = [];\n for (o = 0, len1 = ref2.length; o < len1; o++) {\n _ = ref2[o];\n results.push(N);\n }\n return results;\n })();\n dp[0] = 1;\n used = (function() {\n var o, ref2, results;\n results = [];\n for (_ = o = 0, ref2 = K + 1; (0 <= ref2 ? o < ref2 : o > ref2); _ = 0 <= ref2 ? ++o : --o) {\n results.push({});\n }\n return results;\n })();\n for (o = 0, len1 = A.length; o < len1; o++) {\n a = A[o];\n ref2 = range(K, -1, -1);\n for (q = 0, len2 = ref2.length; q < len2; q++) {\n j = ref2[q];\n if (dp[j] === N) {\n continue;\n }\n if (a in used[j]) {\n if (j < K && dp[j + 1] > dp[j]) {\n dp[j + 1] = dp[j];\n used[j + 1] = used[j];\n }\n dp[j] += 1;\n used[j] = {};\n }\n used[j][a] = 1;\n }\n }\n print(min(dp));\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiamltbTg5LmpzIiwic291cmNlUm9vdCI6Ii4uIiwic291cmNlcyI6WyJjb2ZmZWVcXGppbW04OS5jb2ZmZWUiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLElBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxFQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxJQUFBLEVBQUEsSUFBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsQ0FBQSxFQUFBLEVBQUEsRUFBQSxHQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxJQUFBLEVBQUEsRUFBQSxFQUFBLE9BQUEsRUFBQSxJQUFBLEVBQUE7O0FBQUEsR0FBQSxHQUFNLFFBQUEsQ0FBQSxDQUFBO0FBQUcsTUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxHQUFBLEVBQUE7QUFBVztBQUFBO0VBQUEsS0FBQSxxQ0FBQTs7aUJBQVgsUUFBQSxDQUFTLENBQVQ7RUFBVyxDQUFBOztBQUFkOztBQUNOLEVBQUEsR0FBSyxRQUFBLENBQUEsQ0FBQTtTQUFHLEdBQUEsQ0FBQSxDQUFNLENBQUEsQ0FBQTtBQUFUOztBQUVMOzs7Ozs7Ozs7Ozs7Ozs7OztBQWlCQSxHQUFBLEdBQU0sUUFBQSxDQUFDLEdBQUQsQ0FBQTtBQUNMLE1BQUEsSUFBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUE7RUFBQSxJQUFBLEdBQU8sR0FBSSxDQUFBLENBQUE7RUFDWCxLQUFBLHFDQUFBOztJQUNDLElBQUEsR0FBVSxJQUFBLEdBQU8sSUFBVixHQUFvQixJQUFwQixHQUE4QjtFQUR0QztTQUVBO0FBSks7O0FBTU4sQ0FBQSxHQUFJOztBQUNKLE9BQUE7O0FBQWU7RUFBQSxLQUFTLDRCQUFUO2lCQUFKLENBQUEsR0FBRTtFQUFFLENBQUE7Ozs7QUFFZixDQUFBOztBQUFPO0VBQUEsS0FBUyxnRkFBVDtpQkFBRjtFQUFFLENBQUE7Ozs7QUFDUCxLQUFTLGdGQUFUO0VBQ0MsSUFBRyxDQUFFLENBQUEsQ0FBQSxDQUFGLEtBQVEsQ0FBWDtJQUNDLEtBQUEseUNBQUE7O01BQ0MsSUFBRyxDQUFBLEdBQUUsRUFBRixHQUFPLENBQVY7QUFBaUIsY0FBakI7O01BQ0EsQ0FBRSxDQUFBLENBQUEsR0FBRSxFQUFGLENBQUYsR0FBVTtJQUZYLENBREQ7O0FBREQ7O0FBTUEsS0FBUyxvRkFBVDtFQUNDLEdBQUEsR0FBTSxHQUFBLENBQUE7RUFDTixDQUFBLEdBQUksR0FBSSxDQUFBLENBQUE7RUFDUixDQUFBLEdBQUksR0FBSSxDQUFBLENBQUE7RUFDUixDQUFBOztBQUFVO0FBQUE7SUFBQSxLQUFBLHdDQUFBOzttQkFBTCxDQUFFLENBQUEsQ0FBQTtJQUFHLENBQUE7OztFQUNWLEVBQUE7O0FBQVE7QUFBQTtJQUFBLEtBQUEsd0NBQUE7O21CQUFGO0lBQUUsQ0FBQTs7O0VBQ1IsRUFBRyxDQUFBLENBQUEsQ0FBSCxHQUFRO0VBQ1IsSUFBQTs7QUFBVztJQUFBLEtBQVMscUZBQVQ7bUJBQUgsQ0FBQTtJQUFHLENBQUE7OztFQUNYLEtBQUEscUNBQUE7O0FBQ0M7SUFBQSxLQUFBLHdDQUFBOztNQUNDLElBQUcsRUFBRyxDQUFBLENBQUEsQ0FBSCxLQUFTLENBQVo7QUFBbUIsaUJBQW5COztNQUNBLElBQUcsQ0FBQSxJQUFLLElBQUssQ0FBQSxDQUFBLENBQWI7UUFDQyxJQUFHLENBQUEsR0FBSSxDQUFKLElBQVUsRUFBRyxDQUFBLENBQUEsR0FBSSxDQUFKLENBQUgsR0FBWSxFQUFHLENBQUEsQ0FBQSxDQUE1QjtVQUNDLEVBQUcsQ0FBQSxDQUFBLEdBQUksQ0FBSixDQUFILEdBQVksRUFBRyxDQUFBLENBQUE7VUFDZixJQUFLLENBQUEsQ0FBQSxHQUFJLENBQUosQ0FBTCxHQUFjLElBQUssQ0FBQSxDQUFBLEVBRnBCOztRQUdBLEVBQUcsQ0FBQSxDQUFBLENBQUgsSUFBUztRQUNULElBQUssQ0FBQSxDQUFBLENBQUwsR0FBVSxDQUFBLEVBTFg7O01BTUEsSUFBSyxDQUFBLENBQUEsQ0FBRyxDQUFBLENBQUEsQ0FBUixHQUFhO0lBUmQ7RUFERDtFQVVBLEtBQUEsQ0FBTSxHQUFBLENBQUksRUFBSixDQUFOO0FBbEJEIiwic291cmNlc0NvbnRlbnQiOlsibnJzID0gLT4gcGFyc2VJbnQgaSBmb3IgaSBpbiByZWFkbGluZSgpLnNwbGl0ICcgJ1xubnIgPSAtPiBucnMoKVswXVxuXG5gYGBcbmZ1bmN0aW9uIHJhbmdlKHN0YXJ0LCBzdG9wLCBzdGVwKSB7XG4gIGlmIChzdG9wID09IG51bGwpIHtcbiAgICBzdG9wID0gc3RhcnQgfHwgMFxuICAgIHN0YXJ0ID0gMFxuICB9XG4gIGlmICghc3RlcCkgc3RlcCA9IHN0b3AgPCBzdGFydCA/IC0xIDogMVxuXG4gIHZhciBsZW5ndGggPSBNYXRoLm1heChNYXRoLmNlaWwoKHN0b3AgLSBzdGFydCkgLyBzdGVwKSwgMClcbiAgdmFyIHJhbmdlID0gQXJyYXkobGVuZ3RoKSBcblxuICBmb3IgKHZhciBpZHggPSAwOyBpZHggPCBsZW5ndGg7IGlkeCsrLCBzdGFydCArPSBzdGVwKSByYW5nZVtpZHhdID0gc3RhcnRcblxuICByZXR1cm4gcmFuZ2U7XG59XG5gYGBcblxubWluID0gKGxzdCkgLT5cblx0YmVzdCA9IGxzdFswXVxuXHRmb3IgaXRlbSBpbiBsc3Rcblx0XHRiZXN0ID0gaWYgaXRlbSA8IGJlc3QgdGhlbiBpdGVtIGVsc2UgYmVzdCBcblx0YmVzdCBcblxubiA9IDEwMDAwMDAwXG5zcXVhcmVzID0gKGkqaSBmb3IgaSBpbiBbMS4uLjMxNjJdKVxuXG5wID0gKGkgZm9yIGkgaW4gWzAuLi5uKzFdKVxuZm9yIGkgaW4gWzEuLi5uKzFdXG5cdGlmIHBbaV0gPT0gaVxuXHRcdGZvciBzcSBpbiBzcXVhcmVzXG5cdFx0XHRpZiBpKnNxID4gbiB0aGVuIGJyZWFrXG5cdFx0XHRwW2kqc3FdID0gaVxuXG5mb3IgXyBpbiBbMC4uLm5yKCldXG5cdHh4eCA9IG5ycygpXG5cdE4gPSB4eHhbMF1cblx0SyA9IHh4eFsxXVxuXHRBID0gKHBbYV0gZm9yIGEgaW4gbnJzKCkpXG5cdGRwID0gKE4gZm9yIF8gaW4gcmFuZ2UgSysxKVxuXHRkcFswXSA9IDFcblx0dXNlZCA9ICh7fSBmb3IgXyBpbiBbMC4uLksrMV0pXG5cdGZvciBhIGluIEFcblx0XHRmb3IgaiBpbiByYW5nZSBLLC0xLC0xXG5cdFx0XHRpZiBkcFtqXSA9PSBOIHRoZW4gY29udGludWUgXG5cdFx0XHRpZiBhIG9mIHVzZWRbal1cblx0XHRcdFx0aWYgaiA8IEsgYW5kIGRwW2ogKyAxXSA+IGRwW2pdXG5cdFx0XHRcdFx0ZHBbaiArIDFdID0gZHBbal1cblx0XHRcdFx0XHR1c2VkW2ogKyAxXSA9IHVzZWRbal1cblx0XHRcdFx0ZHBbal0gKz0gMVxuXHRcdFx0XHR1c2VkW2pdID0ge31cblx0XHRcdHVzZWRbal1bYV0gPSAxXG5cdHByaW50IG1pbiBkcFxuIl19\n//# sourceURL=c:\\github\\2021\\009-CodeForces#708\\1497E2\\coffee\\jimm89.coffee"}, {"source_code": "// Generated by CoffeeScript 2.4.1\n // Problem: hittar inte något kommando som kan exekvera\nvar N, _, f, k, len, nr, nrs, p2, prepare, randint, ref,\n indexOf = [].indexOf;\n\nnrs = function() {\n var i, k, len, ref, results;\n ref = readline().split(' ');\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(parseInt(i));\n }\n return results;\n};\n\nnr = function() {\n return nrs()[0];\n};\n\n\nfunction range(start, stop, step) {\n if (stop == null) {\n stop = start || 0\n start = 0\n }\n if (!step) step = stop < start ? -1 : 1\n\n var length = Math.max(Math.ceil((stop - start) / step), 0)\n var range = Array(length)\n\n for (var idx = 0; idx < length; idx++, start += step) range[idx] = start\n\n return range;\n}\n;\n\n//##################################################\nN = 3162;\n\np2 = [];\n\nrandint = function(min, max) {\n return min + Math.floor(Math.random() * (max - min + 1));\n};\n\nprepare = function() {\n var c, i, j, k, l, len, len1, len2, m, p, ref, ref1, ref2, results;\n p = (function() {\n var k, len, ref, results;\n ref = range(N);\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(1);\n }\n return results;\n })();\n ref = range(2, N);\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n if (p[i]) {\n ref1 = range(2 * i, N, i);\n for (l = 0, len1 = ref1.length; l < len1; l++) {\n j = ref1[l];\n p[j] = 0;\n }\n }\n }\n ref2 = range(2, N);\n results = [];\n for (m = 0, len2 = ref2.length; m < len2; m++) {\n c = ref2[m];\n if (p[c] === 1) {\n results.push(c * c);\n }\n }\n return results;\n};\n\nf = function(a) {\n var ans, hash, k, kl, l, len, len1, q, r, r0;\n ans = 1;\n kl = {};\n hash = {};\n for (k = 0, len = a.length; k < len; k++) {\n r0 = a[k];\n if (indexOf.call(hash, r0) >= 0) {\n r = hash[r0];\n } else {\n r = r0;\n for (l = 0, len1 = p2.length; l < len1; l++) {\n q = p2[l];\n if (r < q) {\n break;\n }\n while (r % q === 0) {\n r = Math.floor(r / q);\n }\n }\n hash[r0] = r;\n }\n if (r in kl) {\n ans += 1;\n kl = {};\n }\n kl[r] = 1;\n }\n return ans;\n};\n\np2 = prepare();\n\nref = range(nr());\nfor (k = 0, len = ref.length; k < len; k++) {\n _ = ref[k];\n _ = nrs();\n print(f(nrs()));\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiamF2YXNjcmlwdC5qcyIsInNvdXJjZVJvb3QiOiIuLiIsInNvdXJjZXMiOlsiY29mZmVlXFxqYXZhc2NyaXB0LmNvZmZlZSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7QUFBQSxJQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsRUFBQSxFQUFBLEdBQUEsRUFBQSxFQUFBLEVBQUEsT0FBQSxFQUFBLE9BQUEsRUFBQSxHQUFBO0VBQUE7O0FBQ0EsR0FBQSxHQUFNLFFBQUEsQ0FBQSxDQUFBO0FBQUcsTUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxHQUFBLEVBQUE7QUFBWTtBQUFBO0VBQUEsS0FBQSxxQ0FBQTs7aUJBQVgsUUFBQSxDQUFTLENBQVQ7RUFBVyxDQUFBOztBQUFmOztBQUNOLEVBQUEsR0FBSyxRQUFBLENBQUEsQ0FBQTtTQUFHLEdBQUEsQ0FBQSxDQUFNLENBQUEsQ0FBQTtBQUFUOztBQUVMOzs7Ozs7Ozs7Ozs7Ozs7Q0FKQTs7O0FBc0JBLENBQUEsR0FBSTs7QUFDSixFQUFBLEdBQUs7O0FBRUwsT0FBQSxHQUFVLFFBQUEsQ0FBQyxHQUFELEVBQU0sR0FBTixDQUFBO1NBQWMsR0FBQSxHQUFNLElBQUksQ0FBQyxLQUFMLENBQVcsSUFBSSxDQUFDLE1BQUwsQ0FBQSxDQUFBLEdBQWdCLENBQUMsR0FBQSxHQUFNLEdBQU4sR0FBWSxDQUFiLENBQTNCO0FBQXBCOztBQUVWLE9BQUEsR0FBVSxRQUFBLENBQUEsQ0FBQTtBQUNULE1BQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxJQUFBLEVBQUEsSUFBQSxFQUFBO0VBQUEsQ0FBQTs7QUFBTztBQUFBO0lBQUEsS0FBQSxxQ0FBQTs7bUJBQUY7SUFBRSxDQUFBOzs7QUFDUDtFQUFBLEtBQUEscUNBQUE7O0lBQ0MsSUFBRyxDQUFFLENBQUEsQ0FBQSxDQUFMO0FBQ0M7TUFBQSxLQUFBLHdDQUFBOztRQUNDLENBQUUsQ0FBQSxDQUFBLENBQUYsR0FBTztNQURSLENBREQ7O0VBREQ7QUFJSTtBQUFBO0VBQUEsS0FBQSx3Q0FBQTs7UUFBd0IsQ0FBRSxDQUFBLENBQUEsQ0FBRixLQUFNO21CQUFsQyxDQUFBLEdBQUU7O0VBQUUsQ0FBQTs7QUFOSzs7QUFRVixDQUFBLEdBQUksUUFBQSxDQUFDLENBQUQsQ0FBQTtBQUNILE1BQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUEsRUFBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUE7RUFBQSxHQUFBLEdBQU07RUFDTixFQUFBLEdBQUssQ0FBQTtFQUNMLElBQUEsR0FBTyxDQUFBO0VBQ1AsS0FBQSxtQ0FBQTs7SUFDQyxJQUFHLGFBQU0sSUFBTixFQUFBLEVBQUEsTUFBSDtNQUNDLENBQUEsR0FBSSxJQUFLLENBQUEsRUFBQSxFQURWO0tBQUEsTUFBQTtNQUdDLENBQUEsR0FBSTtNQUNKLEtBQUEsc0NBQUE7O1FBQ0MsSUFBRyxDQUFBLEdBQUksQ0FBUDtBQUNDLGdCQUREOztBQUVBLGVBQU0sQ0FBQSxHQUFJLENBQUosS0FBUyxDQUFmO1VBQ0MsZUFBQSxJQUFNO1FBRFA7TUFIRDtNQUtBLElBQUssQ0FBQSxFQUFBLENBQUwsR0FBVyxFQVRaOztJQVVBLElBQUcsQ0FBQSxJQUFLLEVBQVI7TUFDQyxHQUFBLElBQU87TUFDUCxFQUFBLEdBQUssQ0FBQSxFQUZOOztJQUdBLEVBQUcsQ0FBQSxDQUFBLENBQUgsR0FBUTtFQWRUO1NBZUE7QUFuQkc7O0FBcUJKLEVBQUEsR0FBSyxPQUFBLENBQUE7O0FBQ0w7QUFBQSxLQUFBLHFDQUFBOztFQUNDLENBQUEsR0FBSSxHQUFBLENBQUE7RUFDSixLQUFBLENBQU0sQ0FBQSxDQUFFLEdBQUEsQ0FBQSxDQUFGLENBQU47QUFGRCIsInNvdXJjZXNDb250ZW50IjpbIiMgUHJvYmxlbTogaGl0dGFyIGludGUgbsOlZ290IGtvbW1hbmRvIHNvbSBrYW4gZXhla3ZlcmFcclxubnJzID0gLT4gKHBhcnNlSW50IGkgZm9yIGkgaW4gcmVhZGxpbmUoKS5zcGxpdCAnICcpXHJcbm5yID0gLT4gbnJzKClbMF1cclxuXHJcbmBgYFxyXG5mdW5jdGlvbiByYW5nZShzdGFydCwgc3RvcCwgc3RlcCkge1xyXG4gIGlmIChzdG9wID09IG51bGwpIHtcclxuICAgIHN0b3AgPSBzdGFydCB8fCAwXHJcbiAgICBzdGFydCA9IDBcclxuICB9XHJcbiAgaWYgKCFzdGVwKSBzdGVwID0gc3RvcCA8IHN0YXJ0ID8gLTEgOiAxXHJcblxyXG4gIHZhciBsZW5ndGggPSBNYXRoLm1heChNYXRoLmNlaWwoKHN0b3AgLSBzdGFydCkgLyBzdGVwKSwgMClcclxuICB2YXIgcmFuZ2UgPSBBcnJheShsZW5ndGgpXHJcblxyXG4gIGZvciAodmFyIGlkeCA9IDA7IGlkeCA8IGxlbmd0aDsgaWR4KyssIHN0YXJ0ICs9IHN0ZXApIHJhbmdlW2lkeF0gPSBzdGFydFxyXG5cclxuICByZXR1cm4gcmFuZ2U7XHJcbn1cclxuYGBgXHJcbiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI1xyXG5cclxuTiA9IDMxNjJcclxucDIgPSBbXVxyXG5cclxucmFuZGludCA9IChtaW4sIG1heCkgLT4gbWluICsgTWF0aC5mbG9vciBNYXRoLnJhbmRvbSgpICogKG1heCAtIG1pbiArIDEpICBcclxuXHJcbnByZXBhcmUgPSAtPlxyXG5cdHAgPSAoMSBmb3IgaSBpbiByYW5nZSBOKVxyXG5cdGZvciBpIGluIHJhbmdlIDIsTlxyXG5cdFx0aWYgcFtpXVxyXG5cdFx0XHRmb3IgaiBpbiByYW5nZSAyKmksTixpXHJcblx0XHRcdFx0cFtqXSA9IDBcclxuXHRjKmMgZm9yIGMgaW4gcmFuZ2UgMixOIHdoZW4gcFtjXT09MVxyXG5cclxuZiA9IChhKSAtPlxyXG5cdGFucyA9IDFcclxuXHRrbCA9IHt9XHJcblx0aGFzaCA9IHt9XHJcblx0Zm9yIHIwIGluIGFcclxuXHRcdGlmIHIwIGluIGhhc2hcclxuXHRcdFx0ciA9IGhhc2hbcjBdXHJcblx0XHRlbHNlXHJcblx0XHRcdHIgPSByMFxyXG5cdFx0XHRmb3IgcSBpbiBwMlxyXG5cdFx0XHRcdGlmIHIgPCBxXHJcblx0XHRcdFx0XHRicmVha1xyXG5cdFx0XHRcdHdoaWxlIHIgJSBxID09IDBcclxuXHRcdFx0XHRcdHIgLy89IHFcclxuXHRcdFx0aGFzaFtyMF0gPSByXHJcblx0XHRpZiByIG9mIGtsXHJcblx0XHRcdGFucyArPSAxXHJcblx0XHRcdGtsID0ge31cclxuXHRcdGtsW3JdID0gMVxyXG5cdGFuc1xyXG5cclxucDIgPSBwcmVwYXJlKClcclxuZm9yIF8gaW4gcmFuZ2UgbnIoKVxyXG5cdF8gPSBucnMoKVxyXG5cdHByaW50IGYgbnJzKClcclxuIl19\n//# sourceURL=c:\\github\\2021\\010\\coffee\\javascript.coffee"}, {"source_code": "// Generated by CoffeeScript 2.4.1\nvar N, currentLine, f, input, inputString, main, nr, nrs, p2, prepare, print, randint,\n indexOf = [].indexOf;\n\nprint = console.log;\n\nprocess.stdin.resume();\n\nprocess.stdin.setEncoding('utf-8');\n\ninputString = '';\n\ncurrentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n return inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function(_) {\n inputString = inputString.trim().split('\\n').map(function(string) {\n return string.trim();\n });\n return main();\n});\n\ninput = function() {\n return inputString[currentLine++];\n};\n\nnr = function() {\n return parseInt(input());\n};\n\nnrs = function() {\n var i, k, len, ref, results;\n ref = input().split(' ');\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(parseInt(i));\n }\n return results;\n};\n\n\nfunction range(start, stop, step) {\n if (stop == null) {\n stop = start || 0\n start = 0\n }\n if (!step) step = stop < start ? -1 : 1\n\n var length = Math.max(Math.ceil((stop - start) / step), 0)\n var range = Array(length)\n\n for (var idx = 0; idx < length; idx++, start += step) range[idx] = start\n\n return range;\n}\n // range = (start, stop, step) ->\n // \tif stop == undefined\n // \t\tstop = start || 0\n // \t\tstart = 0\n // \tif step == undefined\n // \t\tstep = if stop < start then -1 else 1\n // \tlength = Math.max(Math.ceil((stop - start) / step), 0)\n // \ti for i in [start...start+length] by step\n;\n\n//##################################################\nN = 3162;\n\np2 = [];\n\nrandint = function(min, max) {\n return min + Math.floor(Math.random() * (max - min + 1));\n};\n\nprepare = function() {\n var c, i, j, k, l, len, len1, len2, m, p, ref, ref1, ref2, results;\n p = (function() {\n var k, len, ref, results;\n ref = range(N);\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(1);\n }\n return results;\n })();\n ref = range(2, N);\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n if (p[i]) {\n ref1 = range(2 * i, N, i);\n for (l = 0, len1 = ref1.length; l < len1; l++) {\n j = ref1[l];\n p[j] = 0;\n }\n }\n }\n ref2 = range(2, N);\n results = [];\n for (m = 0, len2 = ref2.length; m < len2; m++) {\n c = ref2[m];\n if (p[c] === 1) {\n results.push(c * c);\n }\n }\n return results;\n};\n\nf = function(a) {\n var ans, hash, k, kl, l, len, len1, q, r, r0;\n ans = 1;\n kl = {};\n hash = {};\n for (k = 0, len = a.length; k < len; k++) {\n r0 = a[k];\n if (indexOf.call(hash, r0) >= 0) {\n r = hash[r0];\n } else {\n r = r0;\n for (l = 0, len1 = p2.length; l < len1; l++) {\n q = p2[l];\n if (r < q) {\n break;\n }\n while (r % q === 0) {\n r = Math.floor(r / q);\n }\n }\n hash[r0] = r;\n }\n if (r in kl) {\n ans += 1;\n kl = {};\n }\n kl[r] = 1;\n }\n return ans;\n};\n\nmain = function() {\n var _, k, len, ref, results;\n p2 = prepare();\n ref = range(nr());\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n _ = ref[k];\n [_, _] = nrs();\n results.push(print(f(nrs())));\n }\n return results;\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLmpzIiwic291cmNlUm9vdCI6Ii4uIiwic291cmNlcyI6WyJjb2ZmZWVcXGFwcC5jb2ZmZWUiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLElBQUEsQ0FBQSxFQUFBLFdBQUEsRUFBQSxDQUFBLEVBQUEsS0FBQSxFQUFBLFdBQUEsRUFBQSxJQUFBLEVBQUEsRUFBQSxFQUFBLEdBQUEsRUFBQSxFQUFBLEVBQUEsT0FBQSxFQUFBLEtBQUEsRUFBQSxPQUFBO0VBQUE7O0FBQUEsS0FBQSxHQUFRLE9BQU8sQ0FBQzs7QUFFaEIsT0FBTyxDQUFDLEtBQUssQ0FBQyxNQUFkLENBQUE7O0FBQ0EsT0FBTyxDQUFDLEtBQUssQ0FBQyxXQUFkLENBQTBCLE9BQTFCOztBQUVBLFdBQUEsR0FBYzs7QUFDZCxXQUFBLEdBQWM7O0FBRWQsT0FBTyxDQUFDLEtBQUssQ0FBQyxFQUFkLENBQWlCLE1BQWpCLEVBQXlCLFFBQUEsQ0FBQyxVQUFELENBQUE7U0FBZ0IsV0FBQSxJQUFlO0FBQS9CLENBQXpCOztBQUVBLE9BQU8sQ0FBQyxLQUFLLENBQUMsRUFBZCxDQUFpQixLQUFqQixFQUF3QixRQUFBLENBQUMsQ0FBRCxDQUFBO0VBQ3ZCLFdBQUEsR0FBYyxXQUFXLENBQUMsSUFBWixDQUFBLENBQWtCLENBQUMsS0FBbkIsQ0FBeUIsSUFBekIsQ0FBOEIsQ0FBQyxHQUEvQixDQUFtQyxRQUFBLENBQUMsTUFBRCxDQUFBO1dBQVksTUFBTSxDQUFDLElBQVAsQ0FBQTtFQUFaLENBQW5DO1NBQ2QsSUFBQSxDQUFBO0FBRnVCLENBQXhCOztBQUlBLEtBQUEsR0FBUSxRQUFBLENBQUEsQ0FBQTtTQUFHLFdBQVksQ0FBQSxXQUFBLEVBQUE7QUFBZjs7QUFFUixFQUFBLEdBQUssUUFBQSxDQUFBLENBQUE7U0FBTSxRQUFBLENBQVMsS0FBQSxDQUFBLENBQVQ7QUFBTjs7QUFDTCxHQUFBLEdBQU0sUUFBQSxDQUFBLENBQUE7QUFBTSxNQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsR0FBQSxFQUFBLEdBQUEsRUFBQTtBQUFZO0FBQUE7RUFBQSxLQUFBLHFDQUFBOztpQkFBWCxRQUFBLENBQVMsQ0FBVDtFQUFXLENBQUE7O0FBQWxCOztBQVdOOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztDQTVCQTs7O0FBOENBLENBQUEsR0FBSTs7QUFDSixFQUFBLEdBQUs7O0FBRUwsT0FBQSxHQUFVLFFBQUEsQ0FBQyxHQUFELEVBQU0sR0FBTixDQUFBO1NBQWMsR0FBQSxHQUFNLElBQUksQ0FBQyxLQUFMLENBQVcsSUFBSSxDQUFDLE1BQUwsQ0FBQSxDQUFBLEdBQWdCLENBQUMsR0FBQSxHQUFNLEdBQU4sR0FBWSxDQUFiLENBQTNCO0FBQXBCOztBQUVWLE9BQUEsR0FBVSxRQUFBLENBQUEsQ0FBQTtBQUNULE1BQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxJQUFBLEVBQUEsSUFBQSxFQUFBO0VBQUEsQ0FBQTs7QUFBTztBQUFBO0lBQUEsS0FBQSxxQ0FBQTs7bUJBQUY7SUFBRSxDQUFBOzs7QUFDUDtFQUFBLEtBQUEscUNBQUE7O0lBQ0MsSUFBRyxDQUFFLENBQUEsQ0FBQSxDQUFMO0FBQ0M7TUFBQSxLQUFBLHdDQUFBOztRQUNDLENBQUUsQ0FBQSxDQUFBLENBQUYsR0FBTztNQURSLENBREQ7O0VBREQ7QUFJSTtBQUFBO0VBQUEsS0FBQSx3Q0FBQTs7UUFBd0IsQ0FBRSxDQUFBLENBQUEsQ0FBRixLQUFNO21CQUFsQyxDQUFBLEdBQUU7O0VBQUUsQ0FBQTs7QUFOSzs7QUFRVixDQUFBLEdBQUksUUFBQSxDQUFDLENBQUQsQ0FBQTtBQUNILE1BQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUEsRUFBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUE7RUFBQSxHQUFBLEdBQU07RUFDTixFQUFBLEdBQUssQ0FBQTtFQUNMLElBQUEsR0FBTyxDQUFBO0VBQ1AsS0FBQSxtQ0FBQTs7SUFDQyxJQUFHLGFBQU0sSUFBTixFQUFBLEVBQUEsTUFBSDtNQUNDLENBQUEsR0FBSSxJQUFLLENBQUEsRUFBQSxFQURWO0tBQUEsTUFBQTtNQUdDLENBQUEsR0FBSTtNQUNKLEtBQUEsc0NBQUE7O1FBQ0MsSUFBRyxDQUFBLEdBQUksQ0FBUDtBQUNDLGdCQUREOztBQUVBLGVBQU0sQ0FBQSxHQUFJLENBQUosS0FBUyxDQUFmO1VBQ0MsZUFBQSxJQUFNO1FBRFA7TUFIRDtNQUtBLElBQUssQ0FBQSxFQUFBLENBQUwsR0FBVyxFQVRaOztJQVVBLElBQUcsQ0FBQSxJQUFLLEVBQVI7TUFDQyxHQUFBLElBQU87TUFDUCxFQUFBLEdBQUssQ0FBQSxFQUZOOztJQUdBLEVBQUcsQ0FBQSxDQUFBLENBQUgsR0FBUTtFQWRUO1NBZUE7QUFuQkc7O0FBcUJKLElBQUEsR0FBTyxRQUFBLENBQUEsQ0FBQTtBQUNOLE1BQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsR0FBQSxFQUFBO0VBQUEsRUFBQSxHQUFLLE9BQUEsQ0FBQTtBQUNMO0FBQUE7RUFBQSxLQUFBLHFDQUFBOztJQUNDLENBQUMsQ0FBRCxFQUFHLENBQUgsQ0FBQSxHQUFRLEdBQUEsQ0FBQTtpQkFDUixLQUFBLENBQU0sQ0FBQSxDQUFFLEdBQUEsQ0FBQSxDQUFGLENBQU47RUFGRCxDQUFBOztBQUZNIiwic291cmNlc0NvbnRlbnQiOlsicHJpbnQgPSBjb25zb2xlLmxvZ1xuXG5wcm9jZXNzLnN0ZGluLnJlc3VtZSgpXG5wcm9jZXNzLnN0ZGluLnNldEVuY29kaW5nICd1dGYtOCdcbiBcbmlucHV0U3RyaW5nID0gJydcbmN1cnJlbnRMaW5lID0gMFxuIFxucHJvY2Vzcy5zdGRpbi5vbiAnZGF0YScsIChpbnB1dFN0ZGluKSAtPiBpbnB1dFN0cmluZyArPSBpbnB1dFN0ZGluXG4gXG5wcm9jZXNzLnN0ZGluLm9uICdlbmQnLCAoXykgLT4gXG5cdGlucHV0U3RyaW5nID0gaW5wdXRTdHJpbmcudHJpbSgpLnNwbGl0KCdcXG4nKS5tYXAgKHN0cmluZykgLT4gc3RyaW5nLnRyaW0oKVxuXHRtYWluKClcblxuaW5wdXQgPSAtPiBpbnB1dFN0cmluZ1tjdXJyZW50TGluZSsrXVxuXG5uciA9ICgpIC0+IHBhcnNlSW50IGlucHV0KCkgXG5ucnMgPSAoKSAtPiAocGFyc2VJbnQgaSBmb3IgaSBpbiBpbnB1dCgpLnNwbGl0ICcgJylcblxuIyByYW5nZSA9IChzdGFydCwgc3RvcCwgc3RlcCkgLT5cbiMgXHRpZiBzdG9wID09IHVuZGVmaW5lZFxuIyBcdFx0c3RvcCA9IHN0YXJ0IHx8IDBcbiMgXHRcdHN0YXJ0ID0gMFxuIyBcdGlmIHN0ZXAgPT0gdW5kZWZpbmVkXG4jIFx0XHRzdGVwID0gaWYgc3RvcCA8IHN0YXJ0IHRoZW4gLTEgZWxzZSAxXG4jIFx0bGVuZ3RoID0gTWF0aC5tYXgoTWF0aC5jZWlsKChzdG9wIC0gc3RhcnQpIC8gc3RlcCksIDApXG4jIFx0aSBmb3IgaSBpbiBbc3RhcnQuLi5zdGFydCtsZW5ndGhdIGJ5IHN0ZXBcblxuYGBgXG5mdW5jdGlvbiByYW5nZShzdGFydCwgc3RvcCwgc3RlcCkge1xuICBpZiAoc3RvcCA9PSBudWxsKSB7XG4gICAgc3RvcCA9IHN0YXJ0IHx8IDBcbiAgICBzdGFydCA9IDBcbiAgfVxuICBpZiAoIXN0ZXApIHN0ZXAgPSBzdG9wIDwgc3RhcnQgPyAtMSA6IDFcblxuICB2YXIgbGVuZ3RoID0gTWF0aC5tYXgoTWF0aC5jZWlsKChzdG9wIC0gc3RhcnQpIC8gc3RlcCksIDApXG4gIHZhciByYW5nZSA9IEFycmF5KGxlbmd0aClcblxuICBmb3IgKHZhciBpZHggPSAwOyBpZHggPCBsZW5ndGg7IGlkeCsrLCBzdGFydCArPSBzdGVwKSByYW5nZVtpZHhdID0gc3RhcnRcblxuICByZXR1cm4gcmFuZ2U7XG59XG5gYGBcbiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI1xuXG5OID0gMzE2MlxucDIgPSBbXVxuXG5yYW5kaW50ID0gKG1pbiwgbWF4KSAtPiBtaW4gKyBNYXRoLmZsb29yIE1hdGgucmFuZG9tKCkgKiAobWF4IC0gbWluICsgMSkgIFxuXG5wcmVwYXJlID0gLT5cblx0cCA9ICgxIGZvciBpIGluIHJhbmdlIE4pXG5cdGZvciBpIGluIHJhbmdlIDIsTlxuXHRcdGlmIHBbaV1cblx0XHRcdGZvciBqIGluIHJhbmdlIDIqaSxOLGlcblx0XHRcdFx0cFtqXSA9IDBcblx0YypjIGZvciBjIGluIHJhbmdlIDIsTiB3aGVuIHBbY109PTFcblxuZiA9IChhKSAtPlxuXHRhbnMgPSAxXG5cdGtsID0ge31cblx0aGFzaCA9IHt9XG5cdGZvciByMCBpbiBhXG5cdFx0aWYgcjAgaW4gaGFzaFxuXHRcdFx0ciA9IGhhc2hbcjBdXG5cdFx0ZWxzZVxuXHRcdFx0ciA9IHIwXG5cdFx0XHRmb3IgcSBpbiBwMlxuXHRcdFx0XHRpZiByIDwgcVxuXHRcdFx0XHRcdGJyZWFrXG5cdFx0XHRcdHdoaWxlIHIgJSBxID09IDBcblx0XHRcdFx0XHRyIC8vPSBxXG5cdFx0XHRoYXNoW3IwXSA9IHJcblx0XHRpZiByIG9mIGtsXG5cdFx0XHRhbnMgKz0gMVxuXHRcdFx0a2wgPSB7fVxuXHRcdGtsW3JdID0gMVxuXHRhbnNcblxubWFpbiA9IC0+XG5cdHAyID0gcHJlcGFyZSgpXG5cdGZvciBfIGluIHJhbmdlIG5yKClcblx0XHRbXyxfXSA9IG5ycygpXG5cdFx0cHJpbnQgZiBucnMoKVxuIl19\n//# sourceURL=c:\\github\\2021\\010\\coffee\\app.coffee"}, {"source_code": "// Generated by CoffeeScript 2.4.1\nvar N, currentLine, f, input, inputString, main, nr, nrs, p2, prepare, print, randint,\n indexOf = [].indexOf;\n\nprint = console.log;\n\nprocess.stdin.resume();\n\nprocess.stdin.setEncoding('utf-8');\n\ninputString = '';\n\ncurrentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n return inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function(_) {\n inputString = inputString.trim().split('\\n').map(function(string) {\n return string.trim();\n });\n return main();\n});\n\ninput = function() {\n return inputString[currentLine++];\n};\n\nnr = function() {\n return parseInt(input());\n};\n\nnrs = function() {\n var i, k, len, ref, results;\n ref = input().split(' ');\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(parseInt(i));\n }\n return results;\n};\n\n// range = (start, stop, step) ->\n// \tif stop == undefined\n// \t\tstop = start || 0\n// \t\tstart = 0\n// \tif step == undefined\n// \t\tstep = if stop < start then -1 else 1\n// \tlength = Math.max(Math.ceil((stop - start) / step), 0)\n// \ti for i in [start...start+length] by step\n\n//##################################################\nN = 3162;\n\np2 = [];\n\nrandint = function(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n};\n\nprepare = function() {\n var c, i, j, k, l, m, p, ref, ref1, ref2, ref3, ref4, results;\n p = (function() {\n var k, ref, results;\n results = [];\n for (i = k = 0, ref = N; (0 <= ref ? k < ref : k > ref); i = 0 <= ref ? ++k : --k) {\n results.push(1);\n }\n return results;\n })();\n for (i = k = 2, ref = N; (2 <= ref ? k < ref : k > ref); i = 2 <= ref ? ++k : --k) {\n if (p[i]) {\n for (j = l = ref1 = 2 * i, ref2 = N, ref3 = i; ref3 !== 0 && (ref3 > 0 ? l < ref2 : l > ref2); j = l += ref3) {\n p[j] = 0;\n }\n }\n }\n results = [];\n for (c = m = 2, ref4 = N; (2 <= ref4 ? m < ref4 : m > ref4); c = 2 <= ref4 ? ++m : --m) {\n if (p[c] === 1) {\n results.push(c * c);\n }\n }\n return results;\n};\n\nf = function(a) {\n var ans, hash, k, kl, l, len, len1, q, r, r0;\n ans = 1;\n kl = {};\n hash = {};\n for (k = 0, len = a.length; k < len; k++) {\n r0 = a[k];\n if (indexOf.call(hash, r0) >= 0) {\n r = hash[r0];\n } else {\n r = r0;\n for (l = 0, len1 = p2.length; l < len1; l++) {\n q = p2[l];\n if (r < q) {\n break;\n }\n while (r % q === 0) {\n r = Math.floor(r / q);\n }\n }\n hash[r0] = r;\n }\n if (r in kl) {\n ans += 1;\n kl = {};\n }\n kl[r] = 1;\n }\n return ans;\n};\n\nmain = function() {\n var _, k, ref, results;\n p2 = prepare();\n results = [];\n for (_ = k = 0, ref = nr(); (0 <= ref ? k < ref : k > ref); _ = 0 <= ref ? ++k : --k) {\n [_, _] = nrs();\n results.push(print(f(nrs())));\n }\n return results;\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLmpzIiwic291cmNlUm9vdCI6Ii4uIiwic291cmNlcyI6WyJjb2ZmZWVcXGFwcC5jb2ZmZWUiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLElBQUEsQ0FBQSxFQUFBLFdBQUEsRUFBQSxDQUFBLEVBQUEsS0FBQSxFQUFBLFdBQUEsRUFBQSxJQUFBLEVBQUEsRUFBQSxFQUFBLEdBQUEsRUFBQSxFQUFBLEVBQUEsT0FBQSxFQUFBLEtBQUEsRUFBQSxPQUFBO0VBQUE7O0FBQUEsS0FBQSxHQUFRLE9BQU8sQ0FBQzs7QUFFaEIsT0FBTyxDQUFDLEtBQUssQ0FBQyxNQUFkLENBQUE7O0FBQ0EsT0FBTyxDQUFDLEtBQUssQ0FBQyxXQUFkLENBQTBCLE9BQTFCOztBQUVBLFdBQUEsR0FBYzs7QUFDZCxXQUFBLEdBQWM7O0FBRWQsT0FBTyxDQUFDLEtBQUssQ0FBQyxFQUFkLENBQWlCLE1BQWpCLEVBQXlCLFFBQUEsQ0FBQyxVQUFELENBQUE7U0FBZ0IsV0FBQSxJQUFlO0FBQS9CLENBQXpCOztBQUVBLE9BQU8sQ0FBQyxLQUFLLENBQUMsRUFBZCxDQUFpQixLQUFqQixFQUF3QixRQUFBLENBQUMsQ0FBRCxDQUFBO0VBQ3ZCLFdBQUEsR0FBYyxXQUFXLENBQUMsSUFBWixDQUFBLENBQWtCLENBQUMsS0FBbkIsQ0FBeUIsSUFBekIsQ0FBOEIsQ0FBQyxHQUEvQixDQUFtQyxRQUFBLENBQUMsTUFBRCxDQUFBO1dBQVksTUFBTSxDQUFDLElBQVAsQ0FBQTtFQUFaLENBQW5DO1NBQ2QsSUFBQSxDQUFBO0FBRnVCLENBQXhCOztBQUlBLEtBQUEsR0FBUSxRQUFBLENBQUEsQ0FBQTtTQUFHLFdBQVksQ0FBQSxXQUFBLEVBQUE7QUFBZjs7QUFFUixFQUFBLEdBQUssUUFBQSxDQUFBLENBQUE7U0FBTSxRQUFBLENBQVMsS0FBQSxDQUFBLENBQVQ7QUFBTjs7QUFDTCxHQUFBLEdBQU0sUUFBQSxDQUFBLENBQUE7QUFBTSxNQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsR0FBQSxFQUFBLEdBQUEsRUFBQTtBQUFZO0FBQUE7RUFBQSxLQUFBLHFDQUFBOztpQkFBWCxRQUFBLENBQVMsQ0FBVDtFQUFXLENBQUE7O0FBQWxCLEVBakJOOzs7Ozs7Ozs7Ozs7QUE4QkEsQ0FBQSxHQUFJOztBQUNKLEVBQUEsR0FBSzs7QUFFTCxPQUFBLEdBQVUsUUFBQSxDQUFDLEdBQUQsRUFBTSxHQUFOLENBQUE7U0FBYyxJQUFJLENBQUMsS0FBTCxDQUFXLElBQUksQ0FBQyxNQUFMLENBQUEsQ0FBQSxHQUFnQixDQUFDLEdBQUEsR0FBTSxHQUFOLEdBQVksQ0FBYixDQUEzQixDQUFBLEdBQStDO0FBQTdEOztBQUVWLE9BQUEsR0FBVSxRQUFBLENBQUEsQ0FBQTtBQUNULE1BQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxJQUFBLEVBQUEsSUFBQSxFQUFBLElBQUEsRUFBQSxJQUFBLEVBQUE7RUFBQSxDQUFBOztBQUFPO0lBQUEsS0FBUyw0RUFBVDttQkFBRjtJQUFFLENBQUE7OztFQUNQLEtBQVMsNEVBQVQ7SUFDQyxJQUFHLENBQUUsQ0FBQSxDQUFBLENBQUw7TUFDQyxLQUFTLHVHQUFUO1FBQ0MsQ0FBRSxDQUFBLENBQUEsQ0FBRixHQUFPO01BRFIsQ0FERDs7RUFERDtBQUlJO0VBQUEsS0FBUyxpRkFBVDtRQUFzQixDQUFFLENBQUEsQ0FBQSxDQUFGLEtBQU07bUJBQWhDLENBQUEsR0FBRTs7RUFBRSxDQUFBOztBQU5LOztBQVFWLENBQUEsR0FBSSxRQUFBLENBQUMsQ0FBRCxDQUFBO0FBQ0gsTUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLENBQUEsRUFBQSxFQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxJQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQTtFQUFBLEdBQUEsR0FBTTtFQUNOLEVBQUEsR0FBSyxDQUFBO0VBQ0wsSUFBQSxHQUFPLENBQUE7RUFDUCxLQUFBLG1DQUFBOztJQUNDLElBQUcsYUFBTSxJQUFOLEVBQUEsRUFBQSxNQUFIO01BQ0MsQ0FBQSxHQUFJLElBQUssQ0FBQSxFQUFBLEVBRFY7S0FBQSxNQUFBO01BR0MsQ0FBQSxHQUFJO01BQ0osS0FBQSxzQ0FBQTs7UUFDQyxJQUFHLENBQUEsR0FBSSxDQUFQO0FBQ0MsZ0JBREQ7O0FBRUEsZUFBTSxDQUFBLEdBQUksQ0FBSixLQUFTLENBQWY7VUFDQyxlQUFBLElBQU07UUFEUDtNQUhEO01BS0EsSUFBSyxDQUFBLEVBQUEsQ0FBTCxHQUFTLEVBVFY7O0lBVUEsSUFBRyxDQUFBLElBQUssRUFBUjtNQUNDLEdBQUEsSUFBTztNQUNQLEVBQUEsR0FBSyxDQUFBLEVBRk47O0lBR0EsRUFBRyxDQUFBLENBQUEsQ0FBSCxHQUFRO0VBZFQ7U0FlQTtBQW5CRzs7QUFxQkosSUFBQSxHQUFPLFFBQUEsQ0FBQSxDQUFBO0FBQ04sTUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQTtFQUFBLEVBQUEsR0FBSyxPQUFBLENBQUE7QUFDTDtFQUFBLEtBQVMsK0VBQVQ7SUFDQyxDQUFDLENBQUQsRUFBRyxDQUFILENBQUEsR0FBUSxHQUFBLENBQUE7aUJBQ1IsS0FBQSxDQUFNLENBQUEsQ0FBRSxHQUFBLENBQUEsQ0FBRixDQUFOO0VBRkQsQ0FBQTs7QUFGTSIsInNvdXJjZXNDb250ZW50IjpbInByaW50ID0gY29uc29sZS5sb2dcblxucHJvY2Vzcy5zdGRpbi5yZXN1bWUoKVxucHJvY2Vzcy5zdGRpbi5zZXRFbmNvZGluZyAndXRmLTgnXG4gXG5pbnB1dFN0cmluZyA9ICcnXG5jdXJyZW50TGluZSA9IDBcbiBcbnByb2Nlc3Muc3RkaW4ub24gJ2RhdGEnLCAoaW5wdXRTdGRpbikgLT4gaW5wdXRTdHJpbmcgKz0gaW5wdXRTdGRpblxuIFxucHJvY2Vzcy5zdGRpbi5vbiAnZW5kJywgKF8pIC0+IFxuXHRpbnB1dFN0cmluZyA9IGlucHV0U3RyaW5nLnRyaW0oKS5zcGxpdCgnXFxuJykubWFwIChzdHJpbmcpIC0+IHN0cmluZy50cmltKClcblx0bWFpbigpXG5cbmlucHV0ID0gLT4gaW5wdXRTdHJpbmdbY3VycmVudExpbmUrK11cblxubnIgPSAoKSAtPiBwYXJzZUludCBpbnB1dCgpXG5ucnMgPSAoKSAtPiAocGFyc2VJbnQgaSBmb3IgaSBpbiBpbnB1dCgpLnNwbGl0ICcgJylcblxuIyByYW5nZSA9IChzdGFydCwgc3RvcCwgc3RlcCkgLT5cbiMgXHRpZiBzdG9wID09IHVuZGVmaW5lZFxuIyBcdFx0c3RvcCA9IHN0YXJ0IHx8IDBcbiMgXHRcdHN0YXJ0ID0gMFxuIyBcdGlmIHN0ZXAgPT0gdW5kZWZpbmVkXG4jIFx0XHRzdGVwID0gaWYgc3RvcCA8IHN0YXJ0IHRoZW4gLTEgZWxzZSAxXG4jIFx0bGVuZ3RoID0gTWF0aC5tYXgoTWF0aC5jZWlsKChzdG9wIC0gc3RhcnQpIC8gc3RlcCksIDApXG4jIFx0aSBmb3IgaSBpbiBbc3RhcnQuLi5zdGFydCtsZW5ndGhdIGJ5IHN0ZXBcblxuIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjXG5cbk4gPSAzMTYyXG5wMiA9IFtdXG5cbnJhbmRpbnQgPSAobWluLCBtYXgpIC0+IE1hdGguZmxvb3IoTWF0aC5yYW5kb20oKSAqIChtYXggLSBtaW4gKyAxKSApICsgbWluXG5cbnByZXBhcmUgPSAoKSAtPlxuXHRwID0gKDEgZm9yIGkgaW4gWzAuLi5OXSlcblx0Zm9yIGkgaW4gWzIuLi5OXVxuXHRcdGlmIHBbaV1cblx0XHRcdGZvciBqIGluIFsyKmkuLi5OXSBieSBpXG5cdFx0XHRcdHBbal0gPSAwXG5cdGMqYyBmb3IgYyBpbiBbMi4uLk5dIHdoZW4gcFtjXT09MVxuXG5mID0gKGEpIC0+XG5cdGFucyA9IDFcblx0a2wgPSB7fVxuXHRoYXNoID0ge31cblx0Zm9yIHIwIGluIGFcblx0XHRpZiByMCBpbiBoYXNoXG5cdFx0XHRyID0gaGFzaFtyMF1cblx0XHRlbHNlXG5cdFx0XHRyID0gcjBcblx0XHRcdGZvciBxIGluIHAyXG5cdFx0XHRcdGlmIHIgPCBxXG5cdFx0XHRcdFx0YnJlYWtcblx0XHRcdFx0d2hpbGUgciAlIHEgPT0gMFxuXHRcdFx0XHRcdHIgLy89IHFcblx0XHRcdGhhc2hbcjBdPXJcblx0XHRpZiByIG9mIGtsXG5cdFx0XHRhbnMgKz0gMVxuXHRcdFx0a2wgPSB7fVxuXHRcdGtsW3JdID0gMVxuXHRhbnNcblxubWFpbiA9IC0+XG5cdHAyID0gcHJlcGFyZSgpXG5cdGZvciBfIGluIFswLi4ubnIoKV1cblx0XHRbXyxfXSA9IG5ycygpXG5cdFx0cHJpbnQgZiBucnMoKVxuIl19\n//# sourceURL=c:\\github\\2021\\010\\coffee\\app.coffee"}, {"source_code": "// Generated by CoffeeScript 2.4.1\nvar N, currentLine, f, input, inputString, main, nr, nrs, p2, prepare, print, randint, range,\n indexOf = [].indexOf;\n\nprint = console.log;\n\nprocess.stdin.resume();\n\nprocess.stdin.setEncoding('utf-8');\n\ninputString = '';\n\ncurrentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n return inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function(_) {\n inputString = inputString.trim().split('\\n').map(function(string) {\n return string.trim();\n });\n return main();\n});\n\ninput = function() {\n return inputString[currentLine++];\n};\n\nnr = function() {\n return parseInt(input());\n};\n\nnrs = function() {\n var i, k, len, ref, results;\n ref = input().split(' ');\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(parseInt(i));\n }\n return results;\n};\n\nrange = function(start, stop, step) {\n var i, k, length, ref, ref1, ref2, results;\n if (stop === void 0) {\n stop = start || 0;\n start = 0;\n }\n if (step === void 0) {\n step = stop < start ? -1 : 1;\n }\n length = Math.max(Math.ceil((stop - start) / step), 0);\n results = [];\n for (i = k = ref = start, ref1 = start + length, ref2 = step; ref2 !== 0 && (ref2 > 0 ? k < ref1 : k > ref1); i = k += ref2) {\n results.push(i);\n }\n return results;\n};\n\n//##################################################\nN = 3162;\n\np2 = [];\n\nrandint = function(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n};\n\nprepare = function() {\n var c, i, j, k, l, len, len1, len2, m, p, ref, ref1, ref2, results;\n p = (function() {\n var k, len, ref, results;\n ref = range(N);\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(1);\n }\n return results;\n })();\n ref = range(2, N);\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n if (p[i]) {\n ref1 = range(2 * i, N, i);\n for (l = 0, len1 = ref1.length; l < len1; l++) {\n j = ref1[l];\n p[j] = 0;\n }\n }\n }\n ref2 = range(2, N);\n results = [];\n for (m = 0, len2 = ref2.length; m < len2; m++) {\n c = ref2[m];\n if (p[c] === 1) {\n results.push(c * c);\n }\n }\n return results;\n};\n\nf = function(a) {\n var ans, hash, k, kl, l, len, len1, q, r, r0;\n ans = 1;\n kl = {};\n hash = {};\n for (k = 0, len = a.length; k < len; k++) {\n r0 = a[k];\n if (indexOf.call(hash, r0) >= 0) {\n r = hash[r0];\n } else {\n r = r0;\n for (l = 0, len1 = p2.length; l < len1; l++) {\n q = p2[l];\n if (r < q) {\n break;\n }\n while (r % q === 0) {\n r = Math.floor(r / q);\n }\n }\n hash[r0] = r;\n }\n if (r in kl) {\n ans += 1;\n kl = {};\n }\n kl[r] = 1;\n }\n return ans;\n};\n\nmain = function() {\n var _, k, len, ref, results;\n p2 = prepare();\n ref = range(nr());\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n _ = ref[k];\n [_, _] = nrs();\n results.push(print(f(nrs())));\n }\n return results;\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLmpzIiwic291cmNlUm9vdCI6Ii4uIiwic291cmNlcyI6WyJjb2ZmZWVcXGFwcC5jb2ZmZWUiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLElBQUEsQ0FBQSxFQUFBLFdBQUEsRUFBQSxDQUFBLEVBQUEsS0FBQSxFQUFBLFdBQUEsRUFBQSxJQUFBLEVBQUEsRUFBQSxFQUFBLEdBQUEsRUFBQSxFQUFBLEVBQUEsT0FBQSxFQUFBLEtBQUEsRUFBQSxPQUFBLEVBQUEsS0FBQTtFQUFBOztBQUFBLEtBQUEsR0FBUSxPQUFPLENBQUM7O0FBRWhCLE9BQU8sQ0FBQyxLQUFLLENBQUMsTUFBZCxDQUFBOztBQUNBLE9BQU8sQ0FBQyxLQUFLLENBQUMsV0FBZCxDQUEwQixPQUExQjs7QUFFQSxXQUFBLEdBQWM7O0FBQ2QsV0FBQSxHQUFjOztBQUVkLE9BQU8sQ0FBQyxLQUFLLENBQUMsRUFBZCxDQUFpQixNQUFqQixFQUF5QixRQUFBLENBQUMsVUFBRCxDQUFBO1NBQWdCLFdBQUEsSUFBZTtBQUEvQixDQUF6Qjs7QUFFQSxPQUFPLENBQUMsS0FBSyxDQUFDLEVBQWQsQ0FBaUIsS0FBakIsRUFBd0IsUUFBQSxDQUFDLENBQUQsQ0FBQTtFQUN2QixXQUFBLEdBQWMsV0FBVyxDQUFDLElBQVosQ0FBQSxDQUFrQixDQUFDLEtBQW5CLENBQXlCLElBQXpCLENBQThCLENBQUMsR0FBL0IsQ0FBbUMsUUFBQSxDQUFDLE1BQUQsQ0FBQTtXQUFZLE1BQU0sQ0FBQyxJQUFQLENBQUE7RUFBWixDQUFuQztTQUNkLElBQUEsQ0FBQTtBQUZ1QixDQUF4Qjs7QUFJQSxLQUFBLEdBQVEsUUFBQSxDQUFBLENBQUE7U0FBRyxXQUFZLENBQUEsV0FBQSxFQUFBO0FBQWY7O0FBRVIsRUFBQSxHQUFLLFFBQUEsQ0FBQSxDQUFBO1NBQU0sUUFBQSxDQUFTLEtBQUEsQ0FBQSxDQUFUO0FBQU47O0FBQ0wsR0FBQSxHQUFNLFFBQUEsQ0FBQSxDQUFBO0FBQU0sTUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxHQUFBLEVBQUE7QUFBWTtBQUFBO0VBQUEsS0FBQSxxQ0FBQTs7aUJBQVgsUUFBQSxDQUFTLENBQVQ7RUFBVyxDQUFBOztBQUFsQjs7QUFFTixLQUFBLEdBQVEsUUFBQSxDQUFDLEtBQUQsRUFBUSxJQUFSLEVBQWMsSUFBZCxDQUFBO0FBQ1AsTUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLE1BQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLElBQUEsRUFBQTtFQUFBLElBQUcsSUFBQSxLQUFRLE1BQVg7SUFDQyxJQUFBLEdBQU8sS0FBQSxJQUFTO0lBQ2hCLEtBQUEsR0FBUSxFQUZUOztFQUdBLElBQUcsSUFBQSxLQUFRLE1BQVg7SUFDQyxJQUFBLEdBQVUsSUFBQSxHQUFPLEtBQVYsR0FBcUIsQ0FBQyxDQUF0QixHQUE2QixFQURyQzs7RUFFQSxNQUFBLEdBQVMsSUFBSSxDQUFDLEdBQUwsQ0FBUyxJQUFJLENBQUMsSUFBTCxDQUFVLENBQUMsSUFBQSxHQUFPLEtBQVIsQ0FBQSxHQUFpQixJQUEzQixDQUFULEVBQTJDLENBQTNDO0FBQ1A7RUFBQSxLQUFTLHNIQUFUO2lCQUFGO0VBQUUsQ0FBQTs7QUFQSyxFQW5CUjs7O0FBOEJBLENBQUEsR0FBSTs7QUFDSixFQUFBLEdBQUs7O0FBRUwsT0FBQSxHQUFVLFFBQUEsQ0FBQyxHQUFELEVBQU0sR0FBTixDQUFBO1NBQWMsSUFBSSxDQUFDLEtBQUwsQ0FBVyxJQUFJLENBQUMsTUFBTCxDQUFBLENBQUEsR0FBZ0IsQ0FBQyxHQUFBLEdBQU0sR0FBTixHQUFZLENBQWIsQ0FBM0IsQ0FBQSxHQUErQztBQUE3RDs7QUFFVixPQUFBLEdBQVUsUUFBQSxDQUFBLENBQUE7QUFDVCxNQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxJQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLElBQUEsRUFBQTtFQUFBLENBQUE7O0FBQU87QUFBQTtJQUFBLEtBQUEscUNBQUE7O21CQUFGO0lBQUUsQ0FBQTs7O0FBQ1A7RUFBQSxLQUFBLHFDQUFBOztJQUNDLElBQUcsQ0FBRSxDQUFBLENBQUEsQ0FBTDtBQUNDO01BQUEsS0FBQSx3Q0FBQTs7UUFDQyxDQUFFLENBQUEsQ0FBQSxDQUFGLEdBQU87TUFEUixDQUREOztFQUREO0FBSUk7QUFBQTtFQUFBLEtBQUEsd0NBQUE7O1FBQXdCLENBQUUsQ0FBQSxDQUFBLENBQUYsS0FBTTttQkFBbEMsQ0FBQSxHQUFFOztFQUFFLENBQUE7O0FBTks7O0FBUVYsQ0FBQSxHQUFJLFFBQUEsQ0FBQyxDQUFELENBQUE7QUFDSCxNQUFBLEdBQUEsRUFBQSxJQUFBLEVBQUEsQ0FBQSxFQUFBLEVBQUEsRUFBQSxDQUFBLEVBQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBO0VBQUEsR0FBQSxHQUFNO0VBQ04sRUFBQSxHQUFLLENBQUE7RUFDTCxJQUFBLEdBQU8sQ0FBQTtFQUNQLEtBQUEsbUNBQUE7O0lBQ0MsSUFBRyxhQUFNLElBQU4sRUFBQSxFQUFBLE1BQUg7TUFDQyxDQUFBLEdBQUksSUFBSyxDQUFBLEVBQUEsRUFEVjtLQUFBLE1BQUE7TUFHQyxDQUFBLEdBQUk7TUFDSixLQUFBLHNDQUFBOztRQUNDLElBQUcsQ0FBQSxHQUFJLENBQVA7QUFDQyxnQkFERDs7QUFFQSxlQUFNLENBQUEsR0FBSSxDQUFKLEtBQVMsQ0FBZjtVQUNDLGVBQUEsSUFBTTtRQURQO01BSEQ7TUFLQSxJQUFLLENBQUEsRUFBQSxDQUFMLEdBQVMsRUFUVjs7SUFVQSxJQUFHLENBQUEsSUFBSyxFQUFSO01BQ0MsR0FBQSxJQUFPO01BQ1AsRUFBQSxHQUFLLENBQUEsRUFGTjs7SUFHQSxFQUFHLENBQUEsQ0FBQSxDQUFILEdBQVE7RUFkVDtTQWVBO0FBbkJHOztBQXFCSixJQUFBLEdBQU8sUUFBQSxDQUFBLENBQUE7QUFDTixNQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsR0FBQSxFQUFBLEdBQUEsRUFBQTtFQUFBLEVBQUEsR0FBSyxPQUFBLENBQUE7QUFDTDtBQUFBO0VBQUEsS0FBQSxxQ0FBQTs7SUFDQyxDQUFDLENBQUQsRUFBRyxDQUFILENBQUEsR0FBUSxHQUFBLENBQUE7aUJBQ1IsS0FBQSxDQUFNLENBQUEsQ0FBRSxHQUFBLENBQUEsQ0FBRixDQUFOO0VBRkQsQ0FBQTs7QUFGTSIsInNvdXJjZXNDb250ZW50IjpbInByaW50ID0gY29uc29sZS5sb2dcblxucHJvY2Vzcy5zdGRpbi5yZXN1bWUoKVxucHJvY2Vzcy5zdGRpbi5zZXRFbmNvZGluZyAndXRmLTgnXG4gXG5pbnB1dFN0cmluZyA9ICcnXG5jdXJyZW50TGluZSA9IDBcbiBcbnByb2Nlc3Muc3RkaW4ub24gJ2RhdGEnLCAoaW5wdXRTdGRpbikgLT4gaW5wdXRTdHJpbmcgKz0gaW5wdXRTdGRpblxuIFxucHJvY2Vzcy5zdGRpbi5vbiAnZW5kJywgKF8pIC0+IFxuXHRpbnB1dFN0cmluZyA9IGlucHV0U3RyaW5nLnRyaW0oKS5zcGxpdCgnXFxuJykubWFwIChzdHJpbmcpIC0+IHN0cmluZy50cmltKClcblx0bWFpbigpXG5cbmlucHV0ID0gLT4gaW5wdXRTdHJpbmdbY3VycmVudExpbmUrK11cblxubnIgPSAoKSAtPiBwYXJzZUludCBpbnB1dCgpXG5ucnMgPSAoKSAtPiAocGFyc2VJbnQgaSBmb3IgaSBpbiBpbnB1dCgpLnNwbGl0ICcgJylcblxucmFuZ2UgPSAoc3RhcnQsIHN0b3AsIHN0ZXApIC0+XG5cdGlmIHN0b3AgPT0gdW5kZWZpbmVkXG5cdFx0c3RvcCA9IHN0YXJ0IHx8IDBcblx0XHRzdGFydCA9IDBcblx0aWYgc3RlcCA9PSB1bmRlZmluZWRcblx0XHRzdGVwID0gaWYgc3RvcCA8IHN0YXJ0IHRoZW4gLTEgZWxzZSAxXG5cdGxlbmd0aCA9IE1hdGgubWF4KE1hdGguY2VpbCgoc3RvcCAtIHN0YXJ0KSAvIHN0ZXApLCAwKVxuXHRpIGZvciBpIGluIFtzdGFydC4uLnN0YXJ0K2xlbmd0aF0gYnkgc3RlcFxuXG4jIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyNcblxuTiA9IDMxNjJcbnAyID0gW11cblxucmFuZGludCA9IChtaW4sIG1heCkgLT4gTWF0aC5mbG9vcihNYXRoLnJhbmRvbSgpICogKG1heCAtIG1pbiArIDEpICkgKyBtaW5cblxucHJlcGFyZSA9ICgpIC0+XG5cdHAgPSAoMSBmb3IgaSBpbiByYW5nZSBOKVxuXHRmb3IgaSBpbiByYW5nZSAyLE5cblx0XHRpZiBwW2ldXG5cdFx0XHRmb3IgaiBpbiByYW5nZSAyKmksTixpXG5cdFx0XHRcdHBbal0gPSAwXG5cdGMqYyBmb3IgYyBpbiByYW5nZSAyLE4gd2hlbiBwW2NdPT0xXG5cbmYgPSAoYSkgLT5cblx0YW5zID0gMVxuXHRrbCA9IHt9XG5cdGhhc2ggPSB7fVxuXHRmb3IgcjAgaW4gYVxuXHRcdGlmIHIwIGluIGhhc2hcblx0XHRcdHIgPSBoYXNoW3IwXVxuXHRcdGVsc2Vcblx0XHRcdHIgPSByMFxuXHRcdFx0Zm9yIHEgaW4gcDJcblx0XHRcdFx0aWYgciA8IHFcblx0XHRcdFx0XHRicmVha1xuXHRcdFx0XHR3aGlsZSByICUgcSA9PSAwXG5cdFx0XHRcdFx0ciAvLz0gcVxuXHRcdFx0aGFzaFtyMF09clxuXHRcdGlmIHIgb2Yga2xcblx0XHRcdGFucyArPSAxXG5cdFx0XHRrbCA9IHt9XG5cdFx0a2xbcl0gPSAxXG5cdGFuc1xuXG5tYWluID0gLT5cblx0cDIgPSBwcmVwYXJlKClcblx0Zm9yIF8gaW4gcmFuZ2UgbnIoKVxuXHRcdFtfLF9dID0gbnJzKClcblx0XHRwcmludCBmIG5ycygpXG4iXX0=\n//# sourceURL=c:\\github\\2021\\010\\coffee\\app.coffee"}, {"source_code": "// Generated by CoffeeScript 2.4.1\n //_ = require 'underscore'\n\n //range = _.range\nvar N, currentLine, f, input, inputString, main, nr, nrs, p2, prepare, print, randint,\n indexOf = [].indexOf;\n\nprint = console.log;\n\nprocess.stdin.resume();\n\nprocess.stdin.setEncoding('utf-8');\n\ninputString = '';\n\ncurrentLine = 0;\n\nprocess.stdin.on('data', function(inputStdin) {\n return inputString += inputStdin;\n});\n\nprocess.stdin.on('end', function(_) {\n inputString = inputString.trim().split('\\n').map(function(string) {\n return string.trim();\n });\n return main();\n});\n\ninput = function() {\n return inputString[currentLine++];\n};\n\nnr = function() {\n return parseInt(input());\n};\n\nnrs = function() {\n var i, k, len, ref, results;\n ref = input().split(' ');\n results = [];\n for (k = 0, len = ref.length; k < len; k++) {\n i = ref[k];\n results.push(parseInt(i));\n }\n return results;\n};\n\n//##################################################\nN = 3162;\n\np2 = [];\n\nrandint = function(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n};\n\nprepare = function() {\n var c, i, j, k, l, m, p, ref, ref1, ref2, ref3, ref4, results;\n p = (function() {\n var k, ref, results;\n results = [];\n for (i = k = 0, ref = N; (0 <= ref ? k < ref : k > ref); i = 0 <= ref ? ++k : --k) {\n results.push(1);\n }\n return results;\n })();\n for (i = k = 2, ref = N; (2 <= ref ? k < ref : k > ref); i = 2 <= ref ? ++k : --k) {\n if (p[i]) {\n for (j = l = ref1 = 2 * i, ref2 = N, ref3 = i; ref3 !== 0 && (ref3 > 0 ? l < ref2 : l > ref2); j = l += ref3) {\n p[j] = 0;\n }\n }\n }\n results = [];\n for (c = m = 2, ref4 = N; (2 <= ref4 ? m < ref4 : m > ref4); c = 2 <= ref4 ? ++m : --m) {\n if (p[c] === 1) {\n results.push(c * c);\n }\n }\n return results;\n};\n\nf = function(a) {\n var ans, hash, k, kl, l, len, len1, q, r, r0;\n ans = 1;\n kl = {};\n hash = {};\n for (k = 0, len = a.length; k < len; k++) {\n r0 = a[k];\n if (indexOf.call(hash, r0) >= 0) {\n r = hash[r0];\n } else {\n r = r0;\n for (l = 0, len1 = p2.length; l < len1; l++) {\n q = p2[l];\n if (r < q) {\n break;\n }\n while (r % q === 0) {\n r = Math.floor(r / q);\n }\n }\n hash[r0] = r;\n }\n if (r in kl) {\n ans += 1;\n kl = {};\n }\n kl[r] = 1;\n }\n return ans;\n};\n\nmain = function() {\n var _, k, ref, results;\n //start = Date.now()\n p2 = prepare();\n results = [];\n for (_ = k = 0, ref = nr(); (0 <= ref ? k < ref : k > ref); _ = 0 <= ref ? ++k : --k) {\n [_, _] = nrs();\n results.push(print(f(nrs())));\n }\n return results;\n};\n\n// seed = 1;\n// random = () ->\n// \tx = Math.sin(seed++) * 10000\n// \tx - Math.floor(x)\n\n// print f (Math.floor 1 + 2000000 * random() for i in range 200000)\n// #f([9790577 for i in range(200000)])\n//print Date.now() - start,'ms'\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLmpzIiwic291cmNlUm9vdCI6Ii4uIiwic291cmNlcyI6WyJjb2ZmZWVcXGFwcC5jb2ZmZWUiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBOzs7QUFBQSxJQUFBLENBQUEsRUFBQSxXQUFBLEVBQUEsQ0FBQSxFQUFBLEtBQUEsRUFBQSxXQUFBLEVBQUEsSUFBQSxFQUFBLEVBQUEsRUFBQSxHQUFBLEVBQUEsRUFBQSxFQUFBLE9BQUEsRUFBQSxLQUFBLEVBQUEsT0FBQTtFQUFBOztBQUdBLEtBQUEsR0FBUSxPQUFPLENBQUM7O0FBRWhCLE9BQU8sQ0FBQyxLQUFLLENBQUMsTUFBZCxDQUFBOztBQUNBLE9BQU8sQ0FBQyxLQUFLLENBQUMsV0FBZCxDQUEwQixPQUExQjs7QUFFQSxXQUFBLEdBQWM7O0FBQ2QsV0FBQSxHQUFjOztBQUVkLE9BQU8sQ0FBQyxLQUFLLENBQUMsRUFBZCxDQUFpQixNQUFqQixFQUF5QixRQUFBLENBQUMsVUFBRCxDQUFBO1NBQWdCLFdBQUEsSUFBZTtBQUEvQixDQUF6Qjs7QUFFQSxPQUFPLENBQUMsS0FBSyxDQUFDLEVBQWQsQ0FBaUIsS0FBakIsRUFBd0IsUUFBQSxDQUFDLENBQUQsQ0FBQTtFQUN2QixXQUFBLEdBQWMsV0FBVyxDQUFDLElBQVosQ0FBQSxDQUFrQixDQUFDLEtBQW5CLENBQXlCLElBQXpCLENBQThCLENBQUMsR0FBL0IsQ0FBbUMsUUFBQSxDQUFDLE1BQUQsQ0FBQTtXQUFZLE1BQU0sQ0FBQyxJQUFQLENBQUE7RUFBWixDQUFuQztTQUNkLElBQUEsQ0FBQTtBQUZ1QixDQUF4Qjs7QUFJQSxLQUFBLEdBQVEsUUFBQSxDQUFBLENBQUE7U0FBRyxXQUFZLENBQUEsV0FBQSxFQUFBO0FBQWY7O0FBRVIsRUFBQSxHQUFLLFFBQUEsQ0FBQSxDQUFBO1NBQU0sUUFBQSxDQUFTLEtBQUEsQ0FBQSxDQUFUO0FBQU47O0FBQ0wsR0FBQSxHQUFNLFFBQUEsQ0FBQSxDQUFBO0FBQU0sTUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxHQUFBLEVBQUE7QUFBWTtBQUFBO0VBQUEsS0FBQSxxQ0FBQTs7aUJBQVgsUUFBQSxDQUFTLENBQVQ7RUFBVyxDQUFBOztBQUFsQixFQXBCTjs7O0FBd0JBLENBQUEsR0FBSTs7QUFDSixFQUFBLEdBQUs7O0FBRUwsT0FBQSxHQUFVLFFBQUEsQ0FBQyxHQUFELEVBQU0sR0FBTixDQUFBO1NBQWMsSUFBSSxDQUFDLEtBQUwsQ0FBVyxJQUFJLENBQUMsTUFBTCxDQUFBLENBQUEsR0FBZ0IsQ0FBQyxHQUFBLEdBQU0sR0FBTixHQUFZLENBQWIsQ0FBM0IsQ0FBQSxHQUErQztBQUE3RDs7QUFFVixPQUFBLEdBQVUsUUFBQSxDQUFBLENBQUE7QUFDVCxNQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLElBQUEsRUFBQSxJQUFBLEVBQUEsSUFBQSxFQUFBO0VBQUEsQ0FBQTs7QUFBTztJQUFBLEtBQVMsNEVBQVQ7bUJBQUY7SUFBRSxDQUFBOzs7RUFDUCxLQUFTLDRFQUFUO0lBQ0MsSUFBRyxDQUFFLENBQUEsQ0FBQSxDQUFMO01BQ0MsS0FBUyx1R0FBVDtRQUNDLENBQUUsQ0FBQSxDQUFBLENBQUYsR0FBTztNQURSLENBREQ7O0VBREQ7QUFJSTtFQUFBLEtBQVMsaUZBQVQ7UUFBc0IsQ0FBRSxDQUFBLENBQUEsQ0FBRixLQUFNO21CQUFoQyxDQUFBLEdBQUU7O0VBQUUsQ0FBQTs7QUFOSzs7QUFRVixDQUFBLEdBQUksUUFBQSxDQUFDLENBQUQsQ0FBQTtBQUNILE1BQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUEsRUFBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUE7RUFBQSxHQUFBLEdBQU07RUFDTixFQUFBLEdBQUssQ0FBQTtFQUNMLElBQUEsR0FBTyxDQUFBO0VBQ1AsS0FBQSxtQ0FBQTs7SUFDQyxJQUFHLGFBQU0sSUFBTixFQUFBLEVBQUEsTUFBSDtNQUNDLENBQUEsR0FBSSxJQUFLLENBQUEsRUFBQSxFQURWO0tBQUEsTUFBQTtNQUdDLENBQUEsR0FBSTtNQUNKLEtBQUEsc0NBQUE7O1FBQ0MsSUFBRyxDQUFBLEdBQUksQ0FBUDtBQUNDLGdCQUREOztBQUVBLGVBQU0sQ0FBQSxHQUFJLENBQUosS0FBUyxDQUFmO1VBQ0MsZUFBQSxJQUFNO1FBRFA7TUFIRDtNQUtBLElBQUssQ0FBQSxFQUFBLENBQUwsR0FBUyxFQVRWOztJQVVBLElBQUcsQ0FBQSxJQUFLLEVBQVI7TUFDQyxHQUFBLElBQU87TUFDUCxFQUFBLEdBQUssQ0FBQSxFQUZOOztJQUdBLEVBQUcsQ0FBQSxDQUFBLENBQUgsR0FBUTtFQWRUO1NBZUE7QUFuQkc7O0FBcUJKLElBQUEsR0FBTyxRQUFBLENBQUEsQ0FBQTtBQUVOLE1BQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsT0FBQTs7RUFBQSxFQUFBLEdBQUssT0FBQSxDQUFBO0FBQ0w7RUFBQSxLQUFTLCtFQUFUO0lBQ0MsQ0FBQyxDQUFELEVBQUcsQ0FBSCxDQUFBLEdBQVEsR0FBQSxDQUFBO2lCQUNSLEtBQUEsQ0FBTSxDQUFBLENBQUUsR0FBQSxDQUFBLENBQUYsQ0FBTjtFQUZELENBQUE7O0FBSE07O0FBMURQIiwic291cmNlc0NvbnRlbnQiOlsiI18gPSByZXF1aXJlICd1bmRlcnNjb3JlJ1xuXG4jcmFuZ2UgPSBfLnJhbmdlXG5wcmludCA9IGNvbnNvbGUubG9nXG5cbnByb2Nlc3Muc3RkaW4ucmVzdW1lKClcbnByb2Nlc3Muc3RkaW4uc2V0RW5jb2RpbmcgJ3V0Zi04J1xuIFxuaW5wdXRTdHJpbmcgPSAnJ1xuY3VycmVudExpbmUgPSAwXG4gXG5wcm9jZXNzLnN0ZGluLm9uICdkYXRhJywgKGlucHV0U3RkaW4pIC0+IGlucHV0U3RyaW5nICs9IGlucHV0U3RkaW5cbiBcbnByb2Nlc3Muc3RkaW4ub24gJ2VuZCcsIChfKSAtPiBcblx0aW5wdXRTdHJpbmcgPSBpbnB1dFN0cmluZy50cmltKCkuc3BsaXQoJ1xcbicpLm1hcCAoc3RyaW5nKSAtPiBzdHJpbmcudHJpbSgpXG5cdG1haW4oKVxuXG5pbnB1dCA9IC0+IGlucHV0U3RyaW5nW2N1cnJlbnRMaW5lKytdXG5cbm5yID0gKCkgLT4gcGFyc2VJbnQgaW5wdXQoKVxubnJzID0gKCkgLT4gKHBhcnNlSW50IGkgZm9yIGkgaW4gaW5wdXQoKS5zcGxpdCAnICcpXG5cbiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI1xuXG5OID0gMzE2MlxucDIgPSBbXVxuXG5yYW5kaW50ID0gKG1pbiwgbWF4KSAtPiBNYXRoLmZsb29yKE1hdGgucmFuZG9tKCkgKiAobWF4IC0gbWluICsgMSkgKSArIG1pblxuXG5wcmVwYXJlID0gKCkgLT5cblx0cCA9ICgxIGZvciBpIGluIFswLi4uTl0pXG5cdGZvciBpIGluIFsyLi4uTl1cblx0XHRpZiBwW2ldXG5cdFx0XHRmb3IgaiBpbiBbMippLi4uTl0gYnkgaVxuXHRcdFx0XHRwW2pdID0gMFxuXHRjKmMgZm9yIGMgaW4gWzIuLi5OXSB3aGVuIHBbY109PTFcblxuZiA9IChhKSAtPlxuXHRhbnMgPSAxXG5cdGtsID0ge31cblx0aGFzaCA9IHt9XG5cdGZvciByMCBpbiBhXG5cdFx0aWYgcjAgaW4gaGFzaFxuXHRcdFx0ciA9IGhhc2hbcjBdXG5cdFx0ZWxzZVxuXHRcdFx0ciA9IHIwXG5cdFx0XHRmb3IgcSBpbiBwMlxuXHRcdFx0XHRpZiByIDwgcVxuXHRcdFx0XHRcdGJyZWFrXG5cdFx0XHRcdHdoaWxlIHIgJSBxID09IDBcblx0XHRcdFx0XHRyIC8vPSBxXG5cdFx0XHRoYXNoW3IwXT1yXG5cdFx0aWYgciBvZiBrbFxuXHRcdFx0YW5zICs9IDFcblx0XHRcdGtsID0ge31cblx0XHRrbFtyXSA9IDFcblx0YW5zXG5cbm1haW4gPSAtPlxuXHQjc3RhcnQgPSBEYXRlLm5vdygpXG5cdHAyID0gcHJlcGFyZSgpXG5cdGZvciBfIGluIFswLi4ubnIoKV1cblx0XHRbXyxfXSA9IG5ycygpXG5cdFx0cHJpbnQgZiBucnMoKVxuXG5cdCMgc2VlZCA9IDE7XG5cdCMgcmFuZG9tID0gKCkgLT5cblx0IyBcdHggPSBNYXRoLnNpbihzZWVkKyspICogMTAwMDBcblx0IyBcdHggLSBNYXRoLmZsb29yKHgpXG5cblx0IyBwcmludCBmIChNYXRoLmZsb29yIDEgKyAyMDAwMDAwICogcmFuZG9tKCkgZm9yIGkgaW4gcmFuZ2UgMjAwMDAwKVxuXHQjICNmKFs5NzkwNTc3IGZvciBpIGluIHJhbmdlKDIwMDAwMCldKVxuXHQjcHJpbnQgRGF0ZS5ub3coKSAtIHN0YXJ0LCdtcydcblxuIl19\n//# sourceURL=c:\\github\\2021\\010\\coffee\\app.coffee"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 10e6+1\r\n\r\nfunction main() {\r\n const value = new Array(maxN + 1).fill(1);\r\n for (let i = 0; i < maxN + 1; i++) {\r\n value[i] = i\r\n }\r\n //\r\n for (let i = 2; i < maxN + 1; i++) {\r\n for (let j = i * i; j < maxN + 1; j += i) {\r\n while (value[j] % (i * i) === 0) {\r\n value[j] = value[j] / (i * i)\r\n }\r\n }\r\n }\r\n // console.log(value)\r\n var x = parseInt(readline())\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [n, k] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var aa = {}\r\n for (let i = 0; i < n; i++) {\r\n a[i] = value[a[i]]\r\n }\r\n\r\n var array = {}\r\n var ans = 0\r\n for (let i = 0; i < n; i++) {\r\n if (i === 0 || array[a[i]]) {\r\n ans++\r\n array = {}\r\n }\r\n array[a[i]] = true\r\n }\r\n // a = a.sort((a,b)=>a-b)\r\n // console.log(a)\r\n console.log(ans)\r\n\r\n });\r\n}\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 10e6+1\r\n\r\nfunction main() {\r\n const value = new Array(maxN + 1).fill(1);\r\n for (let i = 0; i < maxN + 1; i++) {\r\n value[i] = i\r\n }\r\n //\r\n for (let i = 2; i < maxN + 1; i++) {\r\n for (let j = i * i; j < maxN + 1; j += i) {\r\n if (value[j] % (i * i) === 0) {\r\n value[j] = value[j] / (i * i)\r\n }\r\n }\r\n }\r\n // console.log(value)\r\n var x = parseInt(readline())\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [n, k] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var aa = {}\r\n for (let i = 0; i < n; i++) {\r\n a[i] = value[a[i]]\r\n }\r\n\r\n var array = {}\r\n var ans = 0\r\n for (let i = 0; i < n; i++) {\r\n if (i === 0 || array[a[i]]) {\r\n ans++\r\n array = {}\r\n }\r\n array[a[i]] = true\r\n }\r\n // a = a.sort((a,b)=>a-b)\r\n // console.log(a)\r\n console.log(ans)\r\n\r\n });\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 10e6\r\n\r\nfunction main() {\r\n const value = new Array(maxN + 1).fill(1);\r\n for (let i = 0; i < maxN + 1; i++) {\r\n value[i] = i\r\n }\r\n //\r\n for (let i = 2; i < maxN + 1; i++) {\r\n for (let j = i * i; j < maxN + 1; j += i) {\r\n if (value[j] % (i * i) === 0) {\r\n value[j] = value[j] / (i * i)\r\n }\r\n }\r\n }\r\n // console.log(value)\r\n var x = parseInt(readline())\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [n, k] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var aa = {}\r\n for (let i = 0; i < n; i++) {\r\n a[i] = value[a[i]]\r\n }\r\n\r\n var array = {}\r\n var ans = 0\r\n for (let i = 0; i < n; i++) {\r\n if (i === 0 || array[a[i]]) {\r\n ans++\r\n array = {}\r\n }\r\n array[a[i]] = true\r\n }\r\n // a = a.sort((a,b)=>a-b)\r\n // console.log(a)\r\n console.log(ans)\r\n\r\n });\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 30\r\n\r\nfunction main() {\r\n const value = new Array(maxN + 1).fill(1);\r\n for (let i = 0; i < maxN + 1; i++) {\r\n value[i] = i\r\n }\r\n //\r\n for (let i = 2; i < maxN + 1; i++) {\r\n for (let j = i * i; j < maxN + 1; j += i) {\r\n if (value[j] % (i * i) === 0) {\r\n value[j] = value[j] / (i * i)\r\n }\r\n }\r\n }\r\n // console.log(value)\r\n var x = parseInt(readline())\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [n, k] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var aa = {}\r\n for (let i = 0; i < n; i++) {\r\n a[i] = value[a[i]]\r\n }\r\n\r\n var array = []\r\n var ans = 0\r\n for (let i = 0; i < n; i++) {\r\n if (i === 0 || array.includes(a[i])) {\r\n ans++\r\n array = []\r\n }\r\n array.push(a[i])\r\n }\r\n // a = a.sort((a,b)=>a-b)\r\n // console.log(a)\r\n console.log(ans)\r\n\r\n });\r\n}\r\n"}], "src_uid": "878c2e57a396187ccef51d0f941386cf"} {"nl": {"description": "Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \\le T \\le 1\\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \\le a, b \\le 10^{9}$$$) — the current volume and Bob's desired volume, respectively.", "output_spec": "For each test case, output a single integer — the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.", "sample_inputs": ["3\n4 0\n5 14\n3 9"], "sample_outputs": ["2\n3\n2"], "notes": "NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$. "}, "positive_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n// thats all what you have to write to get input from stdin, using readLine.\n\n\n// Main code runs in main();\n\n\nfunction main() {\n let testCases = readline();\n while(testCases --){\n var line2 = readline();\n let data = line2.split(' ').map(x => parseInt(x));\n checkSound(data);\n }\n}\n\nfunction checkSound([sound1, sound2]){\n let difference = Math.abs(sound1-sound2);\n let steps = 0;\n steps += parseInt(difference/5);\n if(difference%5 == 1 || difference%5 == 2){\n steps++;\n }\n else if(difference%5 == 3 || difference%5 == 4){\n steps += 2;\n }\n console.log(steps)\n}\n"}, {"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n const c = [0, 1, 1, 2, 2, 1]\n for(let i = 0; i < t; i++) {\n const arrT = arr[i].split(' ').map(a => parseInt(a))\n const a = arrT[0]\n const b = arrT[1]\n\n if(a == b) console.log(0)\n else {\n let diff = Math.abs(a - b)\n let count = Math.floor(diff / 5)\n diff = diff - count * 5\n\n count += c[diff]\n\n console.log(count)\n }\n }\n})"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n');\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr('time : ' + end + 'ms');\n myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var one = nextIntArray();\n var a = one[0];\n var b = one[1];\n var diff = Math.abs(a - b);\n var count = Math.floor(diff / 5);\n diff %= 5;\n count += Math.floor(diff / 2);\n diff %= 2;\n count += diff;\n output[i] = count;\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let [a, b] = d.split(' ').map(Number);\n let ans = 0;\n let target = Math.abs(a - b);\n const values = [5, 2, 1];\n let idx = 0;\n\n while (target > 0) {\n ans += Math.floor(target / values[idx]);\n target %= values[idx];\n idx++;\n }\n\n console.log(ans);\n c++;\n});\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n\nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n\nlet nl = nextLine();\n\nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n\nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\tlet n = nl.num();\n let ans = [];\n for(let i = 0; i < n; i++){\n let [a, b] = nl.nums();\n a = Math.abs(a - b);\n let c = Math.trunc(a/5);\n a %= 5;\n c += Math.trunc(a/2);\n a %= 2;\n c += a;\n ans.push(c);\n }\n\tconsole.log(ans.join('\\n'));\n\n};\n\nprocess.stdin.on('end', sol);\n"}, {"source_code": "var n = parseInt(readline());\nvar v = [0,1,1,2,2];\n\nfor(var i = 0;i parseInt(v));\n var d = Math.abs(arr[0] - arr[1]);\n print(Math.floor(d/5) + v[d%5]);\n}"}, {"source_code": "var t = readline();\nvar result = [];\nfor (var i = 0; i < t; i++) {\n\tvar input = readline().split(\" \");\n\tvar diff = input[1] - input[0];\n\tvar count = 0;\n\tvar temp_count = 0;\n\tvar button = [-5,-2,-1,1,2,5];\n\tif (diff < 0) {\n\t\tfor (var j = 0; j < button.length && diff != 0; j++) {\n\t\t\tif (diff <= button[j]) {\n\t\t\t\ttemp_count = Math.floor(diff/button[j]);\n\t\t\t\tcount += temp_count;\n\t\t\t\tdiff -= button[j]*temp_count;\n\t\t\t}\n\t\t}\n\t} else if (diff > 0) {\n\t\tfor (var j = button.length - 1; j >= 0 && diff != 0; j--) {\n\t\t\tif (diff >= button[j]) {\n\t\t\t\ttemp_count = Math.floor(diff/button[j]);\n\t\t\t\tcount += temp_count;\n\t\t\t\tdiff -= button[j]*temp_count;\n\t\t\t}\n\t\t}\n\t}\n\tresult.push(count);\n}\nfor (var i = 0; i < result.length; i++) {\n\tprint(result[i]);\n}"}, {"source_code": "'use strict';\n\nvar t=parseInt(readline());\n\nwhile(t--)\n{\n var inp = readline().split(' ').map(Number);\n var a=inp[0];\n var b=inp[1];\n var cnt=Math.abs(a-b);\n \n var res=0;\n \n while(cnt)\n {\n if(cnt>=5){\n var tmp=parseInt(cnt/5);\n cnt-=(tmp*5);\n res+=tmp;\n }\n else if(cnt>=2){\n var tmp=parseInt(cnt/2);\n cnt-=(tmp*2);\n res+=tmp;\n }\n else {\n res+=cnt;\n cnt=0;\n }\n }\n\n print(res);\n}"}, {"source_code": "\nvar go = function(a, b, steps, floor){\n var add = steps * floor;\n if(a0){\n var h1 = go(a, b, steps, floor);\n var h2 = go(a, b, steps, floor+1);\n if(h2 === null) return floor + h1;\n else return floor + Math.min(h1,1 + h2);\n }\n else{\n h1 = go(a, b, steps, 1); \n if(h1 === null) return 0;\n else return 1 + go(a, b, steps, 1);\n }\n}\nvar countSteps = function(a,b){\n if(a==b) return 0;\n var diff = Math.abs(b-a);\n if(diff > 6){\n return toward(a,b,5);\n }else if(diff === 1 || diff === 2 || diff === 5){\n return 1;\n }else{\n return 2;\n }\n}\n\nvar n = parseInt(readline());\nvar i = 0;\nwhile(i 0) {\n\t\tfor (var j = button.length - 1; j >= 0 && diff != 0; j--) {\n\t\t\tif (diff > button[j]) {\n\t\t\t\tcount += Math.floor(diff/button[j]);\n\t\t\t\tdiff -= button[j]*count;\n\t\t\t}\n\t\t}\n\t}\n\tresult.push(count);\n}\nfor (var i = 0; i < result.length; i++) {\n\tprint(result[i]);\n}"}, {"source_code": "'use strict';\n\nvar t=Number(readline());\n\nwhile(t--)\n{\n var inp = readline().split(' ').map(Number);\n var a=inp[0];\n var b=inp[1];\n\n var cnt=Math.abs(a-b);\n\n var res=0;\n\n while(cnt)\n {\n if(cnt>=5){\n var tmp=cnt/5;\n cnt-=(tmp*5);\n res+=tmp;\n }\n else if(cnt>=2){\n var tmp=cnt/2;\n cnt-=(tmp*2);\n res+=tmp;\n }\n else {\n res+=cnt;\n cnt=0;\n }\n }\n\n print(res);\n}"}, {"source_code": "'use strict';\n\nvar t=parseInt(readline());\n\nwhile(t--)\n{\n var inp = readline().split(' ').map(parseInt);\n var a=inp[0];\n var b=inp[1];\n\n var cnt=parseInt (Math.abs(a-b));\n\n var res=0;\n\n while(cnt)\n {\n if(cnt>=5){\n var tmp=parseInt(cnt/5);\n cnt-=(tmp*5);\n res+=tmp;\n }\n else if(cnt>=2){\n var tmp=parseInt(cnt/2);\n cnt-=(tmp*2);\n res+=tmp;\n }\n else {\n res+=cnt;\n cnt=0;\n }\n }\n\n print(res);\n}"}], "src_uid": "ccfe798f5dc63c492ff54cf40bb40613"} {"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$$$) — 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$$$) — 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 — 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": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (inputStd) => {\n inputString += inputStd;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n let _ = readLine();\n let str = readLine();\n let stack = [];\n for (let i = 0; i < str.length; i++) {\n let char = str[i];\n if (stack[stack.length - 1] === \"(\" && char === \")\") {\n stack.pop();\n } else {\n stack.push(char);\n }\n }\n console.log(stack.length / 2);\n }\n}\n"}, {"source_code": "//↓見なくていいよ!ここから--------------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n \n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n\n//↑見なくていいよ!ここまで--------------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar n = nextInt();\n\t\tvar list = next();\n\t\twhile(list.indexOf(\"()\") != -1){\n\t\t\tlist = list.replace(\"()\",\"\");\n\t\t}\n\t\toutput[i] = list.length / 2;\n\t}\n\tmyout(myconv(output,9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n data = data.split('\\n');\n const testCases = data[0] * 2;\n let i = 1;\n while (i <= testCases) {\n let n = +data[i];\n let s = data[i + 1].trim();\n let count = 0;\n for (let j = 0; j < s.length; j += 1) {\n if (s[j] === '(') count += 1;\n else if (count && s[j] === ')') count -= 1;\n }\n console.log(count);\n i += 2;\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n function solve(sequence) {\n var moves = 0;\n var offset = 0;\n for (var i=0; i= 1) { offset--; }\n else { moves++; }\n }\n }\n return moves;\n }\n const testCases = parseInt(readline());\n for (var i=0; i {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map(str => str.trim());\n\tmain();\n});\n\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\nconst store = {};\n\nfunction main() {\n\tlet t = readLine() >> 0;\n\n\twhile (t--) {\n\t\tlet n = readLine();\n\t\tlet s = readLine().split('');\n\t\tlet pos = 0,\n\t\t\tmove = 0;\n\n\t\ts.forEach(p => {\n\t\t\tif (p === '(') {\n\t\t\t\tpos++;\n\t\t\t} else {\n\t\t\t\tpos--;\n\t\t\t\tif (pos < 0) {\n\t\t\t\t\tpos = 0;\n\t\t\t\t\tmove++;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tconsole.log(move);\n\t}\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n4\n2\n)(\n4\n()()\n8\n())()()(\n10\n)))((((())\n\n\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() { \n let n = parseInt(readline());\n\n for(let r=0;r {\n if (lineCount == 0) {\n // first line\n testCount = parseInt(input)\n }\n else if(lineCount%2==1){\n //do nothing?\n }\n else if (lineCount >= 2*testCount) {\n outputStr += compute(input) + '\\n'\n console.log(outputStr)\n rl.close()\n }\n else {\n // data\n outputStr += compute(input) + '\\n'\n }\n lineCount++\n});\n\nfunction compute(str) {\n for(var i=str.length-2;i>=0;i--){\n if(str[i]=='('&&str[i+1]==')'){\n // 删除他俩\n str = `${str.substring(0,i)}${str.substring(i+2, str.length)}`\n }\n }\n return str.length / 2\n}"}, {"source_code": "var n = readline();\nvar llen = [];\nvar inp = [];\nfor (var i = 0; i0)\n open--;\n else\n close++;\n }\n }\n print(close);\n}"}, {"source_code": "var testCase = Number(readline());\nwhile(testCase--)\n{\n\treadline();\n\tvar str = readline();\n\tfor( var i=1;i<=25;i++)\n\t{\n\t\tstr=str.replace('()','');\n\t}\n\tprint(Math.floor(str.length/2));\n}"}, {"source_code": "function solve() {\n var n = Number(read());\n var s = read();\n var min = 0;\n var sum = 0;\n for (var i = 0; i < n; i++) {\n sum += s[i] === '(' ? 1 : -1;\n if (sum < min) {\n min = sum;\n }\n }\n write(0 - min);\n}\n\nfunction init() {\n var T;\n T = 1;\n T = Number(read());\n for (var t = 0; t < T; t++) {\n solve();\n }\n}\n\n\nvar isNode = typeof console !== 'undefined';\nvar MEMORY = [];\nvar MEMORY_INDEX = 0;\nif (isNode) {\n var fs = require('fs');\n var path = require('path');\n \n var inTextName;\n var outTextName;\n if (process.argv.length === 5) {\n inTextName = process.argv[3];\n outTextName = process.argv[4];\n }\n \n if (inTextName) {\n fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {\n MEMORY = data.split('\\r\\n');\n init();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', init);\n }\n} else {\n init();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}], "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 + 1)-th painter (if j < n); 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, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), 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, ti2, ..., tin (1 ≤ tij ≤ 1000), 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, r2, ..., rm, 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": "print(function(m, n) {\n var i, j, ans=[], a=[];\n for(var i=0; i parseInt(readline());\ngetFlt = () => parseFloat(readline());\ngetArrInt = () => readline().split(' ').map(x => parseInt(x));\ngetArrFlt = () => readline().split(' ').map(x => parseFloat(x));\nInt = (x) => Math.floor(x);\n\nnums = getArrInt();\nm = nums[0];\nn = nums[1];\n\n\nvar t = new Array(m + 1);\nfor(i = 0; i <= m; i++) t[i] = new Array(n + 1);\n\nfor (var i = 1; i <= m; i++){\n\ttijs = \n\treadline()\n\t.split(' ')\n\t.map(x => parseInt(x))\n\t.forEach((el, j) => {\n\t\tt[i][j + 1] = el;\n\t});\n}\n\n\ndp = new Array( m + 1 ).fill(0);\nfor(var worker = 1; worker <= n; worker++){\n\tvar getFree = 0;\n\tfor(var pic = 1; pic <= m; pic++){\n\t\tgetFree = Math.max(getFree, dp[pic]);\n\t\tdp[pic] = getFree + t[pic][worker];\n\t\tgetFree = dp[pic];\n\t}\n}\n\nfor(var pic = 1; pic <= m; pic++){\n\twrite (dp[pic] + \" \");\n}"}, {"source_code": "getInt = () => parseInt(readline());\ngetFlt = () => parseFloat(readline());\ngetArrInt = () => readline().split(' ').map(x => parseInt(x));\ngetArrFlt = () => readline().split(' ').map(x => parseFloat(x));\nInt = (x) => Math.floor(x);\n\nnums = getArrInt();\nm = nums[0];\nn = nums[1];\n\n\nvar t = new Array(m + 1);\nfor(i = 0; i <= m; i++) t[i] = new Array(n + 1);\n\nfor (var i = 1; i <= m; i++){\n\ttijs = readline().split(' ').map(x => parseInt(x));\n\ttijs.forEach((el, j) => {\n\t\tt[i][j + 1] = el;\n\t})\n}\n\n\ndp = new Array( m + 1 ).fill(0);\nfor(var worker = 1; worker <= n; worker++){\n\tvar getFree = 0;\n\tfor(var pic = 1; pic <= m; pic++){\n\t\tgetFree = Math.max(getFree, dp[pic]);\n\t\tdp[pic] = getFree + t[pic][worker];\n\t\tgetFree = dp[pic];\n\t}\n}\n\nfor(var pic = 1; pic <= m; pic++){\n\twrite (dp[pic] + \" \");\n}"}, {"source_code": "getInt = () => parseInt(readline());\ngetFlt = () => parseFloat(readline());\ngetArrInt = () => readline().split(' ').map(x => parseInt(x));\ngetArrFlt = () => readline().split(' ').map(x => parseFloat(x));\nInt = (x) => Math.floor(x);\n\nnums = getArrInt();\nm = nums[0];\nn = nums[1];\n\n\nvar t = [];\nfor(i = 0; i <= m; i++) t[i] = [];\n\nfor (var i = 1; i <= m; i++){\n\ttijs = readline().split(' ').map(x => parseInt(x));\n\ttijs.forEach((el, j) => {\n\t\tt[i][j + 1] = el;\n\t})\n}\n\n\ndp = new Array( m + 1 ).fill(0);\nfor(var worker = 1; worker <= n; worker++){\n\tvar getFree = 0;\n\tfor(var pic = 1; pic <= m; pic++){\n\t\tgetFree = Math.max(getFree, dp[pic]);\n\t\tdp[pic] = getFree + t[pic][worker];\n\t\tgetFree = dp[pic];\n\t}\n}\n\nfor(var pic = 1; pic <= m; pic++){\n\twrite (dp[pic] + \" \");\n}"}, {"source_code": "print(function(m, n){\n\tvar i, j, ans = [], a = [];\n\tfor(i=0; i 1) {\n for (var i = 1; i < pictures; i++) {\n for(var j = 1; j < autors; j++) {\n before = parseInt(info[i-1][j], 10);\n actual = parseInt(info[i][j-1], 10);\n info[i][j] = Math.max(before,actual) + parseInt(info[i][j]);\n }\n }\n}\n\nvar result = [];\nfor (var i = 0; i < info.length; i++) {\n result.push(info[i].pop());\n}\nprint(result.join(' '));"}], "negative_code": [{"source_code": "print(function(m, n) {\n var i, j, ans=[], a=[];\n for(var i=0; i= 0; i--) {\n for (var j = n - 1; j > i; j--) {\n var minV = Infinity;\n minV = Math.min(minV, s[i+1][j] + 1);\n for (var k = i+1; k <= j; k++) {\n if (a[i] == a[k]) \n minV = Math.min(minV, ((k-1 >= 0) ? (Math.max(s[i+1][k-1], 1)) : 0) + ((k+1 < n) ? s[k+1][j] : 0));\n }\n \n if (a[i] == a[i+1] && i+2 < n) minV = Math.min(minV, s[i+2][j] + 1);\n s[i][j] = minV;\n }\n}\n\nwrite(s[0][n-1]);"}], "negative_code": [], "src_uid": "f942ed9c5e707d12be42d3ab55f39441"} {"nl": {"description": "A sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day di he will deposit ti rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following m days.Determine the number of days starting from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.", "input_spec": "The first line contains three integers n, p and m (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 109, 1 ≤ m ≤ 109, n ≤ m) — the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check. The i-th of the following n lines contains two integers di and ti (1 ≤ di ≤ m, 1 ≤ ti ≤ 109) — the index of the day when Arkady will make the i-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i. e. di > di - 1 for all i from 2 to n.", "output_spec": "Print the number of days from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment.", "sample_inputs": ["3 6 7\n2 13\n4 20\n7 9", "5 4 100\n10 70\n15 76\n21 12\n30 100\n67 85"], "sample_outputs": ["3", "26"], "notes": "NoteIn the first example the balance will change as following (remember, initially the balance is zero): in the first day 6 rubles will be charged, the balance in the evening will be equal to  - 6; in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1; in the third day 6 rubles will be charged, the balance in the evening will be equal to  - 5; in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9; in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3; in the sixth day 6 rubles will be charged, the balance in the evening will be equal to  - 3; in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0. Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day."}, "positive_code": [{"source_code": "function parseNumber(x) { \n return parseInt(x); \n}\n\nvar numbers = readline().split(\" \").map(parseNumber);\nvar N = numbers[0], P = numbers[1], M = numbers[2];\nvar balance = 0, numOfDays = 0, payments = [];\nvar lastPaidDay = 0;\n\nfor(var i = 0; i < N; i++) {\n var pay = readline().split(\" \").map(parseNumber);\n\tvar day = pay[0];\n\tvar value = pay[1];\n\t\n\tvar positiveDays = Math.floor(balance / P);\n\tpositiveDays = positiveDays > 0 ? positiveDays : 0;\n\t\n\tvar countedDays = day - lastPaidDay - 1;\n\tvar negDays = countedDays - positiveDays;\n\tbalance -= P*countedDays;\n\t\n\tif(negDays > 0) {\n\t\tnumOfDays+=negDays;\n\t}\n\t\n\tbalance = balance + value - P;\n\tif(balance < 0) {\n\t\tnumOfDays++;\n\t}\n\t\n\tlastPaidDay = day;\n}\n\nvar positiveDays = Math.floor(balance / P);\npositiveDays = positiveDays > 0 ? positiveDays : 0;\nvar countedDays = M - lastPaidDay;\nvar negDays = countedDays - positiveDays\nbalance -= P*countedDays;\n\nif(negDays > 0) {\n\tnumOfDays+=negDays;\n}\n\nwrite(numOfDays);"}, {"source_code": "function min(a, b) {\n if (a < b) {\n return a;\n } else {\n return b;\n }\n}\n\nvar line_0 = readline().split(' ');\n\nvar n = parseInt(line_0[0]);\nvar p = parseInt(line_0[1]);\nvar m = parseInt(line_0[2]);\n\nvar answer = 0;\n\nvar balance = 0;\nvar day = 1;\nfor (var i = 1; i <= n; ++i) {\n var line = readline().split(' ');\n\n var d = parseInt(line[0]);\n var t = parseInt(line[1]);\n \n //print(d, day, (d - day) * p);\n \n balance -= (d - day) * p;\n if (balance < 0) {\n var tmp = -balance;\n var add = min(d - day, Math.ceil(tmp / p));\n answer += add;\n //print(\"!!\", add, \"!!\", balance, Math.ceil(tmp / p), d - day);\n }\n balance += t;\n day = d;\n}\n//print(answer);\n\nbalance -= (m+1 - day) * p;\nif (balance < 0) {\n var tmp = -balance;\n //print(\"@@\", m - day);\n answer += min(m+1 - day, Math.ceil(tmp / p));\n}\nprint(answer);"}], "negative_code": [{"source_code": "function parseNumber(x) { \n return parseInt(x); \n}\n\nvar numbers = readline().split(\" \").map(parseNumber);\nvar N = numbers[0], P = numbers[1], M = numbers[2];\nvar balance = 0, numOfDays = 0, payments = [];\nvar lastPaidDay = 0;\n\nfor(var i = 0; i < N; i++) {\n var pay = readline().split(\" \").map(parseNumber);\n\tvar day = pay[0];\n\tvar value = pay[1];\n\t\n\tvar positiveDays = Math.floor(balance / P);\n\t\n\tvar countedDays = day - lastPaidDay - 1;\n\tvar negDays = countedDays - positiveDays;\n\tbalance -= P*countedDays;\n\t\n\tif(negDays > 0) {\n\t\tnumOfDays+=negDays;\n\t}\n\t\n\tbalance = balance + value - P;\n\tif(balance < 0) {\n\t\tnumOfDays++;\n\t}\n\t\n\tlastPaidDay = day;\n}\n\nvar positiveDays = Math.floor(balance / P);\nvar countedDays = M - lastPaidDay;\nvar negDays = countedDays - positiveDays\nbalance -= P*countedDays;\n\nif(negDays > 0) {\n\tnumOfDays+=negDays;\n}\n\nwrite(numOfDays);"}], "src_uid": "09fa979c7654a0cc79e1bb29500e1dec"} {"nl": {"description": "All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $$$n\\cdot m$$$ different seals, denoted by distinct numbers. All of them were written in an $$$n\\times m$$$ table.The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.", "input_spec": "The first line of the input contains the only integer $$$t$$$ ($$$1\\leq t\\leq 100\\,000$$$) denoting the number of test cases. Their descriptions follow. The first line of each test case description consists of two space-separated integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 500$$$) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from $$$1$$$ to $$$n\\cdot m$$$. The following $$$n$$$ lines contain $$$m$$$ space separated integers each, denoting elements of an arbitrary row in the table left to right. The following $$$m$$$ lines contain $$$n$$$ space separated integers each, denoting elements of an arbitrary column in the table top to bottom. Sum of $$$nm$$$ over all test cases does not exceed $$$250\\,000$$$. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from $$$1$$$ to $$$nm$$$ occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.", "output_spec": "For each test case, output $$$n$$$ lines with $$$m$$$ space-separated integers each, denoting the restored table. One can show that the answer is always unique.", "sample_inputs": ["2\n2 3\n6 5 4\n1 2 3\n1 6\n2 5\n3 4\n3 1\n2\n3\n1\n3 1 2"], "sample_outputs": ["1 2 3 \n6 5 4 \n3 \n1 \n2"], "notes": "NoteConsider the first test case. The matrix is $$$2 \\times 3$$$. You are given the rows and columns in arbitrary order.One of the rows is $$$[6, 5, 4]$$$. One of the rows is $$$[1, 2, 3]$$$.One of the columns is $$$[1, 6]$$$. One of the columns is $$$[2, 5]$$$. One of the columns is $$$[3, 4]$$$.You are to reconstruct the matrix. The answer is given in the output."}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [rowLen, colLen] = readLine().split(\" \").map(Number);\n const [rowMap, colMap] = [new Map(), new Map()];\n const result = [...Array(rowLen).fill(0)].map((_) => Array(colLen).fill(0));\n for (let i = 0; i < rowLen; i++) {\n readLine()\n .split(\" \")\n .map((n, index) => {\n n = parseInt(n);\n colMap.set(n, index);\n });\n }\n for (let i = 0; i < colLen; i++) {\n readLine()\n .split(\" \")\n .map((n, index) => {\n n = parseInt(n);\n rowMap.set(n, index);\n const col = colMap.get(n);\n result[index][col] = n;\n });\n }\n\n for (let i = 0; i < rowLen; i++) {\n console.log(result[i].join(\" \"));\n }\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = [];\n\tfor(var i = 0; i < t; i++){\n\t\tvar one = nextIntArray();\n\t\tvar N = one[0];\n\t\tvar M = one[1];\n\t\tvar list = new Array(N);\n\t\tfor(var j = 0; j < N; j++){\n\t\t\tlist[j] = new Array(M);\n\t\t}\n\t\tvar check = new Array(N);\n\t\tvar check2 = new Array(M);\n\t\tvar map = {};\n\t\tfor(var j = 0; j < N; j++){\n\t\t\tcheck[j] = nextIntArray();\n\t\t\tfor(var k = 0; k < M; k++){\n\t\t\t\tmap[check[j][k]] = k;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(var j = 0; j < M; j++){\n\t\t\ttmp = nextIntArray();\n\t\t\tvar L = map[tmp[0]];\n\t\t\tfor(var k = 0; k < N; k++){\n\t\t\t\tlist[k][L] = tmp[k];\n\t\t\t}\n\t\t}\n\t\tfor(var j = 0; j < N; j++){\n\t\t\toutput.push(myconv(list[j], 8));\n\t\t}\n\n\t}\n\tmyout(myconv(output, 9));\n}\nfunction lcm(m, n) {return (m / gcd(m, n)) * n;}\tfunction gcd(m, n) {return n != 0 ? gcd(n, m % n) : m;}"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;et.toString())).join(\"\\n\"):this.join(\" \")}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});const o=n(r(747));let s=\"\",i=[],u=0,l=\"\";const a=\"local\"===process.argv[2],p=t=>{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return i[u++]}function h(){return f().split(\" \").map((t=>parseFloat(t)))}function c(){return f().split(\"\")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:f,nextNumbers:h,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),p=Array.numbersMatrix(t,e),f=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols = a.transpose()\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.deepCopy().map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// let h = Array.numbersMatrix(n, m)\n// let k = 0\n// \n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// h[i][j] = a[k][j]\n// }\n// k++\n// }\n// \n// io.puts(h.toString())\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function p(){return i[u++]}function c(){return p().split(\" \").map((t=>parseFloat(t)))}function h(){return p().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=c();for(;e>0;)t(),e--}))},readline:p,nextNumbers:c,nextNumbersMatrix:function(t){let e=[];for(let r=0;r[...t].sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),f=Array.numbersMatrix(t,e),p=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols: number[][] = []\n// \n// for (let j = 0; j < m; ++j) {\n// let s: number[] = []\n// for (let i = 0; i < n; ++i) {\n// s.push(a[i][j])\n// }\n// cols.push(s)\n// }\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.map((x) => [...x].sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// // io.debug(f)\n// // io.debug(cols[0])\n// // io.debug(cols[0][0])\n// // io.debug(f.indexOf(cols[0][0]))\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// // io.debug(indices)\n// \n// let h = Array.numbersMatrix(n, m)\n// \n// let k = 0\n// \n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// io.debug(i + \" \" + j)\n// h[i][j] = a[k][j]\n// // io.debug(h)\n// }\n// k++\n// }\n// \n// for (let i = 0; i < n; ++i) {\n// io.puts(h[i].join(\" \"))\n// }\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return i[u++]}function h(){return f().split(\" \").map((t=>parseFloat(t)))}function c(){return f().split(\"\")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:f,nextNumbers:h,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),p=Array.numbersMatrix(t,e),f=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols = a.transpose()\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.deepCopy().map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// let h = Array.numbersMatrix(n, m)\n// let k = 0\n// \n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// h[i][j] = a[k][j]\n// }\n// k++\n// }\n// \n// io.puts(h.toString())\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;et.toString())).join(\"\\n\"):this.join(\" \")}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});const o=n(r(747));let s=\"\",i=[],u=0,l=\"\";const a=\"local\"===process.argv[2],p=t=>{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return i[u++]}function h(){return f().split(\" \").map((t=>parseFloat(t)))}function c(){return f().split(\"\")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:f,nextNumbers:h,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),p=Array.numbersMatrix(t,e),f=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols = a.transpose()\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.deepCopy().map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// let h = Array.numbersMatrix(n, m)\n// \n// let k = 0\n// \n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// h[i][j] = a[k][j]\n// }\n// k++\n// }\n// \n// io.puts(h.toString())\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;et.toString())).join(\"\\n\"):this.join(\" \")}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});const o=n(r(747));let s=\"\",i=[],u=0,l=\"\";const a=\"local\"===process.argv[2],p=t=>{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return i[u++]}function h(){return f().split(\" \").map((t=>parseFloat(t)))}function c(){return f().split(\"\")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:f,nextNumbers:h,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),p=Array.numbersMatrix(t,e),f=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols = a.transpose()\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.deepCopy().map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// let h = Array.numbersMatrix(n, m)\n// let k = 0\n// \n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// h[i][j] = a[k][j]\n// }\n// k++\n// }\n// \n// for (let i = 0; i < n; ++i) {\n// io.puts(h[i].join(\" \"))\n// }\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function f(){return i[u++]}function c(){return f().split(\" \").map((t=>parseFloat(t)))}function h(){return f().split(\"\")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=c();for(;e>0;)t(),e--}))},readline:f,nextNumbers:c,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),p=Array.numbersMatrix(t,e),f=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols: number[][] = []\n// \n// for (let j = 0; j < m; ++j) {\n// let s: number[] = []\n// for (let i = 0; i < n; ++i) {\n// s.push(a[i][j])\n// }\n// cols.push(s)\n// }\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.deepCopy().map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// // io.debug(f)\n// // io.debug(cols[0])\n// // io.debug(cols[0][0])\n// // io.debug(f.indexOf(cols[0][0]))\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// // io.debug(indices)\n// \n// let h = Array.numbersMatrix(n, m)\n// \n// let k = 0\n// \n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// io.debug(i + \" \" + j)\n// h[i][j] = a[k][j]\n// // io.debug(h)\n// }\n// k++\n// }\n// \n// for (let i = 0; i < n; ++i) {\n// io.puts(h[i].join(\" \"))\n// }\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n B();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction B(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [n,m] = ti(readline().split(' '));\n let cols = new Array(n);\n for(let i = 0; i < n; i++){\n cols[i] = readline().split(' ');\n }\n\n let rows = new Array(m);\n for(let i = 0; i < m; i++){\n rows[i] = readline().split(' ');\n }\n\n let map = new Array(10);\n for(let i = 0; i < n; i++){\n for(let j = 0; j < m; j++){\n map[pi(cols[i][j])] = new Array(2);\n map[pi(cols[i][j])][1] = j;\n }\n }\n\n for(let i = 0; i < m; i++){\n for(let j = 0; j < n; j++){\n map[pi(rows[i][j])][0] = j;\n }\n }\n\n let res = new Array(n);\n for(let i = 0; i < n; i++){\n res[i] = new Array(m);\n }\n\n for(let i = 0; i < n; i++){\n for(let j = 0; j < m; j++){\n let r = map[pi(cols[i][j])][0];\n let c = map[pi(cols[i][j])][1];\n res[r][c] = cols[i][j];\n }\n }\n\n for(let i = 0; i < n; i++){\n console.log(res[i].join(' '));\n }\n }\n}"}], "negative_code": [{"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function p(){return i[u++]}function c(){return p().split(\" \").map((t=>parseFloat(t)))}function h(){return p().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=c();for(;e>0;)t(),e--}))},readline:p,nextNumbers:c,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),f=Array.numbersMatrix(t,e),p=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols: number[][] = []\n// \n// for (let j = 0; j < m; ++j) {\n// let s: number[] = []\n// for (let i = 0; i < n; ++i) {\n// s.push(a[i][j])\n// }\n// cols.push(s)\n// }\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// let h = Array.numbersMatrix(n, m)\n// \n// let k = 0\n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// // io.debug(i + \" \" + j)\n// h[k][j] = a[i][j]\n// // io.debug(h)\n// }\n// k++\n// }\n// \n// for (let i = 0; i < n; ++i) {\n// io.puts(h[i].join(\" \"))\n// }\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;ot-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function p(){return i[u++]}function c(){return p().split(\" \").map((t=>parseFloat(t)))}function h(){return p().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=c();for(;e>0;)t(),e--}))},readline:p,nextNumbers:c,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),f=Array.numbersMatrix(t,e),p=0;for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols: number[][] = []\n// \n// for (let j = 0; j < m; ++j) {\n// let s: number[] = []\n// for (let i = 0; i < n; ++i) {\n// s.push(a[i][j])\n// }\n// cols.push(s)\n// }\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// let h = Array.numbersMatrix(n, m)\n// \n// let k = 0\n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// // io.debug(i + \" \" + j)\n// h[i][j] = a[k][j]\n// // io.debug(h)\n// }\n// k++\n// }\n// \n// for (let i = 0; i < n; ++i) {\n// io.puts(h[i].join(\" \"))\n// }\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(a){if(i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),o.default.writeFileSync(\"output.txt\",l),console.log(l),o.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{s+=t})),process.stdin.on(\"end\",(e=>{i=s.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function c(){return i[u++]}function p(){return c().split(\" \").map((t=>parseFloat(t)))}function h(){return c().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=p();for(;e>0;)t(),e--}))},readline:c,nextNumbers:p,nextNumbersMatrix:function(t){let e=[];for(let r=0;rt.sortAsc().join(\"\"))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t)));for(let t of a){for(let n=0;n{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n, m] = io.nextNumbers()\n// let a = io.nextNumbersMatrix(n)\n// \n// let cols: number[][] = []\n// \n// for (let j = 0; j < m; ++j) {\n// let s: number[] = []\n// for (let i = 0; i < n; ++i) {\n// s.push(a[i][j])\n// }\n// cols.push(s)\n// }\n// \n// let c = [...cols[0]].sortAsc().join(\"\")\n// let b = io.nextNumbersMatrix(m)\n// let bb = b.map((x) => x.sortAsc().join(\"\"))\n// \n// let f = b[bb.findIndex((x) => x == c)]\n// \n// let indices = cols[0].map((x) => f.indexOf(x))\n// \n// for (let i of indices) {\n// for (let j = 0; j < m; ++j) {\n// io.put(a[i][j] + \" \")\n// }\n// io.put(\"\\n\")\n// }\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}], "src_uid": "0eab9d2dd60d38f68d49f30cff918fce"} {"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$$$) — 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": "var n = +readline();\nvar a = readline().split(' ').map(Number).sort((x,y)=>y-x),b = readline().split(' ').map(Number).sort((x,y)=>y-x), turna = true, i = 0,j =0;\nvar suma = 0, sumb = 0;\nwhile (i < n && j < n){\n if (turna){\n turna = false;\n if (a[i] >= b[j]){\n suma += a[i];\n i++;\n } else if (a[i] < b[j]){\n j++;\n }\n } else {\n turna = true;\n if (b[j] >= a[i]){\n sumb += b[j];\n j++;\n } else if (b[j] < a[i]){\n i++;\n }\n }\n}\nif (i !== n){\n if (!turna) i++;\n while (i < n){\n suma += a[i];\n i+=2;\n }\n} else if (j !== n) {\n if (turna) j++;\n while (j < n){\n sumb += b[j];\n j+= 2;\n }\n}\nprint(suma - sumb);"}, {"source_code": "// Gambling - https://codeforces.com/problemset/problem/1038/C\n\nconst main = async () => {\n let listLen = 0;\n const listA = [];\n const listB = [];\n \n const rl = require(\"readline\").createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n \n for await (const line of rl) {\n if (!listLen) {\n listLen = Number(line);\n } else {\n if (listA.length < listLen) {\n sortList(line.split(' ')).map((item)=> listA.push(Number(item)));\n } else {\n rl.close();\n sortList(line.split(' ')).map((item)=> listB.push(Number(item)));\n }\n }\n }\n \n runGame(listLen, listA, listB);\n };\n\n const sortList = (list) => list.sort((a, b) => a - b)\n \n const runGame = (listLen, listA, listB) => {\n\n\n let scoreA = 0;\n let scoreB = 0;\n\n for (let i = 0; i <= listLen * 2; i++) {\n // console.log({listA, scoreA, '':'', scoreB, listB})\n if (i % 2 === 0) {\n if (!listB.length || listA[listA.length - 1] > listB[listB.length - 1]) {\n scoreA += listA[listA.length - 1] || 0;\n listA.pop()\n } else {\n listB.pop()\n }\n } else {\n if (!listA.length || listB[listB.length - 1] > listA[listA.length - 1]) {\n scoreB += listB[listB.length - 1] || 0;\n listB.pop()\n } else {\n listA.pop()\n }\n }\n \n }\n\n console.log(scoreA - scoreB);\n };\n \n \n main();"}], "negative_code": [{"source_code": "var n = +readline();\nvar a = readline().split(' ').map(Number).sort((x,y)=>y-x),b = readline().split(' ').map(Number).sort((x,y)=>y-x), turna = true, i = 0,j =0;\nvar suma = 0, sumb = 0;\nwhile (i < n && j < n){\n if (turna){\n turna = false;\n if (a[i] > b[j]){\n suma += a[i];\n i++;\n } else if (a[i] < b[j]){\n j++;\n } else {\n i++;\n j++;\n }\n } else {\n turna = true;\n if (b[j] > a[i]){\n sumb += b[j];\n j++;\n } else if (b[j] < a[i]){\n i++;\n } else {\n i++;j++;\n }\n }\n}\nif (i !== n){\n while (i < n){\n suma += a[i];\n i+=2;\n }\n} else if (j !== n) {\n while (j < n){\n sumb += b[j];\n j+= 2;\n }\n}\nprint(suma - sumb);"}, {"source_code": "var n = +readline();\nvar a = readline().split(' ').map(Number).sort((x,y)=>y-x),b = readline().split(' ').map(Number).sort((x,y)=>y-x), turna = true, i = 0,j =0;\nvar suma = 0, sumb = 0;\nwhile (i < n && j < n){\n if (turna){\n turna = false;\n if (a[i] >= b[j]){\n suma += a[i];\n i++;\n } else if (a[i] < b[j]){\n j++;\n }\n } else {\n turna = true;\n if (b[j] >= a[i]){\n sumb += b[j];\n j++;\n } else if (b[j] < a[i]){\n i++;\n }\n }\n}\nif (i !== n){\n while (i < n){\n suma += a[i];\n i+=2;\n }\n} else if (j !== n) {\n while (j < n){\n sumb += b[j];\n j+= 2;\n }\n}\nprint(suma - sumb);"}], "src_uid": "d740f4ee1b18eeb74dfb253125c52762"} {"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 - 1 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 = 5, 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, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.", "input_spec": "The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears. The second line contains n digits a1, a2, ..., an (0 ≤ ai ≤ n - 1) — 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": "function ProblemSolver() {\n this.HAS_TEST_CASES = false ;\n this.INPUT_FILE_NAME = \"sample.in\" ;\n this.OUTPUT_FILE_NAME = \"sample.out\" ;\n this.DO_OUTPUT_TO_FILE = false ;\n this.CLEAR_ARRAY_PER_CASE = false ;\n\n this.solveCase = function() {\n var res , i , j , fl , cn , a , b , c , d , e ;\n res = false ;\n a = 0 ;\n b = 0 ;\n for( i = 0 ; i < this.n ; i++ ) {\n c = this.arr[ i ] ;\n d = 0 ;\n if( b == 0 ) {\n while( true ) {\n if( c == a ) {\n break ;\n }\n d++ ;\n c = ( c + 1 ) % this.n ;\n }\n }\n else {\n while( true ) {\n if( c == a ) {\n break ;\n }\n d++ ;\n c = ( c - 1 + this.n ) % this.n ;\n }\n }\n this.brr[ i ] = d ;\n b = ! b ;\n a++ ;\n }\n a = 1 ;\n for( i = 1 ; i < this.n ; i++ ) {\n if( this.brr[ i ] != this.brr[ i - 1 ] ) {\n a = 0 ;\n break ;\n }\n }\n if( a == 1 ) {\n res = true ;\n }\n else {\n a = 0 ;\n b = 0 ;\n for( j = 0 ; j < 10000 ; j++ ) {\n e = 1 ;\n for( i = 0 ; i < this.n ; i++ ) {\n c = this.arr[ i ] ;\n if( b == 0 ) {\n this.arr[ i ] = ( this.arr[ i ] + 1 ) % this.n ;\n }\n else {\n this.arr[ i ] = ( this.arr[ i ] - 1 + this.n ) % this.n ;\n }\n if( this.arr[ i ] != i ) {\n e = 0 ;\n }\n b = ! b ;\n a++ ;\n }\n if( e == 1 ) {\n res = true ;\n break ;\n }\n }\n }\n if( res == true ) {\n print( 'Yes' ) ;\n }\n else {\n print( 'No' ) ;\n }\n } ;\n\n this.init = function() {\n this.lim1 = 100010 ;\n this.lim2 = 110 ;\n this.cc = 1 ;\n this.ind = 1 ;\n this.n = 0 ;\n this.cn = 0 ;\n this.declareAndFillArrays() ;\n } ;\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i ;\n hasMoreInput = true ;\n try {\n \tthis.n = irObj.nextInt() ;\n this.arr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n this.arr.push( irObj.nextInt() ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false ;\n }\n return hasMoreInput ;\n } ;\n\n this.clearArraysPerCase = function() {\n var i ;\n this.arr = new Array() ;\n this.adjList = new Array() ;\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 ) ;\n this.adjList.push( new Array() ) ;\n }\n } ;\n\n this.clearPerCase = function() {\n this.cn = 0 ;\n this.cc++ ;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n } ;\n\n this.declareAndFillArrays = function() {\n var i , j ;\n this.srr = new Array() ;\n this.vis = new Array() ;\n this.arr = new Array() ;\n this.brr = new Array() ;\n this.memo = new Array() ;\n this.done = new Array() ;\n this.adjList = new Array() ;\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( '' ) ;\n this.vis.push( 0 ) ;\n this.arr.push( 0 ) ;\n this.brr.push( 0 ) ;\n this.adjList.push( new Array() ) ;\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() ) ;\n this.done.push( new Array() ) ;\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 ) ;\n this.done[ i ].push( 0 ) ;\n }\n }\n } ;\n\n this.init() ;\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array() ;\n this.currrentLineNumber = 0 ;\n this.currrentCharacterIndex = 0 ;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine ;\n while( true ) {\n try {\n singleLine = readline() ;\n if( singleLine == null ) {\n break ;\n }\n }\n catch( ex ) {\n break ;\n }\n this.allLines.push( singleLine ) ;\n }\n } ;\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n } ;\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n } ;\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n } ;\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n } ;\n\n this.parseRawData = function( data ) {\n var len , i , currentString ;\n len = data.length ;\n currentString = '' ;\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString ) ;\n currentString = '' ;\n }\n else {\n currentString += data[ i ] ;\n }\n }\n if( currentString != '' ) {\n this.allLines.push( currentString ) ;\n }\n } ;\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData ;\n fsObj = require( 'fs' ) ;\n currentDirectory = __dirname ;\n if( currentDirectory.indexOf( 'D:' ) != -1 ) {\n //on windows\n inputFilePath = currentDirectory + '\\\\' + inputFileName ;\n }\n else {\n //on linux\n inputFilePath = currentDirectory + '/' + inputFileName ;\n }\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" ) ;\n this.parseRawData( rawData ) ;\n } ;\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx ;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n }\n res = '' ;\n len = this.allLines[ this.currrentLineNumber ].length ;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n return res ;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( 'No more tokens available!' ) ;\n }\n startIdx = -1 ;\n len = this.allLines[ this.currrentLineNumber ].length ;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i ;\n break ;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n continue ;\n }\n res = '' ;\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i ;\n break ;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n }\n this.currrentCharacterIndex = endIdx ;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n }\n return res ;\n }\n } ;\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) ) ;\n } ;\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) ) ;\n } ;\n\n this.nextString = function() {\n return this.next( 1 ) ;\n } ;\n\n this.nextLine = function() {\n return this.next( 0 ) ;\n } ;\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array() ;\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString ) ;\n } ;\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array() ;\n } ;\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath ;\n res = '' ;\n sz = this.resultantStringArray.length ;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += '\\n' ;\n }\n res += this.resultantStringArray[ i ] ;\n }\n fsObj = require( 'fs' ) ;\n currentDirectory = __dirname ;\n if( currentDirectory.indexOf( 'D:' ) != -1 ) {\n //on windows\n outputFilePath = currentDirectory + '\\\\' + outputFileName ;\n }\n else {\n //on linux\n outputFilePath = currentDirectory + '/' + outputFileName ;\n }\n fsObj.writeFileSync( outputFilePath , res ) ;\n this.clearPercase() ;\n } ;\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader() ;\n this.psObj = new ProblemSolver() ;\n this.fohObj = new FileOutputHandler() ;\n\n this.runCases = function() {\n\t\tvar testCases , hasMoreTestCases , i ;\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt() ;\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase() ;\n this.psObj.getInput( this.irObj ) ;\n this.psObj.solveCase() ;\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase() ;\n hasMoreTestCases = this.psObj.getInput( this.irObj ) ;\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase() ;\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME ) ;\n }\n } ;\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && ( __dirname.indexOf( 'D:') != -1 || __dirname.indexOf( '/media/') != -1 ) ) {\n environmentType = 'local-node-js' ;\n }\n else {\n environmentType = 'server-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n } ;\n\n this.configureStreamsAndReadInput = function() {\n var localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log ;\n }\n }\n catch( ex ) {\n print = console.log ;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj ;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments ) ;\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME ) ;\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log ;\n }\n }\n catch( ex ) {\n print = console.log ;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines() ;\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino() ;\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines() ;\n this.runCases() ;\n }\n } ;\n \n this.configureStreamsAndReadInput() ;\n}\n\nnew CodeExecutioner() ;\n"}, {"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false ;\n this.INPUT_FILE_NAME = \"sample.in\" ;\n this.OUTPUT_FILE_NAME = \"sample.out\" ;\n this.DO_OUTPUT_TO_FILE = false ;\n this.CLEAR_ARRAY_PER_CASE = false ;\n\n this.solveCase = function() {\n var res , i , j , fl , cn , a , b , c , d , e ;\n res = false ;\n a = 0 ;\n b = 0 ;\n for( i = 0 ; i < this.n ; i++ ) {\n c = this.arr[ i ] ;\n d = 0 ;\n if( b == 0 ) {\n while( true ) {\n if( c == a ) {\n break ;\n }\n d++ ;\n c = ( c + 1 ) % this.n ;\n }\n }\n else {\n while( true ) {\n if( c == a ) {\n break ;\n }\n d++ ;\n c = ( c - 1 + this.n ) % this.n ;\n }\n }\n this.brr[ i ] = d ;\n b = ! b ;\n a++ ;\n }\n a = 1 ;\n for( i = 1 ; i < this.n ; i++ ) {\n if( this.brr[ i ] != this.brr[ i - 1 ] ) {\n a = 0 ;\n break ;\n }\n }\n if( a == 1 ) {\n res = true ;\n }\n else {\n }\n if( res == true ) {\n print( 'Yes' ) ;\n }\n else {\n print( 'No' ) ;\n }\n } ;\n\n this.init = function() {\n this.lim1 = 100010 ;\n this.lim2 = 110 ;\n this.cc = 1 ;\n this.ind = 1 ;\n this.n = 0 ;\n this.cn = 0 ;\n this.declareAndFillArrays() ;\n } ;\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i ;\n hasMoreInput = true ;\n try {\n \tthis.n = irObj.nextInt() ;\n this.arr = [] ;\n for( i = 0 ; i < this.n ; i++ ) {\n this.arr.push( irObj.nextInt() ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false ;\n }\n return hasMoreInput ;\n } ;\n\n this.clearArraysPerCase = function() {\n var i ;\n this.arr = new Array() ;\n this.adjList = new Array() ;\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 ) ;\n this.adjList.push( new Array() ) ;\n }\n } ;\n\n this.clearPerCase = function() {\n this.cn = 0 ;\n this.cc++ ;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n } ;\n\n this.declareAndFillArrays = function() {\n var i , j ;\n this.srr = new Array() ;\n this.vis = new Array() ;\n this.arr = new Array() ;\n this.brr = new Array() ;\n this.memo = new Array() ;\n this.done = new Array() ;\n this.adjList = new Array() ;\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( '' ) ;\n this.vis.push( 0 ) ;\n this.arr.push( 0 ) ;\n this.brr.push( 0 ) ;\n this.adjList.push( new Array() ) ;\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() ) ;\n this.done.push( new Array() ) ;\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 ) ;\n this.done[ i ].push( 0 ) ;\n }\n }\n } ;\n\n this.init() ;\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array() ;\n this.currrentLineNumber = 0 ;\n this.currrentCharacterIndex = 0 ;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine ;\n while( true ) {\n try {\n singleLine = readline() ;\n if( singleLine == null ) {\n break ;\n }\n }\n catch( ex ) {\n break ;\n }\n this.allLines.push( singleLine ) ;\n }\n } ;\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n } ;\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n } ;\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n } ;\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n } ;\n\n this.parseRawData = function( data ) {\n var len , i , currentString ;\n len = data.length ;\n currentString = '' ;\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString ) ;\n currentString = '' ;\n }\n else {\n currentString += data[ i ] ;\n }\n }\n if( currentString != '' ) {\n this.allLines.push( currentString ) ;\n }\n } ;\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData ;\n fsObj = require( 'fs' ) ;\n currentDirectory = __dirname ;\n if( currentDirectory.indexOf( 'D:' ) != -1 ) {\n //on windows\n inputFilePath = currentDirectory + '\\\\' + inputFileName ;\n }\n else {\n //on linux\n inputFilePath = currentDirectory + '/' + inputFileName ;\n }\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" ) ;\n this.parseRawData( rawData ) ;\n } ;\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx ;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n }\n res = '' ;\n len = this.allLines[ this.currrentLineNumber ].length ;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n return res ;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( 'No more tokens available!' ) ;\n }\n startIdx = -1 ;\n len = this.allLines[ this.currrentLineNumber ].length ;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i ;\n break ;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n continue ;\n }\n res = '' ;\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i ;\n break ;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n }\n this.currrentCharacterIndex = endIdx ;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++ ;\n this.currrentCharacterIndex = 0 ;\n }\n return res ;\n }\n } ;\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) ) ;\n } ;\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) ) ;\n } ;\n\n this.nextString = function() {\n return this.next( 1 ) ;\n } ;\n\n this.nextLine = function() {\n return this.next( 0 ) ;\n } ;\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array() ;\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString ) ;\n } ;\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array() ;\n } ;\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath ;\n res = '' ;\n sz = this.resultantStringArray.length ;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += '\\n' ;\n }\n res += this.resultantStringArray[ i ] ;\n }\n fsObj = require( 'fs' ) ;\n currentDirectory = __dirname ;\n if( currentDirectory.indexOf( 'D:' ) != -1 ) {\n //on windows\n outputFilePath = currentDirectory + '\\\\' + outputFileName ;\n }\n else {\n //on linux\n outputFilePath = currentDirectory + '/' + outputFileName ;\n }\n fsObj.writeFileSync( outputFilePath , res ) ;\n this.clearPercase() ;\n } ;\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader() ;\n this.psObj = new ProblemSolver() ;\n this.fohObj = new FileOutputHandler() ;\n\n this.runCases = function() {\n\t\tvar testCases , hasMoreTestCases , i ;\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt() ;\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase() ;\n this.psObj.getInput( this.irObj ) ;\n this.psObj.solveCase() ;\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase() ;\n hasMoreTestCases = this.psObj.getInput( this.irObj ) ;\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase() ;\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME ) ;\n }\n } ;\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && ( __dirname.indexOf( 'D:') != -1 || __dirname.indexOf( '/media/') != -1 ) ) {\n environmentType = 'local-node-js' ;\n }\n else {\n environmentType = 'server-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n } ;\n\n this.configureStreamsAndReadInput = function() {\n var localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log ;\n }\n }\n catch( ex ) {\n print = console.log ;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj ;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments ) ;\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME ) ;\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log ;\n }\n }\n catch( ex ) {\n print = console.log ;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines() ;\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino() ;\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines() ;\n this.runCases() ;\n }\n } ;\n \n this.configureStreamsAndReadInput() ;\n}\n\nnew CodeExecutioner() ;\n"}, {"source_code": "var n = parseInt(readline());\nvar actives = readline().split(' ').map(function(a){\n\treturn parseInt(a);\n});\n\nfunction is_finished() {\n\tfor (var i = 0; i < n; i++) {\n\t\tif (actives[i] != i) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction action() {\n\tfor (var i = 0; i < n; i++) {\n\t\tif (i % 2) {\n\t\t\tactives[i]--;\n\t\t} else {\n\t\t\tactives[i]++; \n\t\t}\n\t\tif (actives[i] < 0) {\n\t\t\tactives[i] = n-1;\n\t\t}\n\t\tactives[i] = actives[i] % n;\n\t}\n}\n\nvar finished = false;\n\nfor (var i = 0; i < n; i++) {\n\tif (is_finished()) {\n\t\tprint('Yes');\n\t\tfinished=true;\n\t\tbreak;\n\t}\n\taction();\n}\nif (!finished) {\n\tprint('No');\n}"}, {"source_code": "var n = Number(readline());\n\nvar gears = readline().split(' ').map(Number);\nvar trueGears = [],\n res = 'NO';\n\nNumber.prototype.mod = function(n) {\n return ((this%n)+n)%n;\n};\n\nfor (var i = 0; i < n; i++) {\n trueGears.push(i);\n}\n\nfor (var j = 0; j < n; j++) {\n for (i = 0; i < gears.length; i++) {\n if ( i % 2 == 0 ) {\n gears[i]++;\n } else {\n gears[i]--;\n }\n\n gears[i] = gears[i].mod(n);\n }\n\n if ( arrayEqual(trueGears, gears) ) {\n res = 'YES';\n break;\n }\n}\n\nprint( res );\n\nfunction arrayEqual(arr1, arr2) {\n if ( arr1.length !== arr2.length ) {\n return false;\n }\n\n for (var i = 0; i < arr2.length; i++) {\n if ( arr2[i] !== arr1[i] ) {\n return false;\n }\n }\n\n return true;\n};\n\n"}], "negative_code": [], "src_uid": "6c65ca365352380052b0c9d693e6d161"} {"nl": {"description": "Zibi is a competitive programming coach. There are $$$n$$$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the $$$i$$$-th competitor will always have score $$$x_i$$$ when he codes the first task and $$$y_i$$$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are $$$m$$$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\le n \\le 300\\,000$$$, $$$0 \\le m \\le 300\\,000$$$) — the number of participants and the number of pairs of people who will not write a contest together. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^9 \\le x_i, y_i \\le 10^9$$$) — the scores which will the $$$i$$$-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both $$$x_i$$$ and $$$y_i$$$ same. Each of the next $$$m$$$ lines contain two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$) — indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.", "output_spec": "Output $$$n$$$ integers — the sum of scores for all participants in the same order as they appear in the input.", "sample_inputs": ["3 2\n1 2\n2 3\n1 3\n1 2\n2 3", "3 3\n1 2\n2 3\n1 3\n1 2\n2 3\n1 3", "5 3\n-1 3\n2 4\n1 1\n3 5\n2 2\n1 4\n2 3\n3 5"], "sample_outputs": ["3 0 3", "0 0 0", "4 14 4 16 10"], "notes": "NoteIn the first example, there will be only one team consisting of persons $$$1$$$ and $$$3$$$. The optimal strategy for them is to assign the first task to the $$$3$$$-rd person and the second task to the $$$1$$$-st person, this will lead to score equal to $$$1 + 2 = 3$$$.In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case..."}, "positive_code": [{"source_code": " 'use strict';\n\n const first_line = readline().split(' ').map(Number);\n const n = first_line[0];\n const m = first_line[1];\n\n const ans = new Array(n);\n\n const x = new Array(n);\n const y = new Array(n);\n const diff = new Array(n);\n for (let i = 0; i < n; i++) {\n const line = readline().split(' ').map(Number);\n x[i] = line[0];\n y[i] = line[1];\n\n diff[i] = [y[i] - x[i], i];\n }\n\n diff.sort(function(lhs, rhs) {return (lhs[0] !== rhs[0]) ? lhs[0] - rhs[0] : lhs[1] - rhs[1]});\n\n const prefsum = new Array(n + 1);\n prefsum[0] = 0;\n for (let i = 0; i < n; i++) {\n const id = diff[i][1];\n prefsum[i + 1] = prefsum[i] + y[id];\n }\n\n const suffsum = new Array(n + 1);\n suffsum[n] = 0;\n for (let i = n - 1; i >= 0; i--) {\n const id = diff[i][1];\n suffsum[i] = suffsum[i + 1] + x[id];\n }\n\n for (let i = 0; i < n; i++) {\n const id = diff[i][1];\n ans[id] = prefsum[i] + x[id] * i + suffsum[i + 1] + y[id] * (n - i - 1);\n }\n\n for (let i = 0; i < m; i++) {\n const line = readline().split(' ').map(Number);\n const v = line[0] - 1;\n const u = line[1] - 1;\n const score = Math.min(x[v] + y[u], x[u] + y[v]);\n ans[v] -= score;\n ans[u] -= score;\n }\n\n print(ans.join(' '));\n"}, {"source_code": "function split(v) {\n var pos = v.indexOf(' ');\n return [+v.substr(0, pos), +v.substr(pos + 1)]\n}\n\nvar fl = readline().split(' ').map(v=>+v);\nvar persCnt = fl[0];\nvar pairsCnt = fl[1];\n\nvar persons = [], scores = [], all1 = 0, all2 = 0;\nfor(var i = 0; i < persCnt; i++) {\n var rl = split(readline());\n persons.push([i, rl[0], rl[1], rl[1] - rl[0], 0]);\n \n all2 += rl[1]\n}\n\nfor(i = 0; i < pairsCnt; i++) {\n var pair = split(readline());\n var person1 = persons[pair[0] - 1];\n var person2 = persons[pair[1] - 1];\n var sum = person1[3] > person2[3] \n ? person1[1] + person2[2]\n : person1[2] + person2[1]\n\n person1[4] -= sum\n person2[4] -= sum\n}\n\nscores.length = persCnt;\n\npersons.sort((a, b) => a[3] > b[3] ? -1 : 1);\nfor(var i = 0; i < persCnt; i++) {\n var person = persons[i]\n all2-=person[2]\n scores[person[0]] = \n person[1] * (persCnt - i - 1) +\n person[2] * i \n + all2 + all1 \n + person[4]\n \n all1+=person[1]\n}\n\nprint(scores.join(' '));"}], "negative_code": [], "src_uid": "d0cb479bbe2fca382a439148af77e082"} {"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 — $$$6$$$ — 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": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n const arr = Array(len).fill(1);\n console.log(arr.join(\" \"));\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar N = nextInt();\n\t\tvar s = new Array(N).fill(1);\n\t\toutput[i] = myconv(s, 8);\n\t}\n\tmyout(myconv(output, 9));\n}\n"}, {"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;it-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e{if(p){if(s=i.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),i.default.writeFileSync(\"output.txt\",l),console.log(l),i.default.readFileSync(\"expected.txt\").toString().trim()==l.trim()){const{exec:t}=r(129);t(\"osascript -e 'display notification \\\"✅ AC!!\\\"'\")}}else process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{o+=t})),process.stdin.on(\"end\",(e=>{s=o.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function h(){return s[u++]}function f(){return h().split(\" \").map((t=>parseFloat(t)))}function c(){return h().split(\"\")}e.default={runMain:a,runEachTest:t=>{a((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:h,nextNumbers:f,nextBigNumbers:function(){return h().split(\" \").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r{t.exports=require(\"child_process\")},747:t=>{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();\n\n// Solution written in typescript and compiled via webpack. Original source code below\n// Happy Hacking 😜\n\n\n// import './array'\n// \n// import io from './io'\n// \n// function main() {\n// let [n] = io.nextNumbers()\n// \n// io.puts(\"1 \".repeat(n))\n// }\n// \n// io.runEachTest(main)\n// // io.runMain(main)"}, {"source_code": "let input = ''\n\nprocess.stdin.on('data', (x) => input += x)\n\nprocess.stdin.on('end', () => {\n input.trim().split('\\n').slice(1).map((x) => parseInt(x)).forEach((n) => {\n console.log([...new Array(n)].map(() => 1).join(' '))\n })\n})\n\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n3\n1\n2\n4\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction lcm(a, b) {\n return (a / gcd(a, b) * b);\n}\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n3\n1\n2\n4\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction lcm(a, b) {\n return (a / gcd(a, b) * b);\n}\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r sum += item)\n if (sum % arr.length === 0) {\n return true\n } else {\n return false\n }\n }\n \n function geter(arr) {\n var arr2 = []\n arr.map((item,index) => {\n if (index !== arr.length - 2) {\n arr2.push(item)\n }\n })\n var flag = checker(arr2)\n return flag\n }\n \n for (var i = 0; i < t; i++) {\n \n var n = +readline()\n var arr = []\n \n if (n % 2 === 0) {\n var num = 2\n for (j = 0; j < n; j++) {\n arr.push(num)\n num += 2\n var tempArr = arr\n var flag = geter(arr)\n if (!flag) {\n while (!flag) {\n tempArr = tempArr.filter((el,i) => i !== arr.length - 1)\n num += 1\n tempArr.push(num)\n flag = geter(tempArr)\n }\n arr = tempArr\n }\n }\n } else {\n var num = 1\n for (j = 0; j < n; j++) {\n arr.push(num)\n num += 2\n var tempArr = arr\n var flag = geter(arr)\n if (!flag) {\n while (!flag) {\n tempArr = tempArr.filter((el,i) => i !== arr.length - 1)\n num += 1\n tempArr.push(num)\n flag = geter(tempArr)\n }\n arr = tempArr\n }\n }\n }\n print(arr)\n }\n \n}())"}, {"source_code": "var t = +readline();\n\nfor (var i = 0; i < t; i++) {\n var l = +readline();\n var res = [];\n \n if (l === 1) {\n var num = Math.floor(Math.random() * (100 - 1) + 1);\n \n if (num % 2 !== 0) {\n num++;\n }\n \n print(num.toString().replace(/\\,/g, ' '));\n } else {\n for (var j = 0; j < l; j++) {\n var num = Math.floor(Math.random() * (100 - 0) + 0);\n \n while (num % l !== 0) {\n num = Math.floor(Math.random() * (100 - 0) + 0);\n }\n \n res[j] = num;\n }\n \n print(res.toString().replace(/\\,/g, ' '));\n }\n}\n"}, {"source_code": "var t = +readline();\n\nfor (var i = 0; i < t; i++) {\n var l = +readline();\n var res = [];\n \n if (l === 1) {\n var num = Math.floor(Math.random() * (100 - 1) + 1);\n \n if (num % 2 !== 0) {\n num++;\n }\n \n print(num.toString().replace(/\\,/g, ' '));\n } else {\n for (var j = 0; j < l; j++) {\n var num = Math.floor(Math.random() * (100 - 1) + 1);\n \n while (num % l !== 0) {\n num = Math.floor(Math.random() * (100 - 1) + 1);\n }\n \n res[j] = num;\n }\n \n print(res.toString().replace(/\\,/g, ' '));\n }\n}\n"}, {"source_code": "var t = +readline();\n\nfor (var i = 0; i < t; i++) {\n var l = +readline();\n var res = [];\n \n if (l === 1) {\n var num = Math.floor(Math.random() * (100 - 0) + 0);\n \n if (num % 2 !== 0) {\n num++;\n }\n \n print(num.toString().replace(/\\,/g, ' '));\n } else {\n for (var j = 0; j < l; j++) {\n var num = Math.floor(Math.random() * (100 - 0) + 0);\n \n if (num % 2 === 0) {\n num++;\n }\n \n res[j] = num;\n }\n \n print(res.toString().replace(/\\,/g, ' '));\n }\n}\n"}], "src_uid": "da2ac80c2ad6abae676d60a506eb05fc"} {"nl": {"description": "C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term): expression ::= summand | expression + summand | expression - summand summand ::= increment | coefficient*increment increment ::= a++ | ++a coefficient ::= 0|1|2|...|1000 For example, \"5*a++-3*++a+a++\" is a valid expression in C*++.Thus, we have a sum consisting of several summands divided by signs \"+\" or \"-\". Every summand is an expression \"a++\" or \"++a\" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains \"a++\", then during the calculation first the value of the \"a\" variable is multiplied by the coefficient, then value of \"a\" is increased by 1. If the summand contains \"++a\", then the actions on it are performed in the reverse order: first \"a\" is increased by 1, then — multiplied by the coefficient.The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.", "input_spec": "The first input line contains an integer a ( - 1000 ≤ a ≤ 1000) — the initial value of the variable \"a\". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation. ", "output_spec": "Output a single number — the maximal possible value of the expression.", "sample_inputs": ["1\n5*a++-3*++a+a++", "3\na+++++a"], "sample_outputs": ["11", "8"], "notes": "NoteConsider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too."}, "positive_code": [{"source_code": "'use strict'\n\nlet a = +readline()\nlet lll = readline()\nif (lll[0] != '-') lll = '+' + lll\n\nlet ss = {}\nfor (let i = -1000; i <= 1000; i++) {\n ss[i] = []\n}\n\nlet i = 0\nwhile (i < lll.length) {\n let z = 1\n let k = 1\n let b = true\n z = lll[i] == '+' ? z = 1 : -1\n i++\n let idp = lll.indexOf('++', i)\n let ia = lll.indexOf('*', i)\n k = ~ia && ia < idp ? +lll.slice(i, ia) : 1\n if (~ia && ia < idp) i = ia + 1\n b = lll[idp + 2] == 'a'\n ss[z * k].push(b)\n i += 3\n}\n\nlet s = 0\nfor (let i = -1000; i <= 1000; i++) {\n let bef = 0\n let aft = 0\n ss[i].forEach(v => v ? bef++ : aft++)\n if (i < 0) {\n for (let j = 0; j < aft; j++) {\n s += i * a++\n }\n for (let j = 0; j < bef; j++) {\n s += i * ++a\n }\n } else {\n for (let j = 0; j < bef; j++) {\n s += i * ++a\n }\n for (let j = 0; j < aft; j++) {\n s += i * a++\n }\n }\n}\n\nprint(s)"}], "negative_code": [], "src_uid": "766196c156234cc169206dbb7a932fc7"} {"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$$$) — 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": "\nfunction main() {\n const is = new Scanner();\n const LIMIT = parseInt(1e9, 10) + 1;\n const powerOfTwo = [1];\n while (powerOfTwo[powerOfTwo.length - 1] < LIMIT)\n powerOfTwo.push(2 * powerOfTwo[powerOfTwo.length - 1]);\n\n const n = is.nextInt();\n const sequence = is.nextArray();\n const tmpMap = {};\n let maxElement = 0;\n for (let i = 0; i < n; i++) { // conver numbers\n sequence[i] = parseInt(sequence[i], 10);\n maxElement = Math.max(maxElement, sequence[i]);\n if (!tmpMap.hasOwnProperty(sequence[i]))\n tmpMap[sequence[i]] = [];\n tmpMap[sequence[i]].push(i);\n }\n\n let answer = 0, canIUse;\n sequence.forEach((i) => {\n canIUse = false;\n for (let j = lowerBound(powerOfTwo, i + 1); powerOfTwo[j] <= i + maxElement && j < powerOfTwo.length; j += 1)\n if (tmpMap.hasOwnProperty(powerOfTwo[j] - i)) {\n canIUse = true;\n if (i === (powerOfTwo[j] - i) && tmpMap[i].length === 1)\n canIUse = false;\n }\n\n if (!canIUse)\n answer++;\n // console.log(i, canIUse);\n });\n\n console.log(answer);\n}\n\n\nfunction lowerBound(array, value) {\n let left = 0, middle;\n let right = array.length;\n while (left < right) {\n middle = parseInt((left + right) / 2);\n if (value <= array[middle])\n right = middle;\n else\n left = middle + 1;\n }\n\n return left; // not found\n}\n\n\n/*\n * api stdin\n */\n\nclass Scanner {\n constructor() {\n this.index = 0;\n this.lines = stdinInput.trim().split('\\n');\n }\n\n nextLine() {\n return this.lines[this.index++];\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray() {\n return this.nextLine().split(' ');\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', input => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}], "negative_code": [{"source_code": "\nfunction main() {\n const is = new Scanner();\n const LIMIT = parseInt(1e9, 10) + 1;\n const powerOfTwo = [1];\n let last;\n while ((last = 2 * powerOfTwo[powerOfTwo.length - 1]) < LIMIT)\n powerOfTwo.push(last);\n\n const n = is.nextInt();\n const sequence = is.nextArray();\n const tmpMap = {};\n let maxElement = 0;\n for (let i = 0; i < n; i++) { // conver numbers\n sequence[i] = parseInt(sequence[i], 10);\n maxElement = Math.max(maxElement, sequence[i]);\n if (!tmpMap.hasOwnProperty(sequence[i]))\n tmpMap[sequence[i]] = [];\n tmpMap[sequence[i]].push(i);\n }\n\n let answer = 0, canIUse;\n sequence.forEach((i) => {\n canIUse = false;\n for (let j = lowerBound(powerOfTwo, i + 1); powerOfTwo[j] <= i + maxElement; j += 1)\n if (tmpMap.hasOwnProperty(powerOfTwo[j] - i)) {\n canIUse = true;\n if (i === (powerOfTwo[j] - i) && tmpMap[i].length === 1)\n canIUse = false;\n }\n\n if (!canIUse)\n answer++;\n // console.log(i, canIUse);\n });\n\n console.log(answer);\n}\n\n\nfunction lowerBound(array, value) {\n let left = 0, middle;\n let right = array.length;\n while (left < right) {\n middle = parseInt((left + right) / 2);\n if (value <= array[middle])\n right = middle;\n else\n left = middle + 1;\n }\n\n return left; // not found\n}\n\n\n/*\n * api stdin\n */\n\nclass Scanner {\n constructor() {\n this.index = 0;\n this.lines = stdinInput.trim().split('\\n');\n }\n\n nextLine() {\n return this.lines[this.index++];\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray() {\n return this.nextLine().split(' ');\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', input => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}, {"source_code": "\nfunction main() {\n const is = new Scanner();\n const LIMIT = parseInt(1e9, 10) + 1;\n const powerOfTwo = [1];\n let last;\n while ((last = 2 * powerOfTwo[powerOfTwo.length - 1]) < LIMIT)\n powerOfTwo.push(last);\n\n const n = is.nextInt();\n const sequence = is.nextArray();\n const tmpMap = {};\n let maxElement = 0;\n for (let i = 0; i < n; i++) { // conver numbers\n sequence[i] = parseInt(sequence[i], 10);\n maxElement = Math.max(maxElement, sequence[i]);\n if (!tmpMap.hasOwnProperty(sequence[i]))\n tmpMap[sequence[i]] = [];\n tmpMap[sequence[i]].push(i);\n }\n\n let answer = 0, canIUse;\n sequence.forEach((i) => {\n canIUse = false;\n for (let j = lowerBound(powerOfTwo, i + 1); powerOfTwo[j] <= i + maxElement; j += 1)\n if (tmpMap.hasOwnProperty(powerOfTwo[j] - i)) {\n canIUse = true;\n if (i === (powerOfTwo[j] - i) && tmpMap[i].length === 1)\n canIUse = false;\n }\n\n if (!canIUse)\n answer++;\n console.log(i, canIUse);\n });\n\n console.log(answer);\n}\n\n\nfunction lowerBound(array, value) {\n let left = 0, middle;\n let right = array.length;\n while (left < right) {\n middle = parseInt((left + right) / 2);\n if (value <= array[middle])\n right = middle;\n else\n left = middle + 1;\n }\n\n return left; // not found\n}\n\n\n/*\n * api stdin\n */\n\nclass Scanner {\n constructor() {\n this.index = 0;\n this.lines = stdinInput.trim().split('\\n');\n }\n\n nextLine() {\n return this.lines[this.index++];\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray() {\n return this.nextLine().split(' ');\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', input => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}], "src_uid": "ed308777f7122ca6279b522acd3e58f9"} {"nl": {"description": "On a chessboard with a width of $$$10^9$$$ and a height of $$$10^9$$$, the rows are numbered from bottom to top from $$$1$$$ to $$$10^9$$$, and the columns are numbered from left to right from $$$1$$$ to $$$10^9$$$. Therefore, for each cell of the chessboard you can assign the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number and $$$y$$$ is the row number.Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $$$(1,1)$$$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number $$$10^9$$$).Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number $$$x$$$. Such spells create an infinite blocking line between the columns $$$x$$$ and $$$x+1$$$. Horizontal. Each of these is defined by three numbers $$$x_1$$$, $$$x_2$$$, $$$y$$$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $$$y$$$ and in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells. An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $$$(r_0,c_0)$$$ into the cell $$$(r_1,c_1)$$$ only under the condition that $$$r_1 = r_0$$$ or $$$c_1 = c_0$$$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \\le n,m \\le 10^5$$$) — the number of vertical and horizontal spells. Each of the following $$$n$$$ lines contains one integer $$$x$$$ ($$$1 \\le x < 10^9$$$) — the description of the vertical spell. It will create a blocking line between the columns of $$$x$$$ and $$$x+1$$$. Each of the following $$$m$$$ lines contains three integers $$$x_1$$$, $$$x_2$$$ and $$$y$$$ ($$$1 \\le x_{1} \\le x_{2} \\le 10^9$$$, $$$1 \\le y < 10^9$$$) — the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number $$$y$$$, in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.", "output_spec": "In a single line print one integer — the minimum number of spells the rook needs to remove so it can get from the cell $$$(1,1)$$$ to at least one cell in the row with the number $$$10^9$$$", "sample_inputs": ["2 3\n6\n8\n1 5 6\n1 9 4\n2 4 2", "1 3\n4\n1 5 3\n1 9 4\n4 6 6", "0 2\n1 1000000000 4\n1 1000000000 2", "0 0", "2 3\n4\n6\n1 4 3\n1 5 2\n1 6 5"], "sample_outputs": ["1", "1", "2", "0", "2"], "notes": "NoteIn the first sample, in order for the rook return home, it is enough to remove the second horizontal spell. Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home. In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell. Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home. In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them. Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home. In the fourth sample, we have no spells, which means that we do not need to remove anything.In the fifth example, we can remove the first vertical and third horizontal spells. Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. "}, "positive_code": [{"source_code": "var n = Math.pow(10, 9);\n\nvar fl = readline().split(' ').map(v=>+v);\nvar v = fl[0]; var h = fl[1];\n\nvar vert = [];\nfor(var i = 0; i < v; i++) {\n vert.push(+readline());\n}\nvert.push(n);\nvert.sort((a, b) => a - b);\n\nvar hor = [];\nfor(var i = 0; i < h; i++) {\n var line = readline();\n if(line[0] !== '1' || line[1] !== ' ') continue;\n\n line = line.substr(2).split(' ');\n\n hor.push({x: +line[0], y: +line[1]});\n}\n\nhor.sort((a, b) => a.x - b.x);\n\nvar min, pos = 0;\nfor(i = 0; i < vert.length; i++) {\n\n if(min !== undefined && i >= min) break;\n while (pos < hor.length && hor[pos].x < vert[i]) {\n pos += 1;\n }\n\n var hLines = i + hor.length - pos;\n if(!min || hLines < min) min = hLines;\n}\n\nprint(min || 0);"}], "negative_code": [], "src_uid": "00eb4442eb86ccc7352b63dc23354abf"} {"nl": {"description": "Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?", "input_spec": "The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.", "output_spec": "Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.", "sample_inputs": ["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"], "sample_outputs": ["3", "-1", "2999999997"], "notes": "NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time."}, "positive_code": [{"source_code": " var tmp = readline().split(' ').map(x => parseInt(x));\n var n = tmp[0];\n var k = tmp[1];\n var a = readline().split(' ').map(x => parseInt(x));\n var min = a.reduce((a, b) => Math.min(a, b));\n var res = 0;\n var flag = true;\n a.forEach((x) => {\n if((x - min) % k === 0) {\n res += (x - min) / k;\n } else {\n flag = false;\n }\n });\n if(flag) {\n print(res);\n } else {\n print(-1);\n }"}], "negative_code": [], "src_uid": "9e71b4117a24b906dbc16e6a6d110f50"} {"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 000 containing only lowercase English letters \"a\" and \"b\". ", "output_spec": "Print a single integer — 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": "s=' '+readline()\n\nas=[0]\nbs=[0]\n\nfor (i=1;ires)\n res=x\n }\n}\nprint(res)"}], "negative_code": [{"source_code": "s=readline()\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\nz=s;\ns=s.split(' ').map(function(x){return x.length})\nres=0\nif(z[0]=='b')\n{\n s.shift()\n}\nif (1)\n{\n n=s.length\n s.push(0)\n s.push(0)\n s.push(0)\n for (i=0;ires)\n {\n res=s[i]+s[i+1]+s[i+2]\n }\n }\n}\nprint(res)"}, {"source_code": "s=readline()\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\nz=s;\ns=s.split(' ').map(function(x){return x.length})\nres=0\nif(z[0]=='b')\n{\n s.unshift(0)\n}\nif (1)\n{\n n=s.length\n s.push(0)\n s.push(0)\n s.push(0)\n for (i=0;ires)\n {\n res=s[i]+s[i+1]+s[i+2]\n }\n }\n}\nprint(res)"}, {"source_code": "s=readline()\nfor (i=0;i<=0;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=0;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\ns=s.split(\" \")\nif (s[0][0]=='b')\n{\n s.unshift(\"\");\n}\nres=0\nif (1)\n{\n n=s.length\n s.push(\"\")\n s.push(\"\")\n s.push(\"\")\n for (i=0;ires)\n {\n res=s[i].length+s[i+1].length+s[i+2].length\n }\n }\n}\nprint(res)"}, {"source_code": "s=readline()\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\nz=s;\ns=s.split(' ').map(function(x){return x.length})\nres=0\nif(z[0]=='b')\n{\n s.shift()\n}\nif (s.length==1)\n{\n res=s[0]\n}\nif (s.length==2)\n{\n res=s[0]+s[1]\n}\nif (s.length>2)\n{\n var b=0\n n=s.length\n s.push(0)\n s.push(0)\n s.push(0)\n for (i=0;ires)\n {\n res=s[i]+s[i+1]+s[i+2]\n }\n }\n}\nprint(res)"}, {"source_code": "s=readline()\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\nz=s;\ns=s.split(' ').map(function(x){return x.length})\nres=0\nif (s.length==1)\n{\n res=s[0]\n}\nif (s.length==2)\n{\n res=s[0]+s[1]\n}\nif (s.length>2)\n{\n var b=0\n if (z[0]=='b')\n {\n s.unshift(0)\n }\n s.push(0)\n s.push(0)\n s.push(0)\n for (i=b;i=s.length)\n {\n break;\n }\n if (s[i]+s[i+1]+s[i+2]>res)\n {\n res=s[i]+s[i+1]+s[i+2]\n }\n }\n}\nprint(res)"}, {"source_code": "s=readline()\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\nz=s;\ns=s.split(' ').map(function(x){return x.length})\nres=0\nif(z[0]=='b')\n{\n s.shift()\n}\nif (s.length==1)\n{\n res=s[0]\n}\nif (s.length==2)\n{\n res=s[0]+s[1]\n}\nif (s.length>2)\n{\n var b=0\n if (z[0]=='b')\n {\n b=1\n }\n s.push(0)\n for (i=b;i=s.length)\n {\n break;\n }\n if (s[i]+s[i+1]+s[i+2]>res)\n {\n res=s[i]+s[i+1]+s[i+2]\n }\n }\n}\nprint(res)"}, {"source_code": "s=readline()\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\nz=s;\ns=s.split(' ').map(function(x){return x.length})\nres=0\nif (s.length==1)\n{\n res=s[0]\n}\nif (s.length==2)\n{\n res=s[0]+s[1]\n}\nif (s.length>2)\n{\n var b=0\n if (z[0]=='b')\n {\n s.unshift(0)\n }\n s.push(0)\n s.push(0)\n s.push(0)\n for (i=b;i=s.length)\n {\n break;\n }\n if (s[i]+s[i+1]+s[i+2]>res)\n {\n res=s[i]+s[i+1]+s[i+2]\n }\n }\n}\nprint(res)"}, {"source_code": "s=readline()\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ba/gi,\"b a\")\n}\n\nfor (i=0;i<=1;i++)\n{\n s=s.replace(/ab/gi,\"a b\")\n}\nz=s;\ns=s.split(' ').map(function(x){return x.length})\nres=0\nif (s.length==1)\n{\n res=s[0]\n}\nif (s.length==2)\n{\n res=s[0]+s[1]\n}\nif (s.length>2)\n{\n var b=0\n if (z[0]=='b')\n {\n b=1\n }\n s.push(0)\n for (i=b;i=s.length)\n {\n break;\n }\n if (s[i]+s[i+1]+s[i+2]>res)\n {\n res=s[i]+s[i+1]+s[i+2]\n }\n }\n}\nprint(res)"}], "src_uid": "c768f3e52e562ae1fd47502a60dbadfe"} {"nl": {"description": "You invited $$$n$$$ guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the $$$i$$$-th guest wants to have a least $$$l_i$$$ free chairs to the left of his chair, and at least $$$r_i$$$ free chairs to the right. The \"left\" and \"right\" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the $$$l_i$$$ chairs to his left and $$$r_i$$$ chairs to his right may overlap.What is smallest total number of chairs you have to use?", "input_spec": "First line contains one integer $$$n$$$  — number of guests, ($$$1 \\leqslant n \\leqslant 10^5$$$). Next $$$n$$$ lines contain $$$n$$$ pairs of space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \\leqslant l_i, r_i \\leqslant 10^9$$$).", "output_spec": "Output a single integer — the smallest number of chairs you have to use.", "sample_inputs": ["3\n1 1\n1 1\n1 1", "4\n1 2\n2 1\n3 5\n5 3", "1\n5 6"], "sample_outputs": ["6", "15", "7"], "notes": "NoteIn the second sample the only optimal answer is to use two circles: a circle with $$$5$$$ chairs accomodating guests $$$1$$$ and $$$2$$$, and another one with $$$10$$$ chairs accomodationg guests $$$3$$$ and $$$4$$$.In the third sample, you have only one circle with one person. The guest should have at least five free chairs to his left, and at least six free chairs to his right to the next person, which is in this case the guest herself. So, overall number of chairs should be at least 6+1=7."}, "positive_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nlet input = \"\";\nprocess.stdin.on(\"data\", data => input += data);\nprocess.stdin.on(\"end\", () => {\n\tconst nonDecrease = (a, b) => a - b;\n\tconst [n, ...rest] = input.trim().split(\"\\n\");\n\tconst [left, right] = [rest\n\t\t.map(line => line.split(\" \").map(Number))]\n\t\t.map(x => [\n\t\t\tx.map(x => x[0]).sort(nonDecrease),\n\t\t\tx.map(x => x[1]).sort(nonDecrease)\n\t\t])[0];\n\tconsole.log(left.map((v, i) => Math.max(v, right[i])).reduce((a, b) => a + b) + Number(n));\n});"}, {"source_code": "n = +readline();\nleft = []\nright = [];\nfor (i = 0;ia-b);\nright = right.sort((a,b)=>a-b);\nans = 0;\nfor (i = 0;iparseInt(x));\r\n n = nd[0];\r\n a = [];\r\n a.push([nd[1], 1, 2]);\r\n a.push([nd[2], 2, 3]);\r\n a.push([nd[3], 1, 3]);\r\n a.sort((b, c) => c[0] - b[0]);\r\n \r\n var x, y ,z;\r\n x = a[0][0];\r\n y = a[1][0];\r\n z = a[2][0];\r\n var br = (y+z) - x;\r\n if (br & 1 || br < 0) {\r\n print('NO');\r\n continue;\r\n }\r\n br = br / 2;\r\n if (n < a[0][0] + 1 + br) {\r\n print('NO');\r\n continue;\r\n }\r\n print('YES');\r\n if (a[1][1] == a[0][2] || a[1][2] == a[0][2]) {\r\n var temp = a[0][1];\r\n a[0][1] = a[0][2];\r\n a[0][2] = temp;\r\n }\r\n var nodes = [1, 2, 3];\r\n var brNode = nodes.filter(x => x != a[0][1] && x != a[0][2])[0];\r\n\r\n var brStart = brNode;\r\n var reserve = 4;\r\n for (var i = 0; i < br; i++) {\r\n logNodes(reserve, brStart);\r\n brStart = reserve;\r\n reserve++;\r\n }\r\n var lineNode = a[0][1];\r\n for (var i = 0; i < (y - br - 1); i++) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n logNodes(lineNode, brStart);\r\n lineNode = brStart;\r\n for (var i = 0; i < (z - br - 1); i++) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n logNodes(lineNode, a[0][2]);\r\n lineNode = a[0][2];\r\n while( reserve <= n ) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n }"}, {"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const arr = lines[l++].trim().split(' ').map(Number)\r\n output[i] = solve(arr)\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(arr) {\r\n const n = arr.shift()\r\n const pair = ['12', '23', '31']\r\n const sorted = arr.map((x, i) => [x, pair[i]])\r\n .sort((a, b) => a[0] - b[0])\r\n const [a, b, c] = sorted.map(x => x[0])\r\n const [sa, sb, sc] = sorted.map(x => x[1])\r\n const va = getv(sa, sb)\r\n const vb = getv(sa, sc)\r\n const vc = getv(sb, sc)\r\n// console.log(sa, sb, sc)\r\n// return\r\n if (c > a + b || (a + b - c) & 1) return 'NO'\r\n const share = (a + b - c) / 2\r\n// console.log('share', share)\r\n const edges = []\r\n let now = 3\r\n let lca = fill(va, share)\r\n if (share === a) {\r\n fixLast(va)\r\n lca = va\r\n }\r\n fill(lca, a - share)\r\n fixLast(vb)\r\n fill(lca, b - share)\r\n fixLast(vc)\r\n if (now <= n) {\r\n fill(va, n - now)\r\n } else {\r\n return 'NO'\r\n }\r\n function fill(u, d) {\r\n while (d--) {\r\n const v = ++now\r\n edges.push([u, v])\r\n u = v\r\n }\r\n return u\r\n }\r\n function fixLast(u) {\r\n edges[edges.length - 1][1] = u\r\n now--\r\n }\r\n return 'YES\\n' + edges.map(x => x.join(' ')).join('\\n')\r\n}\r\nfunction getv(sa, sb) {\r\n for (let x of [1,2,3]) {\r\n if (sa.indexOf(x) >= 0 && sb.indexOf(x) >= 0) return x\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "var n;\r\n var a;\r\n \r\n function logNodes(x, y) {\r\n print(x + ' ' + y);\r\n }\r\n\r\n var tests = parseInt(readline());\r\n for (var t=0; tparseInt(x));\r\n n = nd[0];\r\n a = [];\r\n a.push([nd[1], 1, 2]);\r\n a.push([nd[2], 2, 3]);\r\n a.push([nd[3], 1, 3]);\r\n a.sort((b, c) => c[0] - b[0]);\r\n \r\n var x, y ,z;\r\n x = a[0][0];\r\n y = a[1][0];\r\n z = a[2][0];\r\n var br = (y+z) - x;\r\n if (br & 1 || br < 0) {\r\n print('NO');\r\n continue;\r\n }\r\n br = br / 2;\r\n if (n < a[0][0] + 1 + br) {\r\n print('NO');\r\n continue;\r\n }\r\n print('YES');\r\n if (a[1][1] == a[0][2] || a[1][2] == a[0][2]) {\r\n var temp = a[0][1];\r\n a[0][1] = a[0][2];\r\n a[0][2] = temp;\r\n }\r\n var nodes = [1, 2, 3];\r\n var brNode = nodes.filter(x => x != a[0][1] && x != a[0][2])[0];\r\n\r\n var brStart = brNode;\r\n var reserve = 4;\r\n for (var i = 0; i < br; i++) {\r\n logNodes(reserve, brNode);\r\n brStart = reserve;\r\n reserve++;\r\n }\r\n var lineNode = a[0][1];\r\n for (var i = 0; i < (y - br - 1); i++) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n logNodes(lineNode, brStart);\r\n lineNode = brStart;\r\n for (var i = 0; i < (z - br - 1); i++) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n logNodes(lineNode, a[0][2]);\r\n lineNode = a[0][2];\r\n while( reserve <= n ) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n }"}, {"source_code": "var n;\r\n var a;\r\n \r\n function logNodes(x, y) {\r\n print(x + ' ' + y);\r\n }\r\n\r\n var tests = parseInt(readline());\r\n for (var t=0; tparseInt(x));\r\n n = nd[0];\r\n a = [];\r\n a.push([nd[1], 1, 2]);\r\n a.push([nd[2], 2, 3]);\r\n a.push([nd[3], 1, 3]);\r\n a.sort((b, c) => c[0] - b[0]);\r\n \r\n var x, y ,z;\r\n x = a[0][0];\r\n y = a[1][0];\r\n z = a[2][0];\r\n var br = (y+z) - x;\r\n if (br & 1 || br < 0) {\r\n print('NO');\r\n continue;\r\n }\r\n br = br / 2;\r\n if (n - 2 < (a - 1) + br) {\r\n print('NO');\r\n continue;\r\n }\r\n print('YES');\r\n if (a[1][1] == a[0][2] || a[1][2] == a[0][2]) {\r\n var temp = a[0][1];\r\n a[0][1] = a[0][2];\r\n a[0][2] = temp;\r\n }\r\n var nodes = [1, 2, 3];\r\n var brNode = nodes.filter(x => x != a[0][1] && x != a[0][2])[0];\r\n\r\n var brStart = brNode;\r\n var reserve = 4;\r\n for (var i = 0; i < br; i++) {\r\n logNodes(reserve, brNode);\r\n brStart = reserve;\r\n reserve++;\r\n }\r\n var lineNode = a[0][1];\r\n for (var i = 0; i < (y - br - 1); i++) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n logNodes(lineNode, brStart);\r\n lineNode = brStart;\r\n for (var i = 0; i < (z - br - 1); i++) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n logNodes(lineNode, a[0][2]);\r\n lineNode = a[0][2];\r\n while( reserve <= n ) {\r\n logNodes(lineNode, reserve);\r\n lineNode = reserve;\r\n reserve++;\r\n }\r\n }"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(arr) {\n const n = arr.shift()\n const pair = ['12', '23', '31']\n const sorted = arr.map((x, i) => [x, pair[i]])\n .sort((a, b) => a[0] - b[0])\n const [a, b, c] = sorted.map(x => x[0])\n const [sa, sb, sc] = sorted.map(x => x[1])\n const va = getv(sa, sb)\n const vb = getv(sa, sc)\n const vc = getv(sb, sc)\n// console.log(sa, sb, sc)\n// return\n if (c > a + b || (a + b - c) & 1) return 'NO'\n const share = (a + b - c) / 2\n// console.log('share', share)\n const edges = []\n let now = 3\n let lca = fill(va, share)\n if (share === a) {\n fixLast(va)\n lca = va\n }\n fill(lca, a - share)\n fixLast(vb)\n fill(lca, b - share)\n fixLast(vc)\n if (now < n) {\n fill(va, n - now)\n }\n function fill(u, d) {\n while (d--) {\n const v = ++now\n edges.push([u, v])\n u = v\n }\n return u\n }\n function fixLast(u) {\n edges[edges.length - 1][1] = u\n now--\n }\n return 'YES\\n' + edges.map(x => x.join(' ')).join('\\n')\n}\nfunction getv(sa, sb) {\n for (let x of [1,2,3]) {\n if (sa.indexOf(x) >= 0 && sb.indexOf(x) >= 0) return x\n }\n}\n"}], "src_uid": "4750029f0a5e802099a6dd4dff2974d5"} {"nl": {"description": "«Polygon» 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 ≤ n ≤ 3000) — the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 3000) — 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": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar N = -1;\n\nrl.on('line', function (input) {\n\n\n if (N == -1) {\n N = parseInt(input);\n }\n else {\n var tests = [];\n tests = input.split(' ').map(item => { return parseInt(item); });\n tests.sort(sortNumber);\n /*console.log(\"*************\");\n tests.forEach(element => {\n rl.write(element + \", \");\n });\n console.log(\"************\");\n */\n var i = 0;\n for (i = 0; i < N; i++)\n if (i + 1 != tests[i]) break;\n\n\n\n console.log(i + 1);\n rl.close();\n }\n}\n)\n\nfunction sortNumber(a, b) {\n return a - b;\n }\n\n"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar N = -1;\n\nrl.on('line', function (input) {\n\n\n if (N == -1) {\n N = parseInt(input);\n }\n else {\n var tests = [];\n tests = input.split(' ').map(item => { return parseInt(item); });\n //tests.sort(sortNumber);\n tests.sort((a,b)=>{return a-b;});\n /*console.log(\"*************\");\n tests.forEach(element => {\n rl.write(element + \", \");\n });\n console.log(\"************\");\n */\n var i = 0;\n for (i = 0; i < N; i++)\n if (i + 1 != tests[i]) break;\n\n\n\n console.log(i + 1);\n rl.close();\n }\n}\n)\n/*\nfunction sortNumber(a, b) {\n return a - b;\n }*/\n\n"}, {"source_code": "function checkValue(value) {\n return value != 1;\n}\nfunction getNextIdx (n, restArgs) {\n var arr = [];\n arr[3000] = 0;\n var i;\n for (i=0;i parseInt(v)).sort((a, b) => a - b)\nif (lll[0] != 1) {\n print(1)\n} else {\n for (var i = 1; i < lll.length; i++) {\n if (lll[i] - lll[i - 1] != 1) break\n }\n print(i + 1)\n}"}], "negative_code": [{"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar N = -1;\n\nrl.on('line', function (input) {\n\n\n if (N == -1) {\n N = parseInt(input);\n }\n else {\n var tests = [];\n tests = input.split(' ').map(item => { return parseInt(item); });\n tests.sort();\n var i = 0;\n for (i = 0; i < N; i++)\n if (i + 1 != tests[i]) break;\n\n\n\n console.log(i + 1);\n rl.close();\n }\n}\n)\n\n\n\n"}, {"source_code": "function checkValue(value) {\n return value != 1;\n}\nfunction getNextIdx (n, restArgs) {\n var arr = [];\n var i;\n for (i=0;i parseInt(v)).sort((a, b) => a - b)\nfor (var i = 1; i < lll.length; i++) {\n if (lll[i] - lll[i - 1] != 1) break\n}\nprint(i + 1)\n"}], "src_uid": "5e449867d9fcecc84333b81eac9b5d92"} {"nl": {"description": "You have a board represented as a grid with $$$2 \\times n$$$ cells.The first $$$k_1$$$ cells on the first row and first $$$k_2$$$ cells on the second row are colored in white. All other cells are colored in black.You have $$$w$$$ white dominoes ($$$2 \\times 1$$$ tiles, both cells are colored in white) and $$$b$$$ black dominoes ($$$2 \\times 1$$$ tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all $$$w + b$$$ dominoes on the board if you can place dominoes both horizontally and vertically?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 3000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$ and $$$k_2$$$ ($$$1 \\le n \\le 1000$$$; $$$0 \\le k_1, k_2 \\le n$$$). The second line of each test case contains two integers $$$w$$$ and $$$b$$$ ($$$0 \\le w, b \\le n$$$).", "output_spec": "For each test case, print YES if it's possible to place all $$$w + b$$$ dominoes on the board and 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\n1 0 1\n1 0\n1 1 1\n0 0\n3 0 0\n1 3\n4 3 1\n2 2\n5 4 3\n3 1"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES"], "notes": "NoteIn the first test case, $$$n = 1$$$, $$$k_1 = 0$$$ and $$$k_2 = 1$$$. It means that $$$2 \\times 1$$$ board has black cell $$$(1, 1)$$$ and white cell $$$(2, 1)$$$. So, you can't place any white domino, since there is only one white cell.In the second test case, the board of the same size $$$2 \\times 1$$$, but both cell are white. Since $$$w = 0$$$ and $$$b = 0$$$, so you can place $$$0 + 0 = 0$$$ dominoes on the board.In the third test case, board $$$2 \\times 3$$$, but fully colored in black (since $$$k_1 = k_2 = 0$$$), so you can't place any white domino.In the fourth test case, cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, and $$$(2, 1)$$$ are white and other cells are black. You can place $$$2$$$ white dominoes at positions $$$((1, 1), (2, 1))$$$ and $$$((1, 2), (1, 3))$$$ and $$$2$$$ black dominoes at positions $$$((1, 4), (2, 4))$$$ $$$((2, 2), (2, 3))$$$."}, "positive_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf8\");\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\nfunction readLine() {\r\n return standardInputString[currentLine++];\r\n}\r\nprocess.stdin.on(\"data\", (rawData) => {\r\n standardInputString += rawData;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n standardInputString = standardInputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((line) => {\r\n return line.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction main() {\r\n const numArray = (a) => a.split(\" \").map((line) => +line),\r\n cl = console.log,\r\n rl = readLine,\r\n tc = rl();\r\n\r\n for (let i = 0; i < tc; i++) {\r\n const [n, k1, k2] = numArray(rl());\r\n const [w, b] = numArray(rl());\r\n solution(n, k1, k2, w, b);\r\n }\r\n /************************Solution****************************************/\r\n function solution(n, k1, k2, w, b) {\r\n // cl(n, k1, k2, w, b);\r\n const whiteArea = k1 + k2;\r\n const blackArea = 2 * n - whiteArea;\r\n\r\n // console.log(\"solution\", w, whiteArea, b, blackArea);\r\n if (w * 2 <= whiteArea && b * 2 <= blackArea) {\r\n cl(\"yes\");\r\n } else {\r\n cl(\"no\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst abs = Math.abs;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n, k1, k2, w, b) => {\r\n let cntw = mi(k1, k2) + (abs(k1 - k2) >> 1);\r\n let cntb = mi(n - k1, n - k2) + (abs((n - k1) - (n - k2)) >> 1);\r\n if (w <= cntw && b <= cntb) return pr('YES');\r\n pr('NO');\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i][0], input[i][1], input[i][2], input[i + 1][0], input[i + 1][1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "var a = function(a, b, c){\n if(a < b){\n var temp = a;\n a = b;\n b = temp;\n }\n a -= b;\n var a2 = a / 2;\n var b2 = c - b;\n if(a2 >= b2){\n return true;\n }else{\n return false;\n }\n};\nlet i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0];\n var e = 0;\n for(var j = 1; j <= n * 2; j++){\n if(j % 2 == 1){\n e = lines[j].split(' ').map(Number);\n }else{\n var k = lines[j].split(' ').map(Number);\n var N = e[0];\n var k1 = e[1];\n var k2 = e[2];\n var w = k[0];\n var b = k[1];\n b1 = N - k1;\n b2 = N - k2;\n if(a(k1, k2, w) === true && a(b1, b2, b) === true){\n console.log('YES');\n }else{\n console.log('NO');\n }\n }\n }\n});"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar w1 = nextInt();\r\n\t\tvar w2 = nextInt();\r\n\t\tvar b1 = N - w1;\r\n\t\tvar b2 = N - w2;\r\n\t\tvar w = nextInt();\r\n\t\tvar b = nextInt();\r\n\t\tif(w1 % 2 != w2 % 2){\r\n\t\t\tif(w1 > w2){\r\n\t\t\t\tw1--;\r\n\t\t\t}else{\r\n\t\t\t\tw2--;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(b1 % 2 != b2 % 2){\r\n\t\t\tif(b1 > b2){\r\n\t\t\t\tb1--;\r\n\t\t\t}else{\r\n\t\t\t\tb2--;\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar L = w1 + w2;\r\n\t\tvar R = b1 + b2;\r\n\t\tif(L < w * 2 || R < b * 2){\r\n\t\t\tmyout(\"NO\");\r\n\t\t}else{\r\n\t\t\tmyout(\"YES\");\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve([n, k1, k2], [w, b]) {\r\n const wArea = k1 + k2, bArea = (2 * n) - (k1 + k2)\r\n let res = false\r\n if (k1 % 2 === k2 % 2) {\r\n if (wArea >= w * 2 && bArea >= b * 2) res = true\r\n } else {\r\n if (wArea - 1 >= w * 2 && bArea - 1 >= b * 2) res = true\r\n }\r\n res ? console.log('YES') : console.log('NO')\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\nvar mod = 1000000000n + 7n\r\nvar maxN = 10e6 + 1\r\n\r\nfunction main() {\r\n var x = parseInt(readline())\r\n\r\n Array(parseInt(x)).fill(1).map((t, iii) => {\r\n // var n = parseInt(readline())\r\n var [n, k1, k2] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n var [w, b] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n\r\n // if ((k1 + k2) % 2 !== 0) return console.log('NO')\r\n// console.log(w * 2 <= (k1 + k2), b * 2 <= (n - k1 + n - k2))\r\n if ((w * 2 <= (k1 + k2) )&& (b * 2 <= (n - k1 + n - k2))) return console.log('YES')\r\n console.log('NO')\r\n // var a = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // });\r\n\r\n });\r\n}\r\n"}, {"source_code": "function getInt(num){\r\n return parseInt(num, 10)\r\n}\r\n\r\nvar t = parseInt(readline(), 10);\r\n\r\nfor(var i = 0; i n){\r\n return 'NO';\r\n }\r\n if(k1 < k2){\r\n var temp;\r\n temp = k1;\r\n k1=k2;\r\n k2 =temp;\r\n }\r\n var ws = k2;\r\n var bs = n-k1;\r\n\r\n if(ws >= w && bs>=b){\r\n return 'YES';\r\n }\r\n b = Math.max(b - bs, 0);\r\n w = Math.max(w - ws, 0);\r\n\r\n n = n - bs - ws;\r\n var rest = Math.floor(n/2);\r\n if(b <= rest && w<=rest){\r\n return 'YES'\r\n }\r\n return 'NO';\r\n \r\n}"}], "negative_code": [{"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf8\");\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\nfunction readLine() {\r\n return standardInputString[currentLine++];\r\n}\r\nprocess.stdin.on(\"data\", (rawData) => {\r\n standardInputString += rawData;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n standardInputString = standardInputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((line) => {\r\n return line.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction main() {\r\n const numArray = (a) => a.split(\"\").map((line) => +line),\r\n cl = console.log,\r\n rl = readLine,\r\n tc = rl();\r\n\r\n for (let i = 0; i < tc; i++) {\r\n const [n, k1, k2] = numArray(rl());\r\n const [w, b] = numArray(rl());\r\n solution(n, k1, k2, w, b);\r\n }\r\n /************************Solution****************************************/\r\n function solution(n, k1, k2, w, b) {\r\n const whiteArea = k1 + k2;\r\n const blackArea = 2 * n - whiteArea;\r\n\r\n // console.log(\"solution\", w, whiteArea, b, blackArea);\r\n if (w <= whiteArea && b <= blackArea) {\r\n cl(\"yes\");\r\n } else {\r\n cl(\"no\");\r\n }\r\n }\r\n}\r\n"}, {"source_code": "///////////////////////////////// pre-define /////////////////////////////////////\r\nconst pr = console.log;\r\n///////////////////////////////////////////////////////////////////////////////////\r\n\r\nconst solve = (n, k1, k2, w, b) => {\r\n // pr(n, k1, k2, w, b)\r\n let a = [];\r\n for (let i = 0; i < 2; i++) {\r\n let tmp = [];\r\n for (let j = 0; j < n; j++) {\r\n if (i == 0) {\r\n j < k1 ? tmp.push('w') : tmp.push('b');\r\n } else {\r\n j < k2 ? tmp.push('w') : tmp.push('b');\r\n }\r\n }\r\n a.push(tmp);\r\n }\r\n // pr(a);\r\n let cntw = cntb = 0\r\n for (let i = 0; i < 2; i++) {\r\n for (let j = 0; j < n; j++) {\r\n if (a[i][j] == 'w') {\r\n if (i - 1 >= 0) {\r\n if (a[i - 1][j] == 'w') {\r\n cntw++;\r\n continue;\r\n }\r\n }\r\n if (i + 1 < 2) {\r\n if (a[i + 1][j] == 'w') {\r\n cntw++;\r\n continue;\r\n }\r\n }\r\n if (j - 1 >= 0) {\r\n if (a[i][j - 1] == 'w') {\r\n cntw++;\r\n continue;\r\n }\r\n }\r\n if (j + 1 < n) {\r\n if (a[i][j + 1] == 'w') {\r\n cntw++;\r\n continue;\r\n }\r\n }\r\n } else {\r\n if (i - 1 >= 0) {\r\n if (a[i - 1][j] == 'b') {\r\n cntb++;\r\n continue;\r\n }\r\n }\r\n if (i + 1 < 2) {\r\n if (a[i + 1][j] == 'b') {\r\n cntb++;\r\n continue;\r\n }\r\n }\r\n if (j - 1 >= 0) {\r\n if (a[i][j - 1] == 'b') {\r\n cntb++;\r\n continue;\r\n }\r\n }\r\n if (j + 1 < n) {\r\n if (a[i][j + 1] == 'b') {\r\n cntb++;\r\n continue;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n // pr(w, cntw, b, cntb);\r\n if (w <= cntw && b <= cntb) return pr('YES');\r\n pr('NO');\r\n};\r\n\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i][0], input[i][1], input[i][2], input[i + 1][0], input[i + 1][1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}], "src_uid": "26354d2628f26eb2eff9432bd46400d5"} {"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 — $$$(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)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) — 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$$$) — 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": "// Q: https://codeforces.com/contest/1339/problem/B\n\nconst readline = require('readline');\n\nlet input = [];\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n});\n\nrl.on('line', lineInput => {\n\tinput.push(lineInput);\n});\n\nrl.on('close', () => {\n\tconst test = parseInt(input[0]);\n\tlet sum = 0;\n\tfor (let t=0; t < test; t++) {\n\t\tlet ans = true;\n\t\tlet n = parseInt(input[sum+t+1]);\n\t\tlet arr1 = input[t+sum+2].split(' ').map((a) => parseInt(a));\n\t\tlet arr2 = [];\n\t\tif (n == 1) {\n\t\t\tif ((arr1[0] < arr1[1])) {\n\t\t\t\tans = false;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (let i = 1; i < n; i++) {\n\t\t\t\tarr2 = input[t+sum+2+i].split(' ').map((a) => parseInt(a));\n\t\t\t\tif ((arr2[0] < arr1[0]) || (arr2[1] < arr1[1]) || (arr2[0] < arr2[1]) || (arr1[0] < arr1[1]) || (arr2[0] - arr1[0] < arr2[1] - arr1[1])) {\n\t\t\t\t\tans = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (arr1[0] === arr2[0] && arr2[1] > arr1[1]) {\n\t\t\t\t\tans = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tarr1 = [...arr2];\n\t\t\t}\n\t\t}\n\t\t\n\t\tconsole.log(ans ? 'YES' : 'NO');\n\t\tsum += n;\n\t}\n});"}, {"source_code": "let i = '';\nlet lines;\nprocess.stdin.on('data', (c) => (i += c));\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n lines = i.split(EOL); /*your input text, split by lines*/\n main();\n});\n\nfunction solve(n, a) {\n if (a[0][0] < a[0][1]) return 'NO';\n for(let i = 1; i < n; ++i) {\n const x = a[i][0] - a[i - 1][0];\n const y = a[i][1] - a[i - 1][1];\n if (x < 0 || y < 0) return 'NO';\n if (x < y) return 'NO';\n }\n return 'YES';\n}\n\nfunction main() {\n let currentLine = 0;\n const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));\n\n const test = readLine()[0];\n for (let t = 1; t <= test; ++t) {\n const n = readLine()[0];\n let a = [];\n for(let i = 0; i < n; ++i) a.push(readLine());\n console.log(solve(n, a));\n }\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const cases = readline();\n var i, j;\n for (i = 0; i < cases; i++) {\n const n = readline();\n var terminate = false;\n var lastX = 0;\n var lastY = 0;\n for (j = 0; j < n; j++) {\n const line = readline();\n// console.log('x' +line+'\\n');\n var x = parseInt(line.split(\" \")[0]);\n var y = parseInt(line.split(\" \")[1]);\n// console.log(\"* \"+x+\" \"+y+\" \"+((!terminate) && ((y > x) || ((y-lastY) > (x-lastX))))+\"\\n\");\n if((!terminate) && ((x < lastX) || (y < lastY) || (y > x) || ((y-lastY) > (x-lastX)))) {\n process.stdout.write(\"NO\\n\");\n terminate = true;\n }\n\n lastX = x;\n lastY = y;\n }\n\n !terminate && process.stdout.write(\"YES\\n\");\n }\n}"}, {"source_code": "t = +readline();\nout = '';\nwhile (t-->0){\n n = +readline();\n attemps = 0;\n clears = 0;\n possible = true;\n while (n-->0){\n p = readline().split(' ').map(Number);\n if (!possible){\n continue;\n }\n if (p[0] < attemps || p[1] < clears || p[0] - attemps < p[1] - clears){\n possible = false;\n }\n attemps = p[0];\n clears = p[1];\n }\n out += possible?\"YES\\n\":\"NO\\n\";\n}\nprint(out);"}], "negative_code": [{"source_code": "// Q: https://codeforces.com/contest/1339/problem/B\n\nconst readline = require('readline');\n\nlet input = [];\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n});\n\nrl.on('line', lineInput => {\n\tinput.push(lineInput);\n});\n\nrl.on('close', () => {\n\tconst test = parseInt(input[0]);\n\tlet sum = 0;\n\tfor (let t=0; t < test; t++) {\n\t\tlet ans = true;\n\t\tlet n = parseInt(input[sum+t+1]);\n\t\tlet arr1 = input[t+sum+2].split(' ').map((a) => parseInt(a));\n\t\tlet arr2 = [];\n\t\tif (n == 1) {\n\t\t\tif ((arr1[0] < arr1[1])) {\n\t\t\t\tans = false;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (let i = 1; i < n; i++) {\n\t\t\t\tarr2 = input[t+sum+2+i].split(' ').map((a) => parseInt(a));\n\t\t\t\tif ((arr2[0] < arr1[0]) || (arr2[1] < arr1[1]) || (arr2[0] < arr2[1]) || (arr1[0] < arr1[1])) {\n\t\t\t\t\tans = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tarr1 = [...arr2];\n\t\t\t}\n\t\t}\n\t\t\n\t\tconsole.log(ans ? 'YES' : 'NO');\n\t\tsum += n;\n\t}\n});"}, {"source_code": "// Q: https://codeforces.com/contest/1339/problem/B\n\nconst readline = require('readline');\n\nlet input = [];\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n});\n\nrl.on('line', lineInput => {\n\tinput.push(lineInput);\n});\n\nrl.on('close', () => {\n\tconst test = parseInt(input[0]);\n\tlet sum = 0;\n\tfor (let t=0; t < test; t++) {\n\t\tlet ans = true;\n\t\tlet n = parseInt(input[sum+t+1]);\n\t\tlet arr1 = input[t+sum+2].split(' ').map((a) => parseInt(a));\n\t\tlet arr2 = [];\n\t\tif (n == 1) {\n\t\t\tif ((arr1[0] < arr1[1])) {\n\t\t\t\tans = false;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (let i = 1; i < n; i++) {\n\t\t\t\tarr2 = input[t+sum+2+i].split(' ').map((a) => parseInt(a));\n\t\t\t\tif ((arr2[0] < arr1[0]) || (arr2[1] < arr1[1]) || (arr2[0] < arr2[1]) || (arr1[0] < arr1[1]) || (arr1[0] == arr2[0] && arr2[1] > arr1[0])) {\n\t\t\t\t\tans = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tarr1 = [...arr2];\n\t\t\t}\n\t\t}\n\t\t\n\t\tconsole.log(ans ? 'YES' : 'NO');\n\t\tsum += n;\n\t}\n});"}, {"source_code": "// Q: https://codeforces.com/contest/1339/problem/B\n\nconst readline = require('readline');\n\nlet input = [];\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n});\n\nrl.on('line', lineInput => {\n\tinput.push(lineInput);\n});\n\nrl.on('close', () => {\n\tconst test = parseInt(input[0]);\n\tlet sum = 0;\n\tfor (let t=0; t < test; t++) {\n\t\tlet ans = true;\n\t\tlet n = parseInt(input[sum+t+1]);\n\t\tlet arr1 = input[t+sum+2].split(' ').map((a) => parseInt(a));\n\t\tlet arr2 = [];\n\t\tif (n == 1) {\n\t\t\tif ((arr1[0] < arr1[1])) {\n\t\t\t\tans = false;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (let i = 1; i < n; i++) {\n\t\t\t\tarr2 = input[t+sum+2+i].split(' ').map((a) => parseInt(a));\n\t\t\t\tif ((arr2[0] < arr1[0]) || (arr2[1] < arr1[1]) || (arr2[0] < arr2[1]) || (arr1[0] < arr1[1])) {\n\t\t\t\t\tans = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (arr1[0] === arr2[0] && arr2[1] > arr1[1]) {\n\t\t\t\t\tans = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tarr1 = [...arr2];\n\t\t\t}\n\t\t}\n\t\t\n\t\tconsole.log(ans ? 'YES' : 'NO');\n\t\tsum += n;\n\t}\n});"}, {"source_code": "// Q: https://codeforces.com/contest/1339/problem/B\n\nconst readline = require('readline');\n\nlet input = [];\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n});\n\nrl.on('line', lineInput => {\n\tinput.push(lineInput);\n});\n\nrl.on('close', () => {\n\tconst test = parseInt(input[0]);\n\tlet sum = 0;\n\tfor (let t=0; t < test; t++) {\n\t\tlet ans = true;\n\t\tlet n = parseInt(input[sum+t+1]);\n\t\tlet arr1 = input[t+sum+2].split(' ').map((a) => parseInt(a));\n\t\tlet arr2 = [];\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tarr2 = input[t+sum+2+i].split(' ').map((a) => parseInt(a));\n\t\t\tif ((arr2[0] < arr1[0]) || (arr2[1] < arr1[1]) || (arr2[0] < arr2[1]) || (arr1[0] < arr1[1])) {\n\t\t\t\tans = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tarr1 = [...arr2];\n\t\t}\n\t\tconsole.log(ans ? 'YES' : 'NO');\n\t\tsum += n;\n\t}\n});"}, {"source_code": "let i = '';\nlet lines;\nprocess.stdin.on('data', (c) => (i += c));\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n lines = i.split(EOL); /*your input text, split by lines*/\n main();\n});\n\nfunction solve(n, a) {\n for(let i = 1; i < n; ++i) {\n if (a[i][1] < a[i - 1][1]) return 'NO';\n if (a[i][0] < a[i - 1][0]) return 'NO';\n if (a[i][1] > a[i - 1][1] && a[i][0] === a[i - 1][0]) return 'NO';\n }\n return 'YES';\n}\n\nfunction main() {\n let currentLine = 0;\n const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));\n\n const test = readLine()[0];\n for (let t = 1; t <= test; ++t) {\n const n = readLine()[0];\n let a = [];\n for(let i = 0; i < n; ++i) a.push(readLine());\n console.log(solve(n, a));\n }\n}\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n const cases = readline();\n var i, j;\n for (i = 0; i < cases; i++) {\n const n = readline();\n var terminte = false;\n var lastX = 0;\n var lastY = 0;\n loop1: for (j = 0; j < n; j++) {\n const line = readline();\n\n var x = line.split(\" \")[0];\n var y = line.split(\" \")[1];\n\n if(!terminte && (y > x || (y-lastY) > (x-lastX))) {\n process.stdout.write(\"NO\\n\");\n terminte = true;\n }\n\n lastX = x;\n lastY = y;\n }\n\n terminte ? process.stdout.write(\"YES\\n\") : null;\n }\n}"}], "src_uid": "714834defd0390659f6ed5bc3024f613"} {"nl": {"description": "The only difference between the two versions is that in this version $$$n \\leq 2 \\cdot 10^5$$$ and the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.A terminal is a row of $$$n$$$ equal segments numbered $$$1$$$ to $$$n$$$ in order. There are two terminals, one above the other. You are given an array $$$a$$$ of length $$$n$$$. For all $$$i = 1, 2, \\dots, n$$$, there should be a straight wire from some point on segment $$$i$$$ of the top terminal to some point on segment $$$a_i$$$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $$$n=7$$$ and $$$a=[4,1,4,6,7,7,5]$$$. A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.What is the maximum number of crossings there can be if you place the wires optimally?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$) — 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$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single integer — the maximum number of crossings there can be if you place the wires optimally.", "sample_inputs": ["4\n\n7\n\n4 1 4 6 7 7 5\n\n2\n\n2 1\n\n1\n\n1\n\n3\n\n2 2 2"], "sample_outputs": ["6\n1\n0\n3"], "notes": "NoteThe first test case is shown in the second picture in the statement.In the second test case, the only wiring possible has the two wires cross, so the answer is $$$1$$$.In the third test case, the only wiring possible has one wire, so the answer is $$$0$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n};\r\nvar __importDefault = (this && this.__importDefault) || function (mod) {\r\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst readline_1 = __importDefault(require(\"readline\"));\r\n(() => {\r\n let readBase = readline_1.default.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n });\r\n let buffer = [];\r\n let resolveList = [];\r\n readBase.on('line', data => {\r\n buffer.push(data);\r\n if (buffer.length <= resolveList.length) {\r\n resolveList[buffer.length - 1](data);\r\n }\r\n });\r\n let input = () => __awaiter(void 0, void 0, void 0, function* () {\r\n return new Promise(resolve => {\r\n resolveList.push(resolve);\r\n if (resolveList.length <= buffer.length) {\r\n resolve(buffer[resolveList.length - 1]);\r\n }\r\n });\r\n });\r\n main({ input }).then(() => {\r\n process.exit(0);\r\n });\r\n})();\r\nfunction main({ input }) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n let solve = () => __awaiter(this, void 0, void 0, function* () {\r\n let getMid = (l, r) => {\r\n return l + Math.floor((r - l) / 2);\r\n };\r\n let n = parseInt(yield input());\r\n let a = (yield input()).split(' ').map(v => parseInt(v));\r\n let tree = Array(n * 4 + 5).fill(0);\r\n let sonOfNode = (nod) => ({\r\n ls: nod * 2,\r\n rs: nod * 2 + 1,\r\n });\r\n let pushup = (nod) => {\r\n let { ls, rs } = sonOfNode(nod);\r\n tree[nod] = tree[ls] + tree[rs];\r\n };\r\n let build = (nod, l, r) => {\r\n if (l === r) {\r\n tree[nod] = 0;\r\n return;\r\n }\r\n let { ls, rs } = sonOfNode(nod);\r\n let mid = getMid(l, r);\r\n build(ls, l, mid);\r\n build(rs, mid + 1, r);\r\n pushup(nod);\r\n };\r\n let modify = (nod, l, r, pos, x) => {\r\n if (l === r) {\r\n tree[nod] += x;\r\n return;\r\n }\r\n let { ls, rs } = sonOfNode(nod);\r\n let mid = getMid(l, r);\r\n if (pos <= mid) {\r\n modify(ls, l, mid, pos, x);\r\n }\r\n else {\r\n modify(rs, mid + 1, r, pos, x);\r\n }\r\n pushup(nod);\r\n };\r\n let query = (nod, l, r, x, y) => {\r\n if (l === x && r === y) {\r\n return tree[nod];\r\n }\r\n let { ls, rs } = sonOfNode(nod);\r\n let mid = getMid(l, r);\r\n if (y <= mid) {\r\n return query(ls, l, mid, x, y);\r\n }\r\n else if (x > mid) {\r\n return query(rs, mid + 1, r, x, y);\r\n }\r\n else {\r\n let ans = query(ls, l, mid, x, mid);\r\n return ans + query(rs, mid + 1, r, mid + 1, y);\r\n }\r\n };\r\n build(1, 1, n);\r\n let ans = 0;\r\n a.forEach(x => {\r\n ans += query(1, 1, n, x, n);\r\n modify(1, 1, n, x, 1);\r\n });\r\n console.log(ans);\r\n });\r\n let T = parseInt(yield input());\r\n for (let i = 0; i < T; i++) {\r\n yield solve();\r\n }\r\n });\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n};\r\nvar __importDefault = (this && this.__importDefault) || function (mod) {\r\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst readline_1 = __importDefault(require(\"readline\"));\r\n(() => {\r\n let readBase = readline_1.default.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n });\r\n let buffer = [];\r\n let resolveList = [];\r\n readBase.on('line', data => {\r\n buffer.push(data);\r\n if (buffer.length <= resolveList.length) {\r\n resolveList[buffer.length - 1](data);\r\n }\r\n });\r\n let input = () => __awaiter(void 0, void 0, void 0, function* () {\r\n return new Promise(resolve => {\r\n resolveList.push(resolve);\r\n if (resolveList.length <= buffer.length) {\r\n resolve(buffer[resolveList.length - 1]);\r\n }\r\n });\r\n });\r\n main({ input }).then(() => {\r\n process.exit(0);\r\n });\r\n})();\r\nfunction main({ input }) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n let solve = () => __awaiter(this, void 0, void 0, function* () {\r\n let getMid = (l, r) => {\r\n return l + Math.floor((r - l) / 2);\r\n };\r\n class TreeArray {\r\n constructor(n) {\r\n this.n = n;\r\n this.arr = Array(n + 1).fill(0);\r\n }\r\n modify(pos, x) {\r\n for (let i = pos; i <= n; i += i & -i) {\r\n this.arr[i] += x;\r\n }\r\n }\r\n queryR(pos) {\r\n let ans = 0;\r\n for (let i = pos; i > 0; i -= i & -i) {\r\n ans += this.arr[i];\r\n }\r\n return ans;\r\n }\r\n query(posL, posR) {\r\n return this.queryR(posR) - this.queryR(posL - 1);\r\n }\r\n }\r\n let n = parseInt(yield input());\r\n let a = (yield input()).split(' ').map(v => parseInt(v));\r\n let treeArray = new TreeArray(n);\r\n let ans = 0;\r\n a.forEach(x => {\r\n ans += treeArray.query(x, n);\r\n treeArray.modify(x, 1);\r\n });\r\n console.log(ans);\r\n });\r\n let T = parseInt(yield input());\r\n for (let i = 0; i < T; i++) {\r\n yield solve();\r\n }\r\n });\r\n}\r\n"}, {"source_code": "// ../../lib/ts/BIT.ts\nvar BIT = class {\n constructor(n2 = 0, op, init) {\n this.n = n2;\n this.op = op;\n this.init = init;\n this.seg = new Array(n2 + 1).fill(init);\n }\n add(i, v) {\n i++;\n while (i <= this.n) {\n this.seg[i] = this.op(this.seg[i], v);\n i += i & -i;\n }\n }\n sumTo(i) {\n let res = this.init;\n while (i > 0) {\n res = this.op(res, this.seg[i]);\n i -= i & -i;\n }\n return res;\n }\n};\n\n// codeforces/1676H2/src/ts/solution1.ts\nvar lines = [];\nrequire(\"readline\").createInterface({\n input: process.stdin\n}).on(\"line\", (line) => lines.push(line));\nprocess.stdin.on(\"end\", () => {\n main(lines);\n});\nvar n;\nvar a;\nvar main = (lines2) => {\n let _ln = 0;\n const readString = () => lines2[_ln++];\n const readStrings = () => readString().split(\" \");\n const readNumber = () => Number(readString());\n const readNumbers = () => readStrings().map(Number);\n for (let t = readNumber(); t > 0; t--) {\n n = readNumber();\n a = readNumbers();\n output(solve());\n }\n};\nvar solve = () => {\n const bit = new BIT(n, (a2, b) => a2 + b, 0);\n let res = 0;\n for (const ai of a) {\n res += bit.sumTo(n) - bit.sumTo(ai - 1);\n bit.add(ai - 1, 1);\n }\n return res;\n};\nvar output = (res) => {\n console.log(res);\n};\n"}, {"source_code": "// ../../lib/ts/segmentTree.ts\nvar STNode = class {\n};\nvar SegmentTree = class {\n constructor(arr, op, e) {\n this.op = op;\n this.e = e;\n let n2 = 1;\n while (n2 * 2 < arr.length)\n n2 *= 2;\n this.tree = new Array(n2 * 4).fill(void 0).map((_) => new STNode());\n const build = (k, l, r) => {\n this.tree[k].l = l;\n this.tree[k].r = r;\n if (l === r) {\n this.tree[k].v = arr[l - 1];\n return;\n }\n const mid = l + r >> 1;\n const lc = k * 2, rc = lc + 1;\n build(lc, l, mid);\n build(rc, mid + 1, r);\n this.tree[k].v = this.op(this.tree[lc].v, this.tree[rc].v);\n };\n build(1, 1, arr.length);\n }\n update_(k, i, v) {\n if (this.tree[k].l === this.tree[k].r && this.tree[k].l === i) {\n this.tree[k].v = v;\n return;\n }\n const mid = this.tree[k].l + this.tree[k].r >> 1;\n const lc = k * 2, rc = lc + 1;\n if (i <= mid)\n this.update_(lc, i, v);\n else\n this.update_(rc, i, v);\n this.tree[k].v = this.op(this.tree[lc].v, this.tree[rc].v);\n }\n update(i, v) {\n this.update_(1, i + 1, v);\n }\n lazy(k, v) {\n this.tree[k].v = this.tree[k].lazy = v;\n }\n pushDown(k) {\n const lc = 2 * k, rc = lc + 1;\n this.lazy(lc, this.tree[k].lazy);\n this.lazy(rc, this.tree[k].lazy);\n this.tree[k].lazy = void 0;\n }\n updateRange_(k, l, r, v) {\n if (l <= this.tree[k].l && this.tree[k].r <= r)\n return this.lazy(k, v);\n if (this.tree[k].lazy !== void 0)\n this.pushDown(k);\n const mid = this.tree[k].l + this.tree[k].r >> 1;\n const lc = k * 2, rc = lc + 1;\n if (l <= mid)\n this.updateRange_(lc, l, r, v);\n if (mid < r)\n this.updateRange_(rc, l, r, v);\n this.tree[k].v = this.op(this.tree[lc].v, this.tree[rc].v);\n }\n updateRange(l, r, v) {\n this.updateRange_(1, l + 1, r + 1, v);\n }\n query_(k, l, r) {\n if (l <= this.tree[k].l && this.tree[k].r <= r)\n return this.tree[k].v;\n if (this.tree[k].lazy !== void 0)\n this.pushDown(k);\n let res = this.e;\n const mid = this.tree[k].l + this.tree[k].r >> 1;\n const lc = k * 2, rc = lc + 1;\n if (l <= mid)\n res = this.op(res, this.query_(lc, l, r));\n if (mid < r)\n res = this.op(res, this.query_(rc, l, r));\n return res;\n }\n query(l, r) {\n return this.query_(1, l + 1, r + 1);\n }\n};\n\n// codeforces/1676H2/src/ts/solution2.ts\nvar lines = [];\nrequire(\"readline\").createInterface({\n input: process.stdin\n}).on(\"line\", (line) => lines.push(line));\nprocess.stdin.on(\"end\", () => {\n main(lines);\n});\nvar n;\nvar a;\nvar main = (lines2) => {\n let _ln = 0;\n const readString = () => lines2[_ln++];\n const readStrings = () => readString().split(\" \");\n const readNumber = () => Number(readString());\n const readNumbers = () => readStrings().map(Number);\n for (let t = readNumber(); t > 0; t--) {\n n = readNumber();\n a = readNumbers();\n output(solve());\n }\n};\nvar solve = () => {\n const b = new Array(n).fill(0);\n const segTree = new SegmentTree(b, (a2, b2) => a2 + b2, 0);\n let res = 0;\n for (const ai of a) {\n res += segTree.query(ai - 1, n - 1);\n b[ai - 1]++;\n segTree.update(ai - 1, b[ai - 1]);\n }\n return res;\n};\nvar output = (res) => {\n console.log(res);\n};\n"}, {"source_code": "// ../../lib/ts/BIT.ts\nvar BIT = class {\n constructor(n2 = 0) {\n this.n = n2;\n this.seg = new Array(n2 + 1).fill(0);\n }\n add(i, v) {\n i++;\n while (i <= this.n) {\n this.seg[i] += v;\n i += i & -i;\n }\n }\n sumTo(i) {\n let res = 0;\n while (i > 0) {\n res += this.seg[i];\n i -= i & -i;\n }\n return res;\n }\n sum(a2, b) {\n return this.sumTo(b + 1) - this.sumTo(a2);\n }\n};\n\n// codeforces/1676H2/src/ts/solution1.ts\nvar lines = [];\nrequire(\"readline\").createInterface({\n input: process.stdin\n}).on(\"line\", (line) => lines.push(line));\nprocess.stdin.on(\"end\", () => {\n main(lines);\n});\nvar n;\nvar a;\nvar main = (lines2) => {\n let _ln = 0;\n const readString = () => lines2[_ln++];\n const readStrings = () => readString().split(\" \");\n const readNumber = () => Number(readString());\n const readNumbers = () => readStrings().map(Number);\n for (let t = readNumber(); t > 0; t--) {\n n = readNumber();\n a = readNumbers();\n output(solve());\n }\n};\nvar solve = () => {\n const bit = new BIT(n);\n let res = 0;\n for (const ai of a) {\n res += bit.sum(ai - 1, n - 1);\n bit.add(ai - 1, 1);\n }\n return res;\n};\nvar output = (res) => {\n console.log(res);\n};\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst lineReader = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet inputPos = 0;\r\nconst inputWords = [];\r\nlineReader.on('line', (line) => {\r\n inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));\r\n});\r\nlineReader.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(inputWords[inputPos++]));\r\n}\r\nfunction nextStr() {\r\n return inputWords[inputPos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nconst INF = Infinity;\r\nfunction lsone(s) {\r\n return s & (-s);\r\n}\r\nclass FenwickTree {\r\n constructor(n) {\r\n this.n = n;\r\n this.ft = af(n + 1).fill(0);\r\n }\r\n adjust(pos, v) {\r\n for (; pos < this.n; pos += lsone(pos)) {\r\n this.ft[pos] += v;\r\n }\r\n // printf(\"adjust(%d,%d) ft %j\\n\", pos, v, this.ft);\r\n }\r\n query(pos) {\r\n let rv = 0;\r\n for (; pos > 0; pos -= lsone(pos)) {\r\n rv += this.ft[pos];\r\n }\r\n return rv;\r\n }\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc--) {\r\n let n = nextInt();\r\n const a = af(n);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = nextInt();\r\n }\r\n const ft = new FenwickTree(n);\r\n let ans = 0;\r\n for (let i = 0; i < n; i++) {\r\n let prior = i;\r\n let left = ft.query(a[i] - 1);\r\n ans += prior - left;\r\n ft.adjust(a[i], 1);\r\n }\r\n printf(\"%d\\n\", ans);\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction _defineProperty(obj, key, value) {\r\n if (key in obj) {\r\n Object.defineProperty(obj, key, {\r\n value: value,\r\n enumerable: true,\r\n configurable: true,\r\n writable: true\r\n });\r\n } else {\r\n obj[key] = value;\r\n }\r\n\r\n return obj;\r\n}\r\n\r\nfunction solve(n, a) {\r\n let res = 0;\r\n const bst = new BinarySearchTree();\r\n for (let i = n - 1; i >= 0; i--) {\r\n const cur = a[i];\r\n res += bst.size() - bst.countGreaterThanEq(cur + 1);\r\n bst.insert(cur);\r\n }\r\n return res.toString();\r\n}\r\nclass BinarySearchTree {\r\n constructor(_compare = (a, b) => a - b) {\r\n _defineProperty(this, \"root\", null);\r\n _defineProperty(this, \"length\", 0);\r\n _defineProperty(this, \"min\", null);\r\n _defineProperty(this, \"max\", null);\r\n _defineProperty(this, \"minCache\", true);\r\n _defineProperty(this, \"maxCache\", true);\r\n this._compare = _compare;\r\n this.compare = this.compare.bind(this);\r\n }\r\n isT(t) {\r\n return t !== undefined && t !== null;\r\n }\r\n compare(a, b) {\r\n const {\r\n isT\r\n } = this;\r\n if (isT(a) && isT(b)) return this._compare(a, b);\r\n if (isT(a)) return 1;\r\n if (isT(b)) return -1;\r\n return 0;\r\n }\r\n isEmpty() {\r\n return !this.root;\r\n }\r\n size() {\r\n return this.root ? this.root.size : 0;\r\n }\r\n getRoot() {\r\n return this.root;\r\n }\r\n getMin() {\r\n if (this.minCache) {\r\n return this.min;\r\n }\r\n const min = this.searchKth(this.size());\r\n this.min = min;\r\n this.minCache = true;\r\n return min;\r\n }\r\n getMax() {\r\n if (this.maxCache) {\r\n return this.max;\r\n }\r\n const max = this.searchKth(1);\r\n this.max = max;\r\n this.maxCache = true;\r\n return max;\r\n }\r\n balance(node) {\r\n node.height = this.getHeight(node);\r\n const blance = this.getBalance(node);\r\n let res;\r\n if (Math.abs(blance) === 2) {\r\n if (blance > 0) {\r\n var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;\r\n const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRight(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeftRight(node);\r\n }\r\n } else {\r\n var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;\r\n const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRightLeft(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeft(node);\r\n }\r\n }\r\n }\r\n return res ? res : node;\r\n }\r\n rotateRight(node) {\r\n const left = node.left;\r\n const leftRight = left.right;\r\n left.right = node;\r\n node.left = leftRight;\r\n node.height = this.getHeight(node);\r\n left.height = this.getHeight(left);\r\n node.size = this.getSize(node);\r\n left.size = this.getSize(left);\r\n return left;\r\n }\r\n rotateLeft(node) {\r\n const right = node.right;\r\n const rightLeft = right.left;\r\n right.left = node;\r\n node.right = rightLeft;\r\n node.height = this.getHeight(node);\r\n right.height = this.getHeight(right);\r\n node.size = this.getSize(node);\r\n right.size = this.getSize(right);\r\n return right;\r\n }\r\n rotateLeftRight(node) {\r\n node.left = this.rotateLeft(node.left);\r\n return this.rotateRight(node);\r\n }\r\n rotateRightLeft(node) {\r\n node.right = this.rotateRight(node.right);\r\n return this.rotateLeft(node);\r\n }\r\n getBalance(node) {\r\n return this.getHeight(node.left) - this.getHeight(node.right);\r\n }\r\n getHeight(node) {\r\n var _node$left$height, _node$left3, _node$right$height, _node$right3;\r\n if (!node) return 0;\r\n return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;\r\n }\r\n getSize(node) {\r\n var _node$left$size, _node$left4, _node$right$size, _node$right4;\r\n if (!node) return 0;\r\n return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;\r\n }\r\n createNode(val) {\r\n return {\r\n id: Math.random() * new Date().valueOf(),\r\n val,\r\n left: null,\r\n right: null,\r\n size: 1,\r\n height: 1,\r\n count: 1\r\n };\r\n }\r\n insert(val) {\r\n let cur = this.createNode(val);\r\n if (this.isEmpty()) {\r\n this.root = cur;\r\n this.length++;\r\n } else {\r\n [, cur] = this.insertNode(this.root, cur);\r\n }\r\n if (this.min === null || this.compare(this.min, val) > 0) {\r\n this.min = val;\r\n }\r\n if (this.max === null || this.compare(this.max, val) < 0) {\r\n this.max = val;\r\n }\r\n }\r\n insertNode(node, cur, parent = null) {\r\n node.size++;\r\n const compareResult = this.compare(cur.val, node.val);\r\n let res;\r\n if (compareResult === 0) {\r\n node.count++;\r\n return [false, node];\r\n } else if (compareResult > 0) {\r\n if (node.right) {\r\n res = this.insertNode(node.right, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.right = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n } else {\r\n if (node.left) {\r\n res = this.insertNode(node.left, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.left = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n }\r\n let preHeight = node.height;\r\n const newNode = this.balance(node);\r\n if (newNode === node && node.height === preHeight) {\r\n res = [false, res[1]];\r\n } else if (newNode !== node) {\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n res = [false, res[1]];\r\n }\r\n return res;\r\n }\r\n delete(val) {\r\n if (!this.root) return;\r\n this.deleteNode(val, this.root, null);\r\n }\r\n deleteNode(val, node, parent) {\r\n if (!node) return null;\r\n let res = this.compare(val, node.val);\r\n if (res === 0) {\r\n node.count--;\r\n node.size--;\r\n if (node.count > 0) return node;\r\n if (!node.left || !node.right) {\r\n if (this.min === val) {\r\n this.minCache = false;\r\n }\r\n if (this.max === val) {\r\n this.maxCache = false;\r\n }\r\n this.length--;\r\n if (!parent) {\r\n var _node$left5;\r\n this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;\r\n return this.root;\r\n } else {\r\n var _node$left6;\r\n return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;\r\n }\r\n } else {\r\n const selectLeft = node.left.height > node.right.height;\r\n let replaceNode = selectLeft ? this.pre(node) : this.next(node),\r\n name = selectLeft ? 'left' : 'right';\r\n node.val = replaceNode.val;\r\n node.count = replaceNode.count;\r\n replaceNode.count = 0;\r\n node[name] = this.deleteNode(replaceNode.val, node[name], node);\r\n }\r\n } else if (res > 0) {\r\n node.right = this.deleteNode(val, node.right, node);\r\n } else {\r\n node.left = this.deleteNode(val, node.left, node);\r\n }\r\n node.size = this.getSize(node);\r\n node.height;\r\n const newNode = this.balance(node);\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n return newNode;\r\n }\r\n next(node) {\r\n let next = node.right;\r\n while ((_next = next) !== null && _next !== void 0 && _next.left) {\r\n var _next;\r\n next = next.left;\r\n }\r\n return next;\r\n }\r\n pre(node) {\r\n let pre = node.left;\r\n while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {\r\n var _pre;\r\n pre = pre.right;\r\n }\r\n return pre;\r\n }\r\n search(val, compare) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);\r\n return node.val;\r\n }\r\n searchCeilingNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.searchCeilingNode(node.right, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n const [p, value] = this.searchCeilingNode(node.left, val, compare, node);\r\n if (compare(value.val, val) < 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n ceiling(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) >= 0 ? node.val : null;\r\n }\r\n searchFloorNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n const [p, value] = this.searchFloorNode(node.right, val, compare, node);\r\n if (compare(value.val, val) > 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n return this.searchFloorNode(node.left, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n floor(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchFloorNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) <= 0 ? node.val : null;\r\n }\r\n searchKth(k) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n if (k <= 0 || k > this.size()) {\r\n return null;\r\n }\r\n const node = this.searchNodeKth(this.root, k);\r\n return node.val;\r\n }\r\n searchNodeKth(node, k) {\r\n var _node$right$size2, _node$right5, _node$right$size3, _node$right6;\r\n const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;\r\n if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;\r\n if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);\r\n }\r\n countGreaterThanEq(val) {\r\n if (!this.root) return 0;\r\n return this.countCompare(val, (a, b) => this._compare(a, b), this.root);\r\n }\r\n countCompare(val, compare, node, pre = 0) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n var _node$right$size4, _node$right7;\r\n return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.countCompare(val, compare, node.right, pre);\r\n } else {\r\n return pre;\r\n }\r\n } else {\r\n var _node$right$size5, _node$right8;\r\n let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;\r\n if (node.left) {\r\n return this.countCompare(val, compare, node.left, count);\r\n } else {\r\n return count;\r\n }\r\n }\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n let res = [];\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n res.push(solve(n, a));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\n// HEADER:\nconst print = console.log;\nlet IS_MULTITEST, testN;\nconst pcalc = testN=>{\n let res = calc(testN);\n if (Array.isArray(res)){\n pa(res);\n } else if (Number.isFinite(res) || typeof res=='string'){\n print(res);\n }\n};\n\nconst main = ()=>{\n if (IS_MULTITEST){\n let T = +readline()\n for (testN=1; testN<=T; testN++)\n pcalc(T);\n } else\n pcalc();\n};\n\nconst lines = [];\nconst rl = require('readline').createInterface({\n input: process.stdin, output: process.stdout});\nrl.on('line', line=>{\n lines.push(line);\n});\nrl.on('close', main);\nlet rli = 0;\nconst readline = ()=>lines[rli++];\nconst L = process.env.DEBUG ? console.log : ()=>{};\nconst LT = obj=>L(`Test #${testN}`, obj);\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\nconst pa = arr=>print(arr.join(' '));\n\n// SOLUTION:\nIS_MULTITEST = 1;\n \nconst calc = ()=>{\n // READING:\n let [n] = ra();\n let A = ra().map(a=>a-1);\n // PROCESSING:\n let ans = 0;\n let cnt = {};\n let revA = new Array(n).fill(0);\n for (let i=0; i{\n let result = 0;\n for (; r >= 0; r = (r & (r+1)) - 1)\n result += t[r];\n return result;\n }\n let inc = (i, delta)=>{\n for (; i < n; i = (i | (i+1)))\n t[i] += delta;\n }\n for (let i=0; i=i){\n cntLeft++;\n deductLeft[A[i-1]]++;\n }\n cntRight -= deductRight[i];\n if (revA[i-1]>=i){\n cntRight++;\n deductRight[revA[i-1]]++;\n }\n ans += cntLeft*cntRight;\n // maintain cnt of all from left bigger than i\n // maintain all from right lower than i\n }\n return ans;\n};\n "}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nlet F\nfunction inc(idx, val) {\n for (; idx < F.length; idx |= idx + 1) {\n F[idx] += val\n }\n}\nfunction sum(idx) {\n let s = 0\n for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {\n s += F[idx]\n }\n return s\n}\n\nfunction solve(n, arr) {\n const sorted = arr.map((x, i) => ({ x, i: i + 1 }))\n .sort((a, b) => {\n if (a.x === b.x) {\n return b.i - a.i\n } else {\n return a.x - b.x\n }\n })\n // console.log(sorted)\n F = Array(n + 5).fill(0) // a little larger in case\n let ans = 0\n for (let i = sorted.length - 1; i >= 0; i--) {\n const it = sorted[i]\n ans += sum(it.i)\n //\n inc(it.i, 1)\n }\n return ans\n}\n"}, {"source_code": "//import { readline, print } from '@ip-algorithmics/codeforces-io';\r\nvar t = +readline();\r\nvar _loop_1 = function () {\r\n var n = readline().split(' ').map(function (v) { return +v; })[0];\r\n var a = readline().split(' ').map(function (v) { return +v; });\r\n var len = n + 1;\r\n var t_1 = [];\r\n while (len) {\r\n t_1.push(Array(len + 1).fill(0));\r\n len >>= 1;\r\n }\r\n var sum = 0;\r\n var _loop_2 = function (i) {\r\n var v = a[i] + 1;\r\n var _loop_3 = function (l) {\r\n var f = v & 1 ? function () { sum += t_1[l][v]; } : function () { };\r\n v >>= 1;\r\n f();\r\n };\r\n for (var l = 0; l < t_1.length; l++) {\r\n _loop_3(l);\r\n }\r\n v = a[i];\r\n for (var l = 0; l < t_1.length; l++) {\r\n if (~v & 1) {\r\n t_1[l][v >> 1] += 1;\r\n }\r\n v >>= 1;\r\n }\r\n };\r\n for (var i = n; i--;) {\r\n _loop_2(i);\r\n }\r\n print(sum);\r\n};\r\nwhile (t--) {\r\n _loop_1();\r\n}\r\n"}], "negative_code": [{"source_code": "//import { readline, print } from '@ip-algorithmics/codeforces-io';\r\nvar t = +readline();\r\nvar _loop_1 = function () {\r\n var n = readline().split(' ').map(function (v) { return +v; })[0];\r\n var a = readline().split(' ').map(function (v) { return +v; });\r\n var len = n + 1;\r\n var t_1 = [];\r\n while (len) {\r\n t_1.push(Array(len + 1).fill(0));\r\n len >>= 1;\r\n }\r\n var sum = 0;\r\n var _loop_2 = function (i) {\r\n var v = a[i] + 1;\r\n var _loop_3 = function (l) {\r\n var f = v & 1 ? function () { sum += t_1[l][v]; } : function () { };\r\n v >>= 1;\r\n f();\r\n };\r\n for (var l = 0; l < t_1.length; l++) {\r\n _loop_3(l);\r\n }\r\n v = a[i] + 1;\r\n for (var l = 0; l < t_1.length; l++) {\r\n if (v ^ 1) {\r\n t_1[l][v >> 1] += 1;\r\n }\r\n v >>= 1;\r\n }\r\n };\r\n for (var i = n; i--;) {\r\n _loop_2(i);\r\n }\r\n print(sum);\r\n};\r\nwhile (t--) {\r\n _loop_1();\r\n}\r\n"}], "src_uid": "35dccda260cfdaea651d1950df452e7a"} {"nl": {"description": "You have a fence consisting of $$$n$$$ vertical boards. The width of each board is $$$1$$$. The height of the $$$i$$$-th board is $$$a_i$$$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \\neq a_i$$$ holds.Unfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the $$$i$$$-th board by $$$1$$$, but you have to pay $$$b_i$$$ rubles for it. The length of each board can be increased any number of times (possibly, zero).Calculate the minimum number of rubles you have to spend to make the fence great again!You have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 3 \\cdot 10^5$$$) — the number of queries. The first line of each query contains one integers $$$n$$$ ($$$1 \\le n \\le 3 \\cdot 10^5$$$) — the number of boards in the fence. The following $$$n$$$ lines of each query contain the descriptions of the boards. The $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le 10^9$$$) — the length of the $$$i$$$-th board and the price for increasing it by $$$1$$$, respectively. It is guaranteed that sum of all $$$n$$$ over all queries not exceed $$$3 \\cdot 10^5$$$. It is guaranteed that answer to each query will not exceed $$$10^{18}$$$.", "output_spec": "For each query print one integer — the minimum number of rubles you have to spend to make the fence great.", "sample_inputs": ["3\n3\n2 4\n2 1\n3 5\n3\n2 3\n2 10\n2 6\n4\n1 7\n3 3\n2 6\n1000000000 2"], "sample_outputs": ["2\n9\n0"], "notes": "NoteIn the first query you have to increase the length of second board by $$$2$$$. So your total costs if $$$2 \\cdot b_2 = 2$$$.In the second query you have to increase the length of first board by $$$1$$$ and the length of third board by $$$1$$$. So your total costs if $$$1 \\cdot b_1 + 1 \\cdot b_3 = 9$$$.In the third query the fence is great initially, so you don't need to spend rubles."}, "positive_code": [{"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const cost = [0]\n const arr = [0]\n for (let i = 1; i <= n; ++i) {\n const ab = getInts()\n arr[i] = ab[0]\n cost[i] = ab[1]\n }\n\n print(solve(arr, cost))\n }\n}\n \nfunction solve (arr, cost) {\n const n = arr.length\n const dp = [[0, cost[0], cost[0] * 2]]\n\n for (let i = 1; i < n; ++i) {\n const cur = []\n for (let j = 0; j <= 2; ++j) {\n let best = Number.MAX_SAFE_INTEGER\n for (let k = 0; k <= 2; ++k) {\n if (arr[i - 1] + k !== arr[i] + j) {\n best = Math.min(best, dp[i - 1][k] + cost[i] * j)\n }\n }\n cur[j] = best\n }\n dp[i] = cur\n }\n\n return Math.min(dp[n - 1][0], dp[n - 1][1], dp[n - 1][2])\n}\n"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n var t = getInt()\n while (t --> 0) {\n const n = getInt()\n const cost = [0]\n const arr = [0]\n for (var i = 1; i <= n; ++i) {\n const ab = getInts()\n arr[i] = ab[0]\n cost[i] = ab[1]\n }\n\n print(solve(arr, cost))\n }\n}\n\nfunction solve (arr, cost) {\n const n = arr.length\n const dp = [[0, cost[0], cost[0] * 2]]\n\n for (var i = 1; i < n; ++i) {\n const cur = []\n for (var j = 0; j <= 2; ++j) {\n var best = Number.MAX_SAFE_INTEGER\n for (var k = 0; k <= 2; ++k) {\n if (arr[i - 1] + k !== arr[i] + j) {\n best = Math.min(best, dp[i - 1][k] + cost[i] * j)\n }\n }\n cur[j] = best\n }\n dp[i] = cur\n }\n\n return Math.min(dp[n - 1][0], dp[n - 1][1], dp[n - 1][2])\n}\n"}], "negative_code": [{"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const cost = [0]\n const arr = [0]\n for (let i = 0; i < n; ++i) {\n const ab = getInts()\n arr.push(ab[0])\n cost.push(ab[1])\n }\n\n print(solve(arr, cost))\n }\n}\n\nfunction solve (arr, cost) {\n const n = arr.length\n const dp = [[0, 0]]\n\n for (let i = 1; i < n; ++i) {\n dp.push([0, 0])\n const changeCurrent = calc(i, arr, cost)\n\n if (arr[i] !== arr[i - 1]) {\n dp[i][0] = Math.min(dp[i - 1][0], dp[i - 1][1])\n }\n else {\n dp[i][0] = dp[i - 1][1]\n }\n dp[i][1] = Math.min(dp[i - 1][0] + changeCurrent, dp[i - 1][1] + changeCurrent)\n }\n\n return Math.min(dp[n - 1][0], dp[n - 1][1])\n}\n\nfunction calc (i, arr, cost) {\n let times = 1\n while (true) {\n const val = arr[i] + times\n if (val !== arr[i + 1] && val !== arr[i - 1]) break\n times ++\n }\n\n return times * cost[i]\n}"}, {"source_code": "'use strict'\n\nconst getLine = () => readline().split(' ')\nconst getInts = () => getLine().map(n => parseInt(n))\nconst getInt = () => getInts()[0]\nconst D = (...args) => { // D({name})\n [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))\n}\n\nmain()\n\nfunction main() {\n let t = getInt()\n while (t --> 0) {\n const n = getInt()\n const cost = [0]\n const arr = [0]\n for (let i = 0; i < n; ++i) {\n const ab = getInts()\n arr.push(ab[0])\n cost.push(ab[1])\n }\n\n print(solve(arr, cost))\n }\n}\n\nfunction solve (arr, cost) {\n const n = arr.length\n const dp = [[0, 0]]\n for (let i = 1; i < n; ++i) {\n dp.push([0, 0])\n if (arr[i] === arr[i - 1]) {\n dp[i][0] = dp[i - 1][1]\n dp[i][1] = dp[i - 1][0] + cost[i]\n } else {\n dp[i][0] = Math.min(dp[i - 1][0], calc(i - 1, dp[i - 1][1], arr, cost))\n dp[i][1] = dp[i - 1][0] + cost[i]\n }\n }\n\n return Math.min(dp[n - 1][0], dp[n - 1][1])\n}\n\nfunction calc (i, cur, arr, cost) {\n if (arr[i] + 1 === arr[i + 1]) {\n cur += cost[i]\n }\n return cur\n}"}], "src_uid": "3e18c9566a43504ff464306900b92855"} {"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  ≤  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 ≤ n ≤ 100 000) — number of cola cans. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — volume of remaining cola in cans. The third line contains n space-separated integers that b1, b2, ..., bn (ai ≤ bi ≤ 109) — 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": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n')\n const n = parseInt(arr.shift())\n const remain2 = arr.shift().split(' ')\n const capacity2 = arr.shift().split(' ')\n var remain = []\n var capacity = []\n var sum = 0\n for(let i = 0; i < n; i++) {\n remain.push(parseInt(remain2[i]))\n capacity.push(parseInt(capacity2[i]))\n }\n sum = remain.reduce((a, b) => a + b)\n\n capacity = capacity.sort((a, b) => b - a)\n // console.log(capacity)\n\n if(capacity[0] + capacity[1] >= sum) console.log('YES')\n else console.log('NO')\n})"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet cola;\nlet cans;\nlet n;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n n = +d;\n return;\n }\n\n if (c === 1) {\n c++;\n cola = d.split(' ').map(Number).reduce((a, b) => a + b, 0);\n return;\n }\n\n cans = d.split(' ').map(Number);\n cans.sort((a, b) => b - a);\n\n c++;\n});\n\nrl.on('close', () => {\n if (n === 2) {\n console.log('YES');\n return;\n }\n\n const [a, b] = cans;\n\n if (a + b >= cola) {\n console.log('YES');\n }\n else {\n console.log(\"NO\");\n }\n});\n"}, {"source_code": "var n = parseInt(readline());\nvar sum = 0, max1 = 0, max2 = 0;\nvar array1 = readline().split(' ');\nvar array2 = readline().split(' ');\nfor (var i = 0; i < n; i++) {\n\tarray2[i]= parseInt(array2[i]);\n\tarray1[i]= parseInt(array1[i]);\n}\nfor (var i = 0; i < n; i++) {\n\tsum += array1[i];\n\tif (array2[i] > max1) {\n\t\tmax2 = max1;\n\t\tmax1 = array2[i];\n\t} else if (array2[i] > max2) {\n\t\tmax2 = array2[i];\n\t}\n}\nif (sum > max1 + max2) {\n\tprint('NO');\n} else {\n\tprint('YES');\n}"}, {"source_code": "n = +readline();\nfunction add(a, b) { \n return a + b; \n}\nfunction cmp(a, b) {\n return b - a;\n}\na = readline().split(\" \").map(Number).reduce(add, 0);\nb = readline().split(\" \").map(Number).sort(cmp).slice(0, 2).reduce(add, 0);\nprint(b >= a ? \"YES\" : \"NO\");"}, {"source_code": "n = +readline();\nfunction add(a, b) { \n return a + b; \n}\nfunction cmp(a, b) {\n return a - b;\n}\na = readline().split(\" \").map(Number).reduce(add, 0);\nb = readline().split(\" \").map(Number).sort(cmp).slice(-2).reduce(add, 0);\n// print(b);\nprint(b >= a ? \"YES\" : \"NO\");"}, {"source_code": "function toInt(x) {\n\treturn parseInt(x);\n}\n\nvar n = toInt(readline());\nvar sum = 0;\nvar max1 = 0;\nvar max2 = 0;\nvar ar = readline().split(' ').map(toInt);\nvar br = readline().split(' ').map(toInt);\n\nfor (var i = 0; i < n; i++) {\n\tsum += ar[i];\n\tif (br[i] > max1) {\n\t\tmax2 = max1;\n\t\tmax1 = br[i];\n\t} else if (br[i] > max2) {\n\t\tmax2 = br[i];\n\t}\n}\n\nif (sum > max1 + max2) {\n\tprint('NO');\n} else {\n\tprint('YES');\n}"}, {"source_code": "var n = parseInt(readline(), 10)\n a = readline().split(' ').map(el => parseInt(el, 10)),\n b = readline().split(' ').map(el => parseInt(el, 10)).sort((a,b) => b-a);\n \nprint((a.reduce((a,b) => a+b) <= b[0]+b[1]) ? 'YES' : 'NO');"}, {"source_code": "n = +readline();\nvolume = readline();\nbanks = readline();\nvol = 0;\n\narrV = volume.split(\" \");\narrV.forEach(function(item, i, arr){\n vol = vol + +item;\n})\n\narrB = banks.split(\" \");\n\narrB.sort(compareNumeric);\n\nfunction compareNumeric(a, b) {\n return b - a;\n}\n\nplace = +arrB[0] + +arrB[1];\nif (place >= vol){\n write(\"YES\");\n} else {\n write(\"NO\");\n}"}], "negative_code": [{"source_code": "n = +readline();\nfunction add(a, b) { \n return a + b; \n}\na = readline().split(\" \").map(Number).reduce(add, 0);\nb = readline().split(\" \").map(Number).sort().slice(-2).reduce(add, 0);\n// print(b);\nprint(b >= a ? \"YES\" : \"NO\");"}, {"source_code": "n = +readline();\nfunction add(a, b) { \n return a + b; \n}\nfunction cmp(a, b) {\n return a - b;\n}\na = readline().split(\" \").map(Number).reduce(add, 0);\nb = readline().split(\" \").map(Number).sort(cmp).slice(-2, 0).reduce(add, 0);\nprint(b >= a ? \"YES\" : \"NO\");"}, {"source_code": "n = +readline();\nfunction add(a, b) { \n return a + b; \n}\na = readline().split(\" \").map(Number).reduce(add, 0);\nb = readline().split(\" \").map(Number).sort().slice(-2).reduce(add, 0);\nprint(b >= a ? \"YES\" : \"NO\");"}, {"source_code": "n = +readline();\nfunction add(a, b) { \n return a + b; \n}\nfunction cmp(a, b) {\n return b - a;\n}\na = readline().split(\" \").map(Number).reduce(add, 0);\nb = readline().split(\" \").map(Number).sort(cmp).slice(2).reduce(add, 0);\nprint(b >= a ? \"YES\" : \"NO\");"}, {"source_code": "function toInt(x) {\n\treturn parseInt(x);\n}\n\nvar n = toInt(readline());\nvar sum = 0;\nvar max1 = 0;\nvar max2 = 0;\nvar ar = readline().split(' ').map(toInt);\nvar br = readline().split(' ').map(toInt);\n\nfor (var i = 0; i < n; i++) {\n\tsum += ar[i];\n\tif (br[i] > max1) {\n\t\tmax2 = max1;\n\t\tmax1 = br[i];\n\t}\n}\n\nif (sum > max1 + max2) {\n\tprint('NO');\n} else {\n\tprint('YES');\n}"}], "src_uid": "88390110e4955c521867864a6f3042a0"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$. Array is good if for each pair of indexes $$$i < j$$$ the condition $$$j - a_j \\ne i - a_i$$$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if $$$a = [1, 1, 3, 5]$$$, then shuffled arrays $$$[1, 3, 5, 1]$$$, $$$[3, 5, 1, 1]$$$ and $$$[5, 3, 1, 1]$$$ are good, but shuffled arrays $$$[3, 1, 5, 1]$$$, $$$[1, 1, 3, 5]$$$ and $$$[1, 1, 5, 3]$$$ aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) — 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 100$$$).", "output_spec": "For each test case print the shuffled version of the array $$$a$$$ which is good.", "sample_inputs": ["3\n1\n7\n4\n1 1 3 5\n6\n3 2 1 5 6 4"], "sample_outputs": ["7\n1 5 1 3\n2 4 6 1 3 5"], "notes": null}, "positive_code": [{"source_code": "function merge (arrA, arrB) {\n var merged = [];\n var j = 0;\n var k = 0;\n\n while (merged.length !== (arrA.length + arrB.length)) {\n if (arrB[k] === undefined || arrA[j] >= arrB[k]) {\n merged.push(arrA[j]);\n j++;\n } else if (arrA[j] === undefined || arrA[j] < arrB[k]) {\n merged.push(arrB[k]);\n k++;\n }\n }\n\n return merged;\n}\n\n\nfunction mergeSort (array) {\n var result = array.map(num => [num]);\n\n while (result.length > 1) {\n var oddNumbered = result.length % 2 !== 0;\n var temp = [];\n\n for (var i = 0; i < result.length; i += 2) {\n var a = result[i];\n var b = result[i + 1];\n\n if (oddNumbered && i === (result.length - 3)) {\n b = merge(b, result[i + 2]);\n i++;\n }\n\n temp.push(merge(a, b));\n }\n\n result = temp;\n }\n return result[0];\n}\n\nfunction processItem() {\n var count = readline();\n var items = readline().split(' ').map(function(i) { return +i; });\n \n print(mergeSort(items).join(' '));\n}\n\nfunction processItems() {\n var itemsCount = +readline();\n var items = [];\n\n for (var i = 0; i < itemsCount; ++i) {\n processItem();\n }\n\n return items;\n}\n\nprocessItems();"}, {"source_code": "Main();\nfunction myout(t){print(t);}//standard output\nfunction next(){return readline();}\nfunction nextInt(){return myconv(next(),1);}\nfunction nextStrArray(){return myconv(next(),2);}//半角スペース分割\nfunction nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化\nfunction nextCharArray(){return myconv(next(),6);}//1文字分割\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す\n//6:1文字に分割 7:1文字に分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\n//atcoderのサンプルは最後に改行入れること\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map((a)=>Number(a));case 6:return i.split(\"\");case 7:return i.split(\"\").map((a)=>Number(a));case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main() {\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var n = nextInt();\n var list = nextIntArray();\n //good list?\n list.sort(function(a,b){\n return b - a;\n });\n output[i] = myconv(list,8);\n }\n myout(myconv(output,9));\n}"}, {"source_code": "function readStringArray() {\n return readline().split(\" \");\n}\nfunction readNumArray() {\n return readStringArray().map(Number);\n}\n\nfunction main() {\n var testCasesNum = +readline();\n for (var i = 0; i < testCasesNum; i++) {\n var len = readline();\n var arr = readNumArray();\n\n print(arr.sort((a, b) => b - a).join(\" \"));\n }\n}\n\nmain()"}, {"source_code": "//var input = readline();\n\nvar T = parseInt(readline());\nfor (var i = 0; i parseInt(x));\n ar.sort((a, b) => b - a);\n\n print(ar.join(' '));\n}\n"}, {"source_code": "//var input = readline();\nvar T = parseInt(readline());\n\nfor (var i = 0; i < T; i++) {\n var n = parseInt(readline()); \n var ar = readline().split(' ').map(x => parseInt(x));\n print(ar.sort((a, b) => b - a).join(' '));\n}\n"}, {"source_code": "var t=readline();\nwhile(t--)\n{\n\tvar n=readline();\n\tvar arr = readline().split(\" \").map(x=> parseInt(x));\n\tvar ans=arr.sort((x,y) => x-y).reverse().join(' ');\n\tprint(ans);\n}"}, {"source_code": "// https://codeforces.com/contest/1312/problem/B\n\nexports.solveProblem = (lineList) => {\n const caseList = [];\n for (let i = 2; i < lineList.length; i += 2) {\n caseList.push(\n lineList[i]\n .split(' ')\n .map(\n v => parseInt(v.trim())\n )\n );\n }\n\n const result = [];\n for (let aCase of caseList) {\n // --------------------------------------------\n const n = aCase.length;\n aCase = aCase.sort((a, b) => a > b ? -1 : a < b ? 1 : 0);\n result.push(aCase.join(' '));\n // --------------------------------------------\n }\n\n return result.join('\\n');\n};\n\nconst processInput = (solveProblem) => {\n const chunkList = [];\n process.stdin.setEncoding('utf8');\n process.stdin.on('readable', () => {\n let chunk;\n while ((chunk = process.stdin.read()) !== null) {\n chunkList.push(chunk);\n }\n });\n process.stdin.on('end', () => {\n const lineList = chunkList.join('').split('\\n');\n const result = solveProblem(lineList);\n process.stdout.write(result);\n process.exit(0);\n });\n};\nif (module === require.main) {\n processInput(exports.solveProblem);\n}"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin\n});\n\nlet answer = \"\";\n\nlet lines = [];\n\nrl.on('line', (t)=>{\n lines.push(t);\n}).on('close', ()=>{\n let t = parseInt(lines[0]);\n for(let i = 0; i < t; i++)\n {\n let n = parseInt(lines[i * 2 + 1]);\n let a = lines[i * 2 + 2].split(\" \").map(function (x) {\n return parseInt(x);\n });\n /*\n console.log('a: ' + a.join());\n console.log('a.sort ' + a.sort().join());\n console.log('a[0] + a[1] = ' + (a[0] + a[1]));\n\n */\n answer += a.sort((x,y)=>x - y).reverse().join(' ') + '\\n';\n }\n console.log(answer);\n});"}, {"source_code": "const processData = (lines) => {\n const num = +lines[0]\n\n for (let j=0; j x).sort((a, b) => b-a)\n console.log(sorted.join(' '))\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const init = () => {\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n let inputString = '';\n let currentLine = 0;\n\n process.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n });\n\n process.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main(); \n });\n\n global.readline = () => {\n return inputString[currentLine++];\n };\n};\n\nif (typeof readline === 'undefined') {\n init();\n}\n\nconst print = (...args) => {\n console.log(...args);\n};\n\n// Write your logic in main();\n// let t = readline().split(' ').map(x => parseInt(x));\nconst main = () => {\n let t = parseInt(readline());\n while (t--) {\n let n = parseInt(readline());\n let a = readline().split(' ').map(x => parseInt(x));\n a.sort((a, b) => b - a);\n print(a.join(' '));\n }\n};\n"}, {"source_code": "var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nfunction main(raw) {\n var lines = raw.trim().split(\"\\n\").map(function (v) { return v.split(\" \").map(function (u) { return parseInt(u, 10); }); });\n var _a = __read(lines.shift(), 1), t = _a[0];\n while (t > 0) {\n var _b = __read(lines.shift(), 1), n = _b[0];\n var as = lines.shift();\n // const as = Array.from({length: 100}).map(_ => Math.ceil(Math.random() * 100));\n console.log(as.sort(function (a, b) { return b - a; }).join(\" \"));\n t--;\n }\n}\nfunction test(as) {\n for (var i = 0; i < as.length; i++) {\n for (var j = i + 1; j < as.length; j++) {\n if (j - as[j] === i - as[i]) {\n return false;\n }\n }\n }\n return true;\n}\n(function () {\n var d = \"\";\n process.stdin.on(\"data\", function (c) { return d += c; });\n process.stdin.on(\"end\", function () { return main(d); });\n})();\n"}], "negative_code": [{"source_code": "var t=readline();\nwhile(t--)\n{\n\tvar n=readline();\n\tvar arr = readline().split(\" \").map(x=> parseInt(x));\n\tvar ans=arr.sort().reverse().join(' ');\n\tprint(ans);\n}"}, {"source_code": "// https://codeforces.com/contest/1312/problem/B\n\nexports.solveProblem = (lineList) => {\n const caseList = [];\n for (let i = 2; i < lineList.length; i += 2) {\n caseList.push(\n lineList[i].split(' ').map(v => parseInt(v.trim()))\n );\n }\n\n const result = [];\n for (let aCase of caseList) {\n const permu = [];\n const size = aCase.length;\n \n for (let i = 0; i < size; i++) {\n const val = aCase[i];\n permu.push([]);\n for (var j = 0; j < size; j++) {\n permu[i][j] = j - val;\n }\n }\n\n const sol = [];\n const diff = [];\n const used = new Map();\n for(let j = 0; j < size; j++) {\n const val = aCase[j];\n let min = Number.MAX_VALUE;\n for (let i = 0; i < size; i++) {\n const iVal = permu[i][j];\n if (!used.has(iVal) && iVal < min) {\n min = iVal;\n }\n }\n used.set(min);\n sol[j] = val;\n diff[j] = min;\n }\n\n result.push(sol);\n }\n\n return result.join('\\n');\n};\n\nconst processInput = (solveProblem) => {\n const chunkList = [];\n process.stdin.setEncoding('utf8');\n process.stdin.on('readable', () => {\n let chunk;\n while ((chunk = process.stdin.read()) !== null) {\n chunkList.push(chunk);\n }\n });\n process.stdin.on('end', () => {\n const lineList = chunkList.join('').split('\\n');\n const result = solveProblem(lineList);\n process.stdout.write(result);\n process.exit(0);\n });\n};\nif (module === require.main) {\n processInput(exports.solveProblem);\n}"}, {"source_code": "// https://codeforces.com/contest/1312/problem/B\n\nexports.solveProblem = (lineList) => {\n const caseList = [];\n for (let i = 2; i < lineList.length; i += 2) {\n caseList.push(\n lineList[i].split(' ').map(v => parseInt(v.trim()))\n );\n }\n\n const result = [];\n for (let aCase of caseList) {\n // --------------------------------------------\n const n = aCase.length;\n aCase = aCase.sort((a, b) => a < b);\n result.push(aCase.join(' '));\n // --------------------------------------------\n }\n\n return result.join('\\n');\n};\n\nconst processInput = (solveProblem) => {\n const chunkList = [];\n process.stdin.setEncoding('utf8');\n process.stdin.on('readable', () => {\n let chunk;\n while ((chunk = process.stdin.read()) !== null) {\n chunkList.push(chunk);\n }\n });\n process.stdin.on('end', () => {\n const lineList = chunkList.join('').split('\\n');\n const result = solveProblem(lineList);\n process.stdout.write(result);\n process.exit(0);\n });\n};\nif (module === require.main) {\n processInput(exports.solveProblem);\n}"}, {"source_code": "// https://codeforces.com/contest/1312/problem/B\n\nexports.solveProblem = (lineList) => {\n const caseList = [];\n for (let i = 2; i < lineList.length; i += 2) {\n caseList.push(\n lineList[i].split(' ').map(v => parseInt(v.trim()))\n );\n }\n\n const result = [];\n for (let aCase of caseList) {\n const permu = [];\n const size = aCase.length;\n \n for (let i = 0; i < size; i++) {\n const val = aCase[i];\n permu.push([]);\n for (var j = 0; j < size; j++) {\n permu[i][j] = j - val;\n }\n }\n\n const sol = [];\n const diff = [];\n const used = new Map();\n for(let j = 0; j < size; j++) {\n const val = aCase[j];\n let min = Number.MAX_VALUE;\n for (let i = 0; i < size; i++) {\n const iVal = permu[i][j];\n if (!used.has(iVal) && iVal < min) {\n min = iVal;\n }\n }\n used.set(min);\n sol[j] = val;\n diff[j] = min;\n }\n\n result.push(sol.join(' '));\n }\n\n return result.join('\\n');\n};\n\nconst processInput = (solveProblem) => {\n const chunkList = [];\n process.stdin.setEncoding('utf8');\n process.stdin.on('readable', () => {\n let chunk;\n while ((chunk = process.stdin.read()) !== null) {\n chunkList.push(chunk);\n }\n });\n process.stdin.on('end', () => {\n const lineList = chunkList.join('').split('\\n');\n const result = solveProblem(lineList);\n process.stdout.write(result);\n process.exit(0);\n });\n};\nif (module === require.main) {\n processInput(exports.solveProblem);\n}"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin\n});\n\nlet answer = \"\";\n\nlet lines = [];\n\nrl.on('line', (t)=>{\n lines.push(t);\n}).on('close', ()=>{\n let t = parseInt(lines[0]);\n for(let i = 0; i < t; i++)\n {\n let n = parseInt(lines[i * 2 + 1]);\n let a = lines[i * 2 + 2].split(\" \").map(function (x) {\n return parseInt(x);\n });\n a = a.sort().reverse();\n answer += a.join(' ') + '\\n';\n }\n\n\n\n\n\n console.log(answer);\n});"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin\n});\n\nlet answer = \"\";\n\nlet lines = [];\n\nrl.on('line', (t)=>{\n lines.push(t);\n}).on('close', ()=>{\n let t = parseInt(lines[0]);\n for(let i = 0; i < t; i++)\n {\n let n = parseInt(lines[i * 2 + 1]);\n let a = lines[i * 2 + 2].split(\" \").map(function (x) {\n return parseInt(x);\n });\n answer += a.sort().reverse().join(' ') + '\\n';\n }\n\n\n\n\n\n console.log(answer);\n});"}, {"source_code": "var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nfunction main(raw) {\n var lines = raw.trim().split(\"\\n\").map(function (v) { return v.split(\" \").map(function (u) { return parseInt(u, 10); }); });\n var _a = __read(lines.shift(), 1), t = _a[0];\n while (t > 0) {\n var _b = __read(lines.shift(), 1), n = _b[0];\n var as = lines.shift();\n // const as = Array.from({length: 100}).map(_ => Math.ceil(Math.random() * 100));\n console.log(test(as.sort(function (a, b) { return b - a; })));\n t--;\n }\n}\nfunction test(as) {\n for (var i = 0; i < as.length; i++) {\n for (var j = i + 1; j < as.length; j++) {\n if (j - as[j] === i - as[i]) {\n return false;\n }\n }\n }\n return true;\n}\n(function () {\n var d = \"\";\n process.stdin.on(\"data\", function (c) { return d += c; });\n process.stdin.on(\"end\", function () { return main(d); });\n})();\n"}], "src_uid": "1d89df4153d70087d212b711852eba5f"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \\dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^9$$$; $$$1 \\le k \\le 10^9$$$).", "output_spec": "For each test case, print one integer — the minimum possible maximum element in array $$$a$$$ such that the sum $$$(a_1 + \\dots + a_n)$$$ is divisible by $$$k$$$. ", "sample_inputs": ["4\n1 5\n4 3\n8 8\n8 17"], "sample_outputs": ["5\n2\n1\n3"], "notes": "NoteIn the first test case $$$n = 1$$$, so the array consists of one element $$$a_1$$$ and if we make $$$a_1 = 5$$$ it will be divisible by $$$k = 5$$$ and the minimum possible.In the second test case, we can create array $$$a = [1, 2, 1, 2]$$$. The sum is divisible by $$$k = 3$$$ and the maximum is equal to $$$2$$$.In the third test case, we can create array $$$a = [1, 1, 1, 1, 1, 1, 1, 1]$$$. The sum is divisible by $$$k = 8$$$ and the maximum is equal to $$$1$$$."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n var answer = []\r\n\r\n // console.log(Number(x))\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [n, k] = readline().split(' ').map(x => Number(x));\r\n\r\n var int = Math.floor(n + k - 1 / k)\r\n // console.log(Math.floor((k * int + n - 1) / n))\r\n\r\n console.log(Math.ceil(Math.ceil(n/k)*k/n))\r\n // console.log(n, k)\r\n // if (n < k) {\r\n // } else {\r\n // console.log(Math.ceil(n/k))\r\n // }\r\n // console.log(answer)\r\n // console.log(sum2)\r\n\r\n })\r\n\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const t = parseInt(readline(), 10);\r\n\r\n for (let i = 0; i < t; i += 1) {\r\n const a = readline().split(' ').map(num => parseInt(num, 10));\r\n const n = a[0];\r\n let k = a[1];\r\n\r\n if (n > k) {\r\n const div = Math.ceil(n / k);\r\n k *= div;\r\n }\r\n\r\n console.log(Math.ceil(k / n));\r\n }\r\n}\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', () => {\r\n inputString = inputString.split('\\n').map(str => str.trim());\r\n\r\n main();\r\n});\r\n"}, {"source_code": "function solve(len, ...params) {\n for (let i = 0; i < params.length; i++) {\n let arr = params[i].split(\" \");\n let n = parseInt(arr[0]);\n let k = parseInt(arr[1]);\n if (n === 1) {\n console.log(k);\n continue;\n }\n if (k === 0) {\n console.log(0);\n continue;\n }\n if (k === 1) {\n console.log(1);\n continue;\n }\n let res = k;\n let p = 0;\n let malti = parseInt(n / k);\n while (res < n) {\n res = k * malti;\n malti += 1;\n }\n p = parseInt(res / n);\n if (res % n === 0) {\n console.log(p);\n } else {\n console.log(p + 1);\n }\n }\n }\nlet text = \"\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nprocess.stdin.on(\"data\", (t) => {\n if (t === \"\\r\\n\" || t === \"\\n\") {\n process.stdin.emit(\"end\");\n } else {\n text += t;\n }\n});\nprocess.stdin.on(\"end\", () => {\n const input = text.trim().replace(/\\r/g, \"\").split(\"\\n\");\n solve(...input);\n process.exit();\n});\n\n\t \t \t\t\t\t\t\t \t\t \t\t \t\t \t\t\t"}, {"source_code": "function solve(n, k) {\n let ans;\n if (k % n === 0) {\n ans = k / n;\n } else {\n if (n > k) {\n ans = n % k === 0 ? 1 : 2\n } else {\n let factor = Math.floor(k / n);\n while (true) {\n const quotient = Math.floor((n * factor) / k);\n factor++;\n const nextQuotient = Math.floor((factor * n) / k);\n if (nextQuotient !== quotient) {\n ans = factor;\n break;\n }\n }\n }\n }\n console.log(ans);\n}\n\nlet text = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', t => {\n if (t === '\\r\\n' || t === '\\n') {\n process.stdin.emit('end');\n } else {\n text += t;\n }\n});\nprocess.stdin.on('end', () => {\n const input = text.trim().replace(/\\r/g, '').split('\\n');\n const dataArr = input\n .slice(1)\n .map(item => item.split(' ').map(n => parseInt(n)));\n const len = dataArr.length;\n\n for (let i = 0; i < len; i++) {\n solve(...dataArr[i]);\n }\n process.exit();\n});\n\n\t\t \t\t\t\t\t \t \t \t\t\t \t\t \t \t \t\t"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', (data) => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map((str) => str.trim());\n\tmain();\n});\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n\tfor (var a = arguments, r = a[0], i = a.length; --i; )\n\t\tr = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n\treturn r;\n}\nfunction inv(b) {\n\tfor (var a = MOD, u = 0, v = 1, t; b; v = t)\n\t\t(t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n\tu %= MOD;\n\treturn u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n\tif (n === 0) return 1;\n\tlet p = pow(base, Math.floor(n / 2));\n\tlet res = mul(mod(p), mod(p));\n\tif (n % 2 === 1) res = mul(mod(res), base);\n\treturn res;\n}\nfunction highestOneBit(i) {\n\ti |= i >> 1;\n\ti |= i >> 2;\n\ti |= i >> 4;\n\ti |= i >> 8;\n\ti |= i >> 16;\n\treturn i - (i >>> 1);\n}\nfunction permutation(arr, len, store = '', permutations = []) {\n\tif (store.length === len) {\n\t\tpermutations.push(store);\n\t\treturn;\n\t}\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tconst newArr = [...arr];\n\t\tconst newChar = newArr.splice(i, 1);\n\t\tpermutation(newArr, len, store.concat(newChar), permutations);\n\t}\n\treturn permutations;\n}\nfunction gcd(a, b) {\n\tif (b === 0) return a;\n\treturn gcd(b, a % b);\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tlet [a, b] = readLine().split(' ').map(Number);\n\t\tif (a > b) {\n\t\t\tconst div = Math.ceil(a / b);\n\t\t\tb = b * div;\n\t\t}\n\t\tconsole.log(Math.ceil(b / a));\n\t}\n}\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n if (n === k || k === 1) console.log(1);\r\n else if (n === 1) console.log(k);\r\n else {\r\n if (n > k) {\r\n if (n % k === 0) k = n;\r\n else k = n + (k - (n % k));\r\n }\r\n let i = Math.floor(k / n);\r\n let j = Math.floor(k / n) + (k % n);\r\n if (j === i) console.log(i);\r\n else console.log(i + 1);\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n})\n\nconst getNumberList = line => line.split(' ').map(val => Number(val))\n\nconst calculate = (n, k) => {\n let index = Math.ceil(n / k)\n\n const b = Math.ceil((k * index) / n)\n\n return b\n}\n\nlet index = -1\nlet maxRound = 0\nlet round = 0\n\nlet n, k\nlet answer = []\n\nreadline.on('line', line => {\n if (index === -1) {\n maxRound = Number(line)\n index = 0\n } else {\n ;[n, k] = getNumberList(line)\n\n answer.push(calculate(n, k))\n\n round++\n if (round === maxRound) {\n readline.close()\n console.log(answer.join('\\n'))\n return\n }\n index++\n }\n})\n// console.log(calculate(6, 5, [1, 2, 3, 3, 2, 1]))\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main() \n});\n\nfunction readline() {\n return inputString[currentLine++]\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\n\nfunction main() {\n let testCases = readline()\n while(testCases--)\n solve()\n}\n\n// function to solve problems\nfunction solve (){\n let line = readline().split(' ')\n let n = line[0]\n let k = line[1]\n // let ans = ''\n // ------------------\n let startingDigit = 0\n let cF = Math.ceil(n/k)\n // startingDigit == 0 ? maxDigit = 1 : maxDigit = startingDigit\n // let arrayCounter = 0\n let total = cF * k\n let maxDigit = Math.ceil(total / n)\n // console.log('total = ', total)\n\n // while (total % k != 0) {\n // total++\n // // console.log('arrayCounter = ', arrayCounter)\n // if (arrayCounter == 0)\n // maxDigit++\n // arrayCounter = (++arrayCounter) % n\n // // console.log('arrayCounter After = ', (arrayCounter) % n)\n // }\n console.log(maxDigit)\n}"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, k] = readline()\r\n .split(\" \")\r\n .map((x) => parseInt(x));\r\n if (k < n) {\r\n k = k * Math.ceil(n / k);\r\n }\r\n let res = Math.ceil(k / n);\r\n console.log(res);\r\n }\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, k] = readline()\r\n .split(\" \")\r\n .map((x) => parseInt(x));\r\n if (k < n) {\r\n k = k * Math.ceil(n / k);\r\n }\r\n let res = Math.ceil(k / n);\r\n console.log(res);\r\n }\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar N = nextInt();\r\n\t\tvar K = nextInt();\r\n\t\tvar sum = Math.ceil(N / K) * K;\r\n\t\tvar L = Math.floor(sum / N);\r\n\t\tvar R = sum % N;\r\n\t\tif(R > 0){\r\n\t\t\tL++;\r\n\t\t}\r\n\t\tmyout(L);\r\n\t}\r\n}"}, {"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n let testCases = parseInt(data.shift());\r\n\r\n while(testCases--) {\r\n\r\n const [n , k] = readLine().split(' ').map(Number);\r\n\r\n console.log(a(n , k));\r\n\r\n }\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n \r\nfunction a(n, k){\r\n /*\r\n You should create an array of n positive integers a1,a2,…,an such that the sum (a1+a2+⋯+an) is divisible by k and maximum element in a is minimum possible.\r\n\r\n What is the minimum possible maximum element in a?\r\n */\r\n return Math.floor((Math.floor((n + k -1)/k)*k + (n - 1))/n);\r\n}\r\n\r\nmodule.exports = a;\r\n"}, {"source_code": " T=+readline();\r\nwhile(T--){\r\n var n,k,ans=0;\r\n var nk =readline().split(' ').map(x=>+x);\r\n n=nk[0];\r\n k=nk[1];\r\n\r\n if(n%k===0){\r\n ans=1;\r\n }\r\n \r\n else if(k%n===0){\r\n ans =k/n;\r\n }\r\n \r\n else if(n>k){\r\n ans =2;\r\n }\r\n \r\n else {\r\n ans = parseInt(k/n)+1;\r\n }\r\n \r\n print(ans);\r\n} \r\n"}, {"source_code": "var t = parseInt(readline());\r\nwhile(t--)\r\n{\r\n\tvar ar = readline().split(' ').map(x => +x);\r\n\tvar n = ar[0];\r\n\tvar k = ar[1];\r\n\tif(n>k)\r\n\t{\r\n\t\tk = n + (k-n%k)%k;\r\n\t}\r\n\tvar ans = k/n;\r\n\tans = Math.ceil(ans);\r\n\tprint(ans);\r\n}"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n var answer = []\r\n\r\n // console.log(Number(x))\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [n, k] = readline().split(' ').map(x => Number(x));\r\n\r\n if (n < k) {\r\n console.log(Math.ceil(k/n))\r\n } else {\r\n console.log(Math.ceil(n/k))\r\n }\r\n // console.log(answer)\r\n // console.log(sum2)\r\n\r\n })\r\n\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n var answer = []\r\n\r\n // console.log(Number(x))\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [n, k] = readline().split(' ').map(x => Number(x));\r\n var odd1 = n % 2\r\n var odd2 = k % 2\r\n if (k === 1) return console.log(1)\r\n if (n === 1) return console.log(k)\r\n if (n > k && odd1 === odd2 || k === 1) return console.log(1)\r\n if (n > k && odd1 !== odd2) return console.log(2)\r\n console.log(Math.floor(k / n) + (k % n === 0 ? 0 : 1))\r\n\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0n) return a\r\n return gcd(b, a % b)\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n var answer = []\r\n\r\n // console.log(Number(x))\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [n, k] = readline().split(' ').map(x => Number(x));\r\n var odd1 = n % 2\r\n var odd2 = k % 2\r\n if(k === 1) return console.log(1)\r\n if(n === 1) return console.log(k)\r\n if(n > k && odd1 === odd2 || k === 1) return console.log(1)\r\n if(n > k && odd1 !== odd2) return console.log(2)\r\n console.log(Math.floor(k/n) +(odd1 === odd2 ? 0 : 1))\r\n\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0n) return a\r\n return gcd(b, a % b)\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n var answer = []\r\n\r\n // console.log(Number(x))\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [n, k] = readline().split(' ').map(x => Number(x));\r\n var odd1 = n % 2\r\n var odd2 = k % 2\r\n if(n > k && odd1 === odd2 || k === 1) return console.log(1)\r\n if(n > k && odd1 !== odd2) return console.log(2)\r\n console.log(Math.floor(k/n) +(odd1 === odd2 ? 0 : 1))\r\n\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0n) return a\r\n return gcd(b, a % b)\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n var answer = []\r\n\r\n // console.log(Number(x))\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [n, k] = readline().split(' ').map(x => Number(x));\r\n var odd1 = n % 2\r\n var odd2 = k % 2\r\n if(n > k && odd1 !== odd2) return console.log(2)\r\n if(n > k && odd1 === odd2) return console.log(1)\r\n console.log(Math.floor(k/n) +(odd1 === odd2 ? 0 : 1))\r\n\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0n) return a\r\n return gcd(b, a % b)\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n var answer = []\r\n\r\n // console.log(Number(x))\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [n, k] = readline().split(' ').map(x => Number(x));\r\n var odd1 = n % 2\r\n var odd2 = k % 2\r\n if(n > k && odd1 !== odd2) return console.log(2)\r\n if(n > k && odd1 === odd2) return console.log(1)\r\n console.log(Math.floor(k/n) +(k % n === 0 ? 0 : 1))\r\n\r\n })\r\n\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b === 0n) return a\r\n return gcd(b, a % b)\r\n}\r\n\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const t = parseInt(readline(), 10);\r\n\r\n for (let i = 0; i < t; i += 1) {\r\n const a = readline().split(' ').map(num => parseInt(num, 10));\r\n const n = a[0];\r\n let k = a[1];\r\n\r\n if (n <= k) {\r\n console.log(Math.ceil(k / n));\r\n } else {\r\n while (k < n) {\r\n k *= 2;\r\n }\r\n\r\n console.log(Math.ceil(k / n));\r\n }\r\n }\r\n}\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', () => {\r\n inputString = inputString.split('\\n').map(str => str.trim());\r\n\r\n main();\r\n});\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const t = parseInt(readline(), 10);\r\n\r\n for (let i = 0; i < t; i += 1) {\r\n const a = readline().split(' ').map(num => parseInt(num, 10));\r\n const n = a[0];\r\n const k = a[1];\r\n\r\n if (n >= k) {\r\n console.log(Math.ceil(n / k));\r\n } else {\r\n console.log(Math.ceil(k / n));\r\n }\r\n }\r\n}\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', () => {\r\n inputString = inputString.split('\\n').map(str => str.trim());\r\n\r\n main();\r\n});\r\n"}, {"source_code": "function solve(n, k) {\n let ans;\n if (k % n === 0) {\n ans = k / n;\n } else {\n let factor = 1;\n while (true) {\n const quotient = Math.floor((n * factor) / k);\n const nextQuotient = Math.floor((factor + 1) * n);\n if (nextQuotient !== quotient) {\n ans = factor + 1;\n break;\n }\n }\n }\n console.log(ans);\n}\n\nlet text = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', t => {\n if (t === '\\r\\n' || t === '\\n') {\n process.stdin.emit('end');\n } else {\n text += t;\n }\n});\nprocess.stdin.on('end', () => {\n const input = text.trim().replace(/\\r/g, '').split('\\n');\n const dataArr = input\n .slice(1)\n .map(item => item.split(' ').map(n => parseInt(n)));\n const len = dataArr.length;\n\n for (let i = 0; i < len; i++) {\n solve(...dataArr[i]);\n }\n process.exit();\n});\n\n\t \t\t\t \t\t \t \t\t \t \t\t\t\t \t\t \t \t"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', (data) => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map((str) => str.trim());\n\tmain();\n});\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n\tfor (var a = arguments, r = a[0], i = a.length; --i; )\n\t\tr = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n\treturn r;\n}\nfunction inv(b) {\n\tfor (var a = MOD, u = 0, v = 1, t; b; v = t)\n\t\t(t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n\tu %= MOD;\n\treturn u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n\tif (n === 0) return 1;\n\tlet p = pow(base, Math.floor(n / 2));\n\tlet res = mul(mod(p), mod(p));\n\tif (n % 2 === 1) res = mul(mod(res), base);\n\treturn res;\n}\nfunction highestOneBit(i) {\n\ti |= i >> 1;\n\ti |= i >> 2;\n\ti |= i >> 4;\n\ti |= i >> 8;\n\ti |= i >> 16;\n\treturn i - (i >>> 1);\n}\nfunction permutation(arr, len, store = '', permutations = []) {\n\tif (store.length === len) {\n\t\tpermutations.push(store);\n\t\treturn;\n\t}\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tconst newArr = [...arr];\n\t\tconst newChar = newArr.splice(i, 1);\n\t\tpermutation(newArr, len, store.concat(newChar), permutations);\n\t}\n\treturn permutations;\n}\nfunction gcd(a, b) {\n\tif (b === 0) return a;\n\treturn gcd(b, a % b);\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tlet [a, b] = readLine().split(' ').map(Number);\n\t\tif (a > b) {\n\t\t\tconst div = Math.ceil(a / b);\n\t\t\tconsole.log(div);\n\t\t} else {\n\t\t\tconsole.log(`${Math.floor(b / a) + (b % a)}`);\n\t\t}\n\t}\n}\n"}, {"source_code": "let inputString = '';\nlet currentLine = 0;\nprocess.stdin.on('data', (data) => {\n\tinputString += data;\n});\nprocess.stdin.on('end', function () {\n\tinputString = inputString\n\t\t.trim()\n\t\t.split('\\n')\n\t\t.map((str) => str.trim());\n\tmain();\n});\nfunction readLine() {\n\treturn inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n\tfor (var a = arguments, r = a[0], i = a.length; --i; )\n\t\tr = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n\treturn r;\n}\nfunction inv(b) {\n\tfor (var a = MOD, u = 0, v = 1, t; b; v = t)\n\t\t(t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n\tu %= MOD;\n\treturn u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n\tif (n === 0) return 1;\n\tlet p = pow(base, Math.floor(n / 2));\n\tlet res = mul(mod(p), mod(p));\n\tif (n % 2 === 1) res = mul(mod(res), base);\n\treturn res;\n}\nfunction highestOneBit(i) {\n\ti |= i >> 1;\n\ti |= i >> 2;\n\ti |= i >> 4;\n\ti |= i >> 8;\n\ti |= i >> 16;\n\treturn i - (i >>> 1);\n}\nfunction permutation(arr, len, store = '', permutations = []) {\n\tif (store.length === len) {\n\t\tpermutations.push(store);\n\t\treturn;\n\t}\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tconst newArr = [...arr];\n\t\tconst newChar = newArr.splice(i, 1);\n\t\tpermutation(newArr, len, store.concat(newChar), permutations);\n\t}\n\treturn permutations;\n}\nfunction gcd(a, b) {\n\tif (b === 0) return a;\n\treturn gcd(b, a % b);\n}\n\nfunction main() {\n\tlet t = +readLine();\n\twhile (t--) {\n\t\tconst [a, b] = readLine().split(' ').map(Number);\n\t\tconst min = Math.min(a, b);\n\t\tconst max = Math.max(a, b);\n\t\tconsole.log(`${Math.floor(max / min) + (max % min)}`);\n\t}\n}\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n if (n === k || k === 1) console.log(1);\r\n else if (n === 1) console.log(k);\r\n else {\r\n if (n > k) k = n + (k - (n % k));\r\n let i = Math.floor(k / n);\r\n let j = Math.floor(k / n) + (k % n);\r\n if (j === i) console.log(i);\r\n else console.log(i + 1);\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": " T=+readline();\r\nwhile(T--){\r\n var n,k,ans=0;\r\n var nk =readline().split(' ').map(x=>+x);\r\n n=nk[0];\r\n k=nk[1];\r\n\r\n if(n%k===0){\r\n ans=1;\r\n }\r\n \r\n else if(k%n===0){\r\n ans =k/n;\r\n }\r\n \r\n else if(n>k){\r\n ans =parseInt(n/k)+1 ;\r\n }\r\n \r\n else {\r\n ans = parseInt(k/n)+1;\r\n }\r\n \r\n print(ans);\r\n} \r\n"}], "src_uid": "a28b84c9d1a54e322ab2d54bd5ab45c8"} {"nl": {"description": "This problem is actually a subproblem of problem G from the same contest.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \\le a_i \\le n$$$).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer $$$q$$$ independent queries.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$$$) — the number of queries. Each query is represented by two lines. The first line of each query contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the number of candies. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy in the box. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.", "sample_inputs": ["3\n8\n1 4 8 4 5 6 3 8\n16\n2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1\n9\n2 2 4 4 4 7 7 7 7"], "sample_outputs": ["3\n10\n9"], "notes": "NoteIn the first query, you can prepare a gift with two candies of type $$$8$$$ and one candy of type $$$5$$$, totalling to $$$3$$$ candies.Note that this is not the only possible solution — taking two candies of type $$$4$$$ and one candy of type $$$6$$$ is also valid."}, "positive_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var q = read.number();\n var res = '';\n while (q) {\n q--;\n\n var n = read.number();\n var a = read.arrNumber(' ');\n var t = {};\n a.forEach(i => {\n if(t[i]) {\n t[i]++;\n }\n else {\n t[i] = 1;\n }\n });\n\n var unic = {};\n for(var type in t) {\n if(unic[t[type]]) {\n unic[t[type]]++;\n }\n else {\n unic[t[type]] = 1;\n }\n }\n\n var f = Object.keys(unic).sort((a,b) => b - a);\n\n var count = 0;\n var max = +f[0];\n\n f.forEach(key => {\n if(max === 0) {\n return;\n }\n if(max > key) {\n max = +key;\n }\n while(unic[key]) {\n if(max === 0) {\n break;\n }\n unic[key]--;\n count += max;\n max--;\n }\n });\n res += count + '\\n';\n }\n print(res);\n}());\n"}, {"source_code": "var interationsCount = parseInt(readline());\nfor (var i = 0; i < interationsCount; i++) {\n readline();\n var candies = readline().split(\" \").map(x => parseInt(x));\n\n var groupedCandies = groupByCount(candies);\n\n var numberOfCandies = 0;\n var maxCandies = groupedCandies[0][1];\n for (j = 0; j < groupedCandies.length - 1; j++) {\n if (maxCandies <= 0) {\n break;\n }\n\n numberOfCandies += maxCandies;\n maxCandies = Math.min(maxCandies - 1, groupedCandies[j + 1][1]);\n }\n \n numberOfCandies += maxCandies;\n\n print(numberOfCandies);\n}\n\nfunction groupByCount(candies) {\n var map = new Map();\n for (var j = 0; j < candies.length; j++) {\n var currentTypeCount = map.get(candies[j]);\n if (!currentTypeCount) {\n map.set(candies[j], 1);\n } else {\n map.set(candies[j], currentTypeCount + 1)\n }\n }\n\n return Array.from(map).sort((a, b) => {\n return b[1] - a[1];\n });\n}"}, {"source_code": "\"use strict\";\n\nvar q = +readline()\n\nwhile (q--) {\n var n = +readline();\n var A = readline().split(' ').map(value => +value);\n var M = {};\n\n for (var i = 0; i < A.length; ++i) {\n var value = A[i];\n M[value] = (M[value] || 0) + 1;\n }\n\n var R = {};\n for (var key in M) {\n if (M.hasOwnProperty(key)) {\n var value = M[key];\n R[value] = (R[value] || 0) + 1;\n }\n }\n \n var L = Object.keys(R).map(value => +value).sort(function(a, b){return b - a});\n var result = 0;\n var lastMax = L[0];\n loop:for (var i = 0; i < L.length; ++i) {\n if (lastMax > L[i]) {\n lastMax = L[i];\n }\n var count = +R[L[i]];\n\n while (count--) {\n result += lastMax;\n lastMax--;\n if (lastMax === 0) {\n break loop;\n }\n }\n }\n \n write(result, '\\n');\n}"}], "negative_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var q = read.number();\n var res = '';\n while (q) {\n q--;\n\n var n = read.number();\n var a = read.arrNumber(' ');\n var t = {};\n a.forEach(i => {\n if(t[i]) {\n t[i]++;\n }\n else {\n t[i] = 1;\n }\n });\n\n var unic = {};\n for(var type in t) {\n if(unic[t[type]]) {\n unic[t[type]]++;\n }\n else {\n unic[t[type]] = 1;\n }\n }\n\n var f = Object.keys(unic).sort((a,b) => b - a);\n\n var count = 0;\n var max = +f[0];\n\n f.forEach(key => {\n if(max === 0) {\n return;\n }\n if(max > key) {\n max = +key;\n }\n while(unic[key]) {\n unic[key]--;\n count += max;\n max--;\n }\n });\n\n res += count + '\\n';\n\n }\n print(res);\n\n}());\n"}, {"source_code": "\nvar interationsCount = parseInt(readline());\nfor (var i = 0; i < interationsCount; i++) {\n var candiesCount = parseInt(readline());\n var candies = readline().split(\" \").map(x => parseInt(x));\n\n var groupedCandies = groupByCount(candies);\n var maxNumberOfTypesInPresent = Math.min(groupedCandies.length, groupedCandies[0][1]);\n\n var numberOfCandies = 0;\n var previousNumber = -1;\n for (j = 0; j < maxNumberOfTypesInPresent; j++) {\n var currentTypeCandiesMax = groupedCandies[j][1];\n numberOfCandies += groupedCandies[j][1];\n\n if (previousNumber != -1) {\n if (previousNumber === currentTypeCandiesMax) {\n numberOfCandies -= j;\n } \n }\n\n previousNumber = currentTypeCandiesMax;\n }\n\n print(numberOfCandies);\n}\n\nfunction groupByCount(candies) {\n var map = new Map();\n for (var j = 0; j < candies.length; j++) {\n var currentTypeCount = map.get(candies[j]);\n if (!currentTypeCount) {\n map.set(candies[j], 1);\n } else {\n map.set(candies[j], currentTypeCount + 1)\n } \n }\n\n return Array.from(map).sort((a, b) => {\n return b[1] - a[1];\n });\n}"}, {"source_code": "var interationsCount = parseInt(readline());\nfor (var i = 0; i < interationsCount; i++) {\n var candiesCount = parseInt(readline());\n var candies = readline().split(\" \").map(x => parseInt(x));\n\n var groupedCandies = groupByCount(candies);\n var maxNumberOfTypesInPresent = Math.min(groupedCandies.length, groupedCandies[0][1]);\n\n var numberOfCandies = 0;\n var maxCandies = groupedCandies[0][1];\n for (j = 0; j < maxNumberOfTypesInPresent - 1; j++) {\n numberOfCandies += maxCandies;\n maxCandies = Math.min(maxCandies - 1, groupedCandies[j+1][1]);\n }\n numberOfCandies += maxCandies;\n\n print(numberOfCandies);\n}\n\nfunction groupByCount(candies) {\n var map = new Map();\n for (var j = 0; j < candies.length; j++) {\n var currentTypeCount = map.get(candies[j]);\n if (!currentTypeCount) {\n map.set(candies[j], 1);\n } else {\n map.set(candies[j], currentTypeCount + 1)\n } \n }\n\n return Array.from(map).sort((a, b) => {\n return b[1] - a[1];\n });\n}"}], "src_uid": "a00d831da539c69d571d9720fd94eee1"} {"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$$$) — 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$$$) — column in which $$$i$$$-th square will appear.", "output_spec": "Print one integer — 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": "var isNodeJS = false;\n// isNodeJS = !isNodeJS;\nvar doWork = (readline, print) => {\nvar readInts = () => {\n return readline().split(\" \").map(function(x) { return parseInt(x); });\n};\n/////////////////////////////////////////////////////////////// BEGIN\n\nvar nums = readInts();\nvar n = nums[0];\nvar m = nums[1];\n\nvar a = readInts();\nvar b = new Array(n).fill(0);\nvar result = 0;\na.forEach(c => {\n --c;\n b[c]++;\n var allFilled = true;\n b.forEach(v => {\n if (v == 0) allFilled = false;\n });\n if (allFilled) {\n ++result;\n for (var i = 0; i < n; ++i) {\n b[i]--;\n }\n }\n});\n\nprint(result + \"\\n\");\n\n/////////////////////////////////////////////////////////////// END OF CODE\n};\n\nif (isNodeJS) {\n var stdin = process.stdin;\n var stdout = process.stdout;\n var lines, currentLine = 0;\n stdin.resume();\n stdin.once('data', function(data) {\n data = data.toString().trim();\n lines = data.split(\"\\n\");\n var readline = () => {\n return lines[currentLine++];\n };\n doWork(readline, stdout.write.bind(stdout));\n });\n} else {\n doWork(readline, print);\n}\n"}, {"source_code": "// You are given a following process.\n\n// There is a platform with n columns. 1 × 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.\n\n// 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.\n\n// You task is to calculate the amount of points you will receive.\n// Input\n\n// The first line of input contain 2 integer numbers n and m (1 ≤ n, m ≤ 1000) — the length of the platform and the number of the squares.\n\n// The next line contain m integer numbers c1, c2, ..., cm (1 ≤ ci ≤ n) — column in which i-th square will appear.\n// Output\n\n// Print one integer — the amount of points you will receive.\n\n\nvar input1 = readline();\nvar input2 = readline();\n\ninput1Arr = input1.split(' ');\nsquareArray = input2.split(' ');\n\nvar nColumn = input1Arr[0];\nvar totalSquare = squareArray[1];\n\nvar countN = [];\nvar count = 0;\n\nfor (var i = 1; i <= nColumn; i++) {\n count = 0;\n for (var j = 0; j < squareArray.length; j++) {\n if (squareArray[j] == i) {\n count += 1;\n }\n }\n countN.push(count);\n}\n\nvar min = countN.reduce(function(current, acc) {\n return ( current < acc ? current : acc);\n});\n\nprint(min);"}, {"source_code": "function main() {\n var n = Number(readline().split(' ')[0]);\n var squares = readline()\n .split(' ')\n .map(l => Number(l));\n var stacked = new Array(n).fill(0);\n\n for (var i = 0; i < squares.length; i++) {\n stacked[squares[i] - 1] += 1;\n }\n\n print(Math.min(...stacked));\n}\n\nmain();\n"}, {"source_code": "var g = readline().split(\" \");\nvar k = readline().split(\" \");\nvar min = 0;\nvar arr = [];\nfor(i=1;i<=Number(g[0]);i++){\n arr[i] = 0;\n}\n\nfor(i=0;i arr[b])\n min = arr[b];\n }\n}\nprint(min);"}, {"source_code": "\nlet _inputLines;\nlet _lineNumber = 0;\nlet inputReader = _inputReader ();\n\nfunction _main() {\n\t\n\t_inputLines = _inputData.trim().split('\\n').map((string) => {\n\t\treturn string.trim();\n\t});;\n\tlet[a,b] = inputReader.readNumberArray();\n\tlet count = 0,x1=0,x2=0,x3=0;\n\tlet arr = inputReader.readNumberArray();\n\tlet res= [];\n\tfor(let i =0;i Number(val));\n\t}\n\t\t\n\t\n\treturn {\n\t\treadNumberArray,\n\t}\n}"}], "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 ≤ m ≤ n ≤ 1000, 0 ≤ k ≤ 106) — 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 ≤ r ≤ m) — index of the row, where belongs the corresponding tooth, and c (0 ≤ c ≤ 106) — 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": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nlet N = lll[0]\nlet M = lll[1]\nlet K = lll[2]\n\nlet c = 0\nlet rs = []\n\nwhile (lll = readline()) {\n lll = lll.split(' ').map(v => parseInt(v))\n let r = lll[0]\n let l = lll[1]\n if (!rs[r]) rs[r] = []\n rs[r].push(l)\n}\n\nfor (let i = 1; i < rs.length; i++) {\n c += rs[i].reduce((r, v) => Math.min(r, v), Infinity)\n}\n\n\nprint(Math.min(c, K))"}, {"source_code": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nvar n,m,k,indicator=0,temp=[],dict={};\nrl.on('line', (input) => {\n if (indicator==0){\n temp = input.split(' ').map(item=>parseInt(item));// \"5 7 8\" => |\"5\"|\"7\"|\"8\"| => |5|7|8|\n n = temp[0], m = temp[1], k = temp[2]; \n indicator++; \n } else {\n temp = input.split(' ').map(item=>parseInt(item));\n let row=temp[0], viability = temp[1];\n if(row in dict && dict[row]>viability || !(row in dict))\n dict[row]=viability; \n } \n }).on('close',function(){\n let _sum = Object.values(dict).reduce((x,y)=>{\n return x+y;\n });\n console.log(_sum>k ? k : _sum);\n });"}], "negative_code": [], "src_uid": "65eb0f3ab35c4d95c1cbd39fc7a4227b"} {"nl": {"description": "Fishingprince is playing with an array $$$[a_1,a_2,\\dots,a_n]$$$. He also has a magic number $$$m$$$.He can do the following two operations on it: Select $$$1\\le i\\le n$$$ such that $$$a_i$$$ is divisible by $$$m$$$ (that is, there exists an integer $$$t$$$ such that $$$m \\cdot t = a_i$$$). Replace $$$a_i$$$ with $$$m$$$ copies of $$$\\frac{a_i}{m}$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[2,3]$$$ and $$$i=1$$$, $$$a$$$ changes into $$$[1,1,3]$$$. Select $$$1\\le i\\le n-m+1$$$ such that $$$a_i=a_{i+1}=\\dots=a_{i+m-1}$$$. Replace these $$$m$$$ elements with a single $$$m \\cdot a_i$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[3,2,2,3]$$$ and $$$i=2$$$, $$$a$$$ changes into $$$[3,4,3]$$$. Note that the array length might change during the process. The value of $$$n$$$ above is defined as the current length of the array (might differ from the $$$n$$$ in the input).Fishingprince has another array $$$[b_1,b_2,\\dots,b_k]$$$. Please determine if he can turn $$$a$$$ into $$$b$$$ using any number (possibly zero) of operations.", "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 $$$m$$$ ($$$1\\le n\\le 5\\cdot 10^4$$$, $$$2\\le m\\le 10^9$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1\\le a_i\\le 10^9$$$). The third line of each test case contains one integer $$$k$$$ ($$$1\\le k\\le 5\\cdot 10^4$$$). The fourth line of each test case contains $$$k$$$ integers $$$b_1,b_2,\\ldots,b_k$$$ ($$$1\\le b_i\\le 10^9$$$). It is guaranteed that the sum of $$$n+k$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each testcase, print Yes if it is possible to turn $$$a$$$ into $$$b$$$, and No otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["5\n\n5 2\n\n1 2 2 4 2\n\n4\n\n1 4 4 2\n\n6 2\n\n1 2 2 8 2 2\n\n2\n\n1 16\n\n8 3\n\n3 3 3 3 3 3 3 3\n\n4\n\n6 6 6 6\n\n8 3\n\n3 9 6 3 12 12 36 12\n\n16\n\n9 3 2 2 2 3 4 12 4 12 4 12 4 12 4 4\n\n8 3\n\n3 9 6 3 12 12 36 12\n\n7\n\n12 2 4 3 4 12 56"], "sample_outputs": ["Yes\nYes\nNo\nYes\nNo"], "notes": "NoteIn the first test case of the sample, we can do the second operation with $$$i=2$$$: $$$[1,\\color{red}{2,2},4,2]\\to [1,\\color{red}{4},4,2]$$$.In the second testcase of the sample, we can: do the second operation with $$$i=2$$$: $$$[1,\\color{red}{2,2},8,2,2]\\to [1,\\color{red}{4},8,2,2]$$$. do the second operation with $$$i=4$$$: $$$[1,4,8,\\color{red}{2,2}]\\to [1,4,8,\\color{red}{4}]$$$. do the first operation with $$$i=3$$$: $$$[1,4,\\color{red}{8},4]\\to [1,4,\\color{red}{4,4},4]$$$. do the second operation with $$$i=2$$$: $$$[1,\\color{red}{4,4},4,4]\\to [1,\\color{red}{8},4,4]$$$. do the second operation with $$$i=3$$$: $$$[1,8,\\color{red}{4,4}]\\to [1,8,\\color{red}{8}]$$$. do the second operation with $$$i=2$$$: $$$[1,\\color{red}{8,8}]\\to [1,\\color{red}{16}]$$$."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, k, a, b) {\r\n const s1 = a.reduce((a, b) => a + b, 0),\r\n s2 = b.reduce((a, b) => a + b, 0);\r\n if (s1 !== s2) return 'NO';\r\n const sa = [],\r\n sb = [];\r\n for (let i = 0, j = 0; (i < n || sa.length) && (j < k || sb.length);) {\r\n if (i < n && !sa.length) sa.push([a[i++], 1]);\r\n if (j < k && !sb.length) sb.push([b[j++], 1]);\r\n while (sa.length && sb.length) {\r\n const la = sa[sa.length - 1],\r\n lb = sb[sb.length - 1];\r\n if (la[0] === lb[0]) {\r\n const min = Math.min(la[1], lb[1]);\r\n la[1] -= min;\r\n lb[1] -= min;\r\n if (!la[1]) sa.pop();\r\n if (!lb[1]) sb.pop();\r\n } else if (la[0] > lb[0]) {\r\n if (la[0] % m !== 0) return 'NO';\r\n la[0] /= m;\r\n la[1] *= m;\r\n } else {\r\n if (lb[0] % m !== 0) return 'NO';\r\n lb[0] /= m;\r\n lb[1] *= m;\r\n }\r\n }\r\n }\r\n if (sa.length || sb.length) return 'NO';\r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const k = Number(await read());\r\n const b = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, m, k, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, k, a, b) {\r\n const s1 = a.reduce((a, b) => a + b, 0),\r\n s2 = b.reduce((a, b) => a + b, 0);\r\n if (s1 !== s2) return 'NO';\r\n const sa = [],\r\n sb = [];\r\n for (let i = 0, j = 0; i < n && j < k;) {\r\n if (!sa.length) sa.push([a[i++], 1]);\r\n if (!sb.length) sb.push([b[j++], 1]);\r\n while (sa.length && sb.length) {\r\n const la = sa[sa.length - 1],\r\n lb = sb[sb.length - 1];\r\n if (la[0] === lb[0]) {\r\n const min = Math.min(la[1], lb[1]);\r\n la[1] -= min;\r\n lb[1] -= min;\r\n if (!la[1]) sa.pop();\r\n if (!lb[1]) sb.pop();\r\n } else if (la[0] > lb[0]) {\r\n if (la[0] % m !== 0) return 'NO';\r\n la[0] /= m;\r\n la[1] *= m;\r\n } else {\r\n if (lb[0] % m !== 0) return 'NO';\r\n lb[0] /= m;\r\n lb[1] *= m;\r\n }\r\n }\r\n }\r\n return 'YES';\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n const k = Number(await read());\r\n const b = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, m, k, a, b);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "src_uid": "2ff40423619cefd8c2fb35a18549c411"} {"nl": {"description": "You are given a number $$$n$$$ and an array $$$b_1, b_2, \\ldots, b_{n+2}$$$, obtained according to the following algorithm: some array $$$a_1, a_2, \\ldots, a_n$$$ was guessed; array $$$a$$$ was written to array $$$b$$$, i.e. $$$b_i = a_i$$$ ($$$1 \\le i \\le n$$$); The $$$(n+1)$$$-th element of the array $$$b$$$ is the sum of the numbers in the array $$$a$$$, i.e. $$$b_{n+1} = a_1+a_2+\\ldots+a_n$$$; The $$$(n+2)$$$-th element of the array $$$b$$$ was written some number $$$x$$$ ($$$1 \\le x \\le 10^9$$$), i.e. $$$b_{n+2} = x$$$; The array $$$b$$$ was shuffled. For example, the array $$$b=[2, 3, 7, 12 ,2]$$$ it could be obtained in the following ways: $$$a=[2, 2, 3]$$$ and $$$x=12$$$; $$$a=[3, 2, 7]$$$ and $$$x=2$$$. For the given array $$$b$$$, find any array $$$a$$$ that could have been guessed initially.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$). The second row of each test case contains $$$n+2$$$ integers $$$b_1, b_2, \\ldots, b_{n+2}$$$ ($$$1 \\le b_i \\le 10^9$$$). 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: \"-1\", if the array $$$b$$$ could not be obtained from any array $$$a$$$; $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$, otherwise. If there are several arrays of $$$a$$$, you can output any.", "sample_inputs": ["4\n3\n2 3 7 12 2\n4\n9 1 7 1 6 5\n5\n18 2 2 3 2 9 2\n3\n2 6 9 2 1"], "sample_outputs": ["2 3 7 \n-1\n2 2 2 3 9 \n1 2 6"], "notes": null}, "positive_code": [{"source_code": "var num = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\r\n\r\nvar n = num[0];\r\nfor (var index = 0; index < n; index++) {\r\n var m = readline().split(\" \").map((x) => parseInt(x));\r\n var numbers = readline().split(\" \").map((x) => parseInt(x));\r\n\r\n\r\n // for (var j = 1; j < numbers.length; j++) {\r\n // if (max < numbers[j]) {\r\n // max = numbers[j];\r\n // }\r\n // }\r\n numbers.sort((a, b) => a - b);\r\n var max = numbers[numbers.length - 1];\r\n // write(max + ' max \\n'); \r\n for (var j = 0; j < numbers.length - 1; j++) {\r\n max -= numbers[j]; \r\n // write(max + ' max \\n'); \r\n }\r\n\r\n var result = [];\r\n\r\n var finded = max * -1;\r\n var findedIndex = numbers.indexOf(finded);\r\n if (findedIndex != -1 && findedIndex != numbers.length - 1) {\r\n // write(findedIndex + ' findedIndex \\n'); \r\n numbers.splice(findedIndex, 1);\r\n numbers.splice(-1, 1);\r\n result = numbers;\r\n } else {\r\n max = numbers[numbers.length - 2];\r\n for (var j = 0; j < numbers.length - 2; j++) {\r\n // write(max + ' max \\n');\r\n max -= numbers[j]; \r\n }\r\n if (max == 0) {\r\n numbers.splice(-2, 2);\r\n result = numbers; \r\n } else {\r\n result = [-1];\r\n }\r\n\r\n }\r\n\r\n write(result.join(' ') + '\\n'); \r\n \r\n}\r\n"}, {"source_code": "var t = parseInt(readline());\r\n\r\nfor (var test = 0; test < t; test++) {\r\n var n = parseInt(readline());\r\n var arr = readline().split(' ');\r\n var ans = [];\r\n\r\n var iMax1 = parseInt(arr[0]) >= parseInt(arr[1]) ? 0 : 1;\r\n var iMax2 = parseInt(arr[0]) >= parseInt(arr[1]) ? 1 : 0;\r\n\r\n for (var i = 2; i < n + 2; i++) {\r\n if (parseInt(arr[i]) > parseInt(arr[iMax1])) {\r\n iMax2 = iMax1;\r\n iMax1 = i;\r\n } else if (parseInt(arr[i]) > parseInt(arr[iMax2])) {\r\n iMax2 = i;\r\n }\r\n }\r\n\r\n var arrSum = arr.reduce((sum, item) => sum += parseInt(item), 0);\r\n\r\n var testMax = iMax => {\r\n for (var i = 0; i < n + 2; i++) {\r\n if (i !== iMax && arrSum - arr[i] - arr[iMax] === parseInt(arr[iMax])) {\r\n for (var j = 0; j < n + 2; j ++) {\r\n if (j !== i && j !== iMax) {\r\n ans.push(arr[j]);\r\n }\r\n }\r\n print(ans.join(' '));\r\n return true;\r\n }\r\n }\r\n }\r\n\r\n if (!testMax(iMax1)) {\r\n if (!testMax(iMax2)) {\r\n print('-1');\r\n }\r\n }\r\n}"}, {"source_code": "function solution(n,array) {\r\n var pointer = 0;\r\n var result = null;\r\n var noResult = false;\r\n var sortedArray = array.sort((a, b) => a - b);\r\n\r\n const firstTotal = [...sortedArray]\r\n .slice(0, n)\r\n .reduce((total, currentValue) => total + currentValue);\r\n \r\n if (firstTotal === sortedArray[n] || firstTotal === sortedArray[n + 1]) {\r\n return [...sortedArray].slice(0, n).join(' ');\r\n } else if (firstTotal > sortedArray[n] && firstTotal > sortedArray[n + 1]) {\r\n return -1;\r\n } else {\r\n const secondTotal = firstTotal + sortedArray[n];\r\n var i=0;\r\n \r\n while(i <= n-1 && ((secondTotal - sortedArray[i]) !== sortedArray[n + 1])){\r\n i++;\r\n }\r\n \r\n if(i===n){\r\n return -1;\r\n }\r\n return [...sortedArray].slice(0, n+1).filter((item,index)=> index !== i).join(' ');\r\n }\r\n}\r\n\r\n\r\n\r\n\r\nvar iteration = parseInt(readline());\r\nfor(var i=0; i parseInt(x))\r\n )\r\n );\r\n}"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet n = rn();\r\n\t\tlet b = rna();\r\n\r\n\t\tlet have = new Map();\r\n\t\tlet sm = 0;\r\n\t\tfor (x of b) {\r\n\t\t\tsm += x;\r\n\t\t\thave.set(x, 1 + (have.has(x) ? have.get(x) : 0));\r\n\t\t}\r\n\r\n\t\tlet ans;\r\n\t\tfor (let i = 0; !ans && i < n + 2; i++) {\r\n\t\t\tconst x = sm - 2 * b[i];\r\n\t\t\tif (have.has(x)) {\r\n\t\t\t\tif (x == b[i] && have.get(x) < 2)\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tans = b.slice();\r\n\t\t\t\tans.splice(ans.indexOf(b[i]), 1);\r\n\t\t\t\tans.splice(ans.indexOf(x), 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nvar maxN = 21\r\nvar mod = 1000000007\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n const xx = readline();\r\n\r\n Array(Number(xx)).fill(1).map((t, i) => {\r\n var n = parseInt(readline());\r\n // var [x, y] = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return BigInt(x)\r\n })\r\n n = n + 2\r\n var sum = 0n\r\n var object = {}\r\n for (let j = 0; j < n; j++) {\r\n sum += a[j]\r\n if (!object[a[j]]) object[a[j]] = 0\r\n object[a[j]]++\r\n }\r\n var ans = []\r\n var minus1 = false\r\n var minus2 = false\r\n for (let j = 0; j < n; j++) {\r\n var number = sum - a[j]\r\n if (number / 2n === a[j] && object[number / 2n] === 1) continue\r\n if (number % 2n === 0n && object[number / 2n]) {\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] === a[j] && !minus1) {\r\n minus1 = true\r\n continue\r\n }\r\n if (a[i] === number / 2n && !minus2) {\r\n minus2 = true\r\n continue\r\n }\r\n ans.push(a[i])\r\n }\r\n console.log(ans.join(' '))\r\n return\r\n }\r\n }\r\n console.log(-1)\r\n\r\n })\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = BigInt(1e9 + 7);\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let arr = iInpArr();\r\n arr.sort((a, b) => a - b);\r\n let narr = [],\r\n sum = 0;\r\n for (let i = 0; i < n; i++) {\r\n narr.push(arr[i]);\r\n sum += arr[i];\r\n }\r\n if (sum === arr[n] || sum === arr[n + 1]) console.log(narr.join(\" \"));\r\n else {\r\n let flag = true,\r\n s1 = sum;\r\n for (let i = n - 1; i >= 0; i--) {\r\n s1 = sum + arr[n];\r\n s1 -= narr[i];\r\n if (s1 === arr[n + 1]) {\r\n narr[i] = arr[n];\r\n console.log(narr.join(\" \"));\r\n flag = false;\r\n break;\r\n }\r\n }\r\n if (flag) console.log(-1);\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet pos = 0;\r\nconst words = [];\r\nrl.on('line', (line) => {\r\n words.push.apply(words, line.split(' ').filter(s => s != ''));\r\n});\r\nrl.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(words[pos++]));\r\n}\r\nfunction nextStr() {\r\n return words[pos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nlet n;\r\nlet b;\r\nfunction solve() {\r\n b.sort((x, y) => x - y);\r\n let mx = b[b.length - 1];\r\n let sum = 0;\r\n for (let i = 0; i < b.length; i++) {\r\n sum += b[i];\r\n }\r\n for (let i = 0; i + 1 < b.length; i++) {\r\n const rem = sum - b[i];\r\n if (rem % 2 != 0) {\r\n continue;\r\n }\r\n if (mx * 2 == rem) {\r\n const t = b[b.length - 2];\r\n b[b.length - 2] = b[i];\r\n b[i] = t;\r\n return true;\r\n }\r\n }\r\n let x = b[b.length - 1];\r\n mx = b[b.length - 2];\r\n if (mx * 2 + x == sum) {\r\n return true;\r\n }\r\n return false;\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc-- > 0) {\r\n n = nextInt();\r\n b = af(n + 2);\r\n for (let i = 0; i < n + 2; i++) {\r\n b[i] = nextInt();\r\n }\r\n if (solve()) {\r\n for (let i = 0; i < n; i++) {\r\n printf(\"%d \", b[i]);\r\n }\r\n printf(\"\\n\");\r\n }\r\n else {\r\n printf(\"%d\\n\", INIT);\r\n }\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "var num = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\r\n\r\nvar n = num[0];\r\nfor (var index = 0; index < n; index++) {\r\n var m = readline().split(\" \").map((x) => parseInt(x));\r\n var numbers = readline().split(\" \").map((x) => parseInt(x));\r\n\r\n\r\n // for (var j = 1; j < numbers.length; j++) {\r\n // if (max < numbers[j]) {\r\n // max = numbers[j];\r\n // }\r\n // }\r\n numbers.sort((a, b) => a - b);\r\n var max = numbers[numbers.length - 1];\r\n // write(max + ' max \\n'); \r\n for (var j = 0; j < numbers.length - 1; j++) {\r\n max -= numbers[j]; \r\n // write(max + ' max \\n'); \r\n }\r\n\r\n var result = [];\r\n\r\n var finded = max * -1;\r\n var findedIndex = numbers.indexOf(finded);\r\n if (findedIndex != -1 && findedIndex != numbers.length - 1) {\r\n // write(findedIndex + ' findedIndex \\n'); \r\n numbers.splice(findedIndex, 1);\r\n numbers.splice(-1, 1);\r\n result = numbers;\r\n } else {\r\n max = numbers[numbers.length - 2];\r\n for (var j = 0; j < numbers.length - 1; j++) {\r\n // write(max + ' max \\n');\r\n max -= numbers[j]; \r\n }\r\n if (max == 0) {\r\n numbers.splice(-2, 2);\r\n result = numbers; \r\n } else {\r\n result = [-1];\r\n }\r\n\r\n }\r\n\r\n write(result.join(' ') + '\\n'); \r\n \r\n}\r\n"}, {"source_code": "var num = readline().split(\" \").map(x => parseInt(x)); // num will be an array [1,2,3]\r\n\r\nvar n = num[0];\r\nfor (var index = 0; index < n; index++) {\r\n var m = readline().split(\" \").map((x) => parseInt(x));\r\n var numbers = readline().split(\" \").map((x) => parseInt(x));\r\n\r\n\r\n // for (var j = 1; j < numbers.length; j++) {\r\n // if (max < numbers[j]) {\r\n // max = numbers[j];\r\n // }\r\n // }\r\n numbers.sort((a, b) => a - b);\r\n var max = numbers[numbers.length - 1];\r\n // write(max + ' max \\n'); \r\n for (var j = 0; j < numbers.length - 1; j++) {\r\n max -= numbers[j]; \r\n // write(max + ' max \\n'); \r\n }\r\n\r\n var result = [];\r\n\r\n var finded = max * -1;\r\n var findedIndex = numbers.indexOf(finded);\r\n if (findedIndex != -1) {\r\n // write(findedIndex + ' findedIndex \\n'); \r\n numbers.splice(findedIndex, 1);\r\n numbers.splice(-1, 1);\r\n result = numbers;\r\n } else {\r\n max = numbers[numbers.length - 2];\r\n for (var j = 0; j < numbers.length - 1; j++) {\r\n max -= numbers[j]; \r\n }\r\n if (max == 0) {\r\n numbers.splice(-2, 2);\r\n result = numbers; \r\n } else {\r\n result = [-1];\r\n }\r\n\r\n }\r\n\r\n write(result.join(' ') + '\\n'); \r\n \r\n}\r\n"}, {"source_code": "var t = parseInt(readline());\r\n\r\nfor (var test = 0; test < t; test++) {\r\n var n = parseInt(readline());\r\n var arr = readline().split(' ');\r\n\r\n var iMax1 = parseInt(arr[0]) >= parseInt(arr[1]) ? 0 : 1;\r\n var iMax2 = parseInt(arr[0]) >= parseInt(arr[1]) ? 1 : 0;\r\n\r\n for (var i = 2; i < n + 2; i++) {\r\n if (parseInt(arr[i]) > parseInt(arr[iMax1])) {\r\n iMax2 = iMax1;\r\n iMax1 = i;\r\n } else if (parseInt(arr[i]) > parseInt(arr[iMax2])) {\r\n iMax2 = i;\r\n }\r\n }\r\n\r\n var arrSum = arr.reduce((sum, item) => sum += parseInt(item), 0);\r\n\r\n var testMax = iMax => {\r\n for (var i = 0; i < n + 2; i++) {\r\n if (i !== iMax && arrSum - arr[i] - arr[iMax] === parseInt(arr[iMax])) {\r\n arr.splice(i, 1);\r\n arr.splice(iMax, 1);\r\n print(arr.join(' '));\r\n return true;\r\n }\r\n }\r\n }\r\n\r\n if (!testMax(iMax1)) {\r\n if (!testMax(iMax2)) {\r\n print('-1');\r\n }\r\n }\r\n}"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet n = rn();\r\n\t\tlet b = rna();\r\n\r\n\t\tlet have = new Map();\r\n\t\tlet sm = 0;\r\n\t\tfor (x of b) {\r\n\t\t\tsm += x;\r\n\t\t\thave.set(x, 1 + (have.has(x) ? have.get(x) : 0));\r\n\t\t}\r\n\r\n\t\tlet ans;\r\n\t\tfor (let i = 0; !ans && i < n + 2; i++) {\r\n\t\t\tconst x = sm - 2 * b[i];\r\n\t\t\tif (have.has(x)) {\r\n\t\t\t\tif (x == b[i] && have.get(x) != 2)\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tans = b.slice();\r\n\t\t\t\tans.splice(ans.indexOf(b[i]), 1);\r\n\t\t\t\tans.splice(ans.indexOf(x), 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet n = rn();\r\n\t\tlet b = rna();\r\n\r\n\t\tlet have = new Map();\r\n\t\tlet sm = 0;\r\n\t\tfor (x of b) {\r\n\t\t\tsm += x;\r\n\t\t\thave.set(x, 1 + (have.has(x) ? have.get(x) : 0));\r\n\t\t}\r\n\r\n\t\tlet ans;\r\n\t\tfor (let i = 0; !ans && i < n + 2; i++) {\r\n\t\t\tconst x = sm - 2 * b[i];\r\n\t\t\tif (have.has(x)) {\r\n\t\t\t\tans = b.slice();\r\n\t\t\t\tans.splice(ans.indexOf(b[i]), 1);\r\n\t\t\t\tans.splice(ans.indexOf(x), 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet n = rn();\r\n\t\tlet b = rna();\r\n\r\n\t\tlet sm = 0;\r\n\t\tfor (x of b) sm += x;\r\n\r\n\t\tlet ans;\r\n\t\tfor (let i = 0; !ans && i < n + 2; i++) {\r\n\t\t\tconst x = sm - 2 * b[i];\r\n\t\t\tfor (let j = 0; !ans && j < n + 2; j++)\r\n\t\t\t\tif (b[j] == x) {\r\n\t\t\t\t\tans = b.slice();\r\n\t\t\t\t\tans.splice(ans.indexOf(b[i]), 1);\r\n\t\t\t\t\tans.splice(ans.indexOf(b[j]), 1);\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? ans.join(' ') : -1);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nvar maxN = 21\r\nvar mod = 1000000007\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n const xx = readline();\r\n\r\n Array(Number(xx)).fill(1).map((t, i) => {\r\n var n = parseInt(readline());\r\n // var [x, y] = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // });\r\n var a = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n })\r\n n = n + 2\r\n var sum = 0\r\n var object = {}\r\n for (let j = 0; j < n; j++) {\r\n sum += a[j]\r\n object[a[j]] = true\r\n }\r\n var ans = []\r\n var minus1 = false\r\n var minus2 = false\r\n for (let j = 0; j < n; j++) {\r\n var number = sum - a[j]\r\n if (number % 2 === 0 && object[number / 2]) {\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] === a[j] && !minus1) {\r\n minus1 = true\r\n continue\r\n }\r\n if (a[i] === number / 2 && !minus2) {\r\n minus2 = true\r\n continue\r\n }\r\n ans.push(a[i])\r\n }\r\n console.log(ans.join(' '))\r\n return\r\n }\r\n }\r\n console.log(-1)\r\n\r\n })\r\n}\r\n"}], "src_uid": "ce667a8fb60841c994aebedb35a3b0d8"} {"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$$$) — 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 — 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": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n')\n const arrq = arr.shift().split(' ').map(a => parseInt(a))\n const c = arr.shift().split(' ').map(a => parseInt(a))//.sort((a,b) => b[0] - a[0])\n const n = arrq[0]\n const m = arrq[1]\n const d = arrq[2]\n let d2 = d\n // console.log(c)\n\n let ans = new Array(n).fill(0) \n let j = -1\n let float = n - c.reduce((a, b) => a + b, 0)\n for(let i = 0; i < m; i++) {\n if(float > 0) float -= d - 1\n if(float <= 0) d2 = 1\n ans.fill(i + 1, j + d2, j + d2 + c[i])\n j = j + d2 + c[i] - 1\n // console.log(float)\n }\n let last = 0\n for(let i = n - 1; i >= 0; i --) {\n if(ans[i] != 0){\n last = i\n break\n }\n }\n // console.log(ans, last)\n if(last + d >= n) {\n console.log('YES')\n console.log(ans.join(' '))\n }\n else \n console.log('NO')\n})"}], "negative_code": [{"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n')\n const arrq = arr.shift().split(' ').map(a => parseInt(a))\n const c = arr.shift().split(' ').map((a, i) => [parseInt(a), i]).sort((a,b) => b[0] - a[0])\n const n = arrq[0]\n const m = arrq[1]\n const d = arrq[2]\n\n let ans = new Array(n).fill(0) \n let j = -1\n for(let i = 0; i < m; i++) {\n ans.fill(c[i][1] + 1, j + d, j + d + c[i][0])\n j = j + d + c[i][0] - 1\n }\n let last = 0\n for(let i = n - 1; i >= 0; i --) {\n if(ans[i] != 0){\n last = i\n break\n }\n }\n // console.log(ans, last)\n if(last + d >= n) {\n console.log('YES')\n console.log(ans.join(' '))\n }\n else \n console.log('NO')\n})"}, {"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n')\n const arrq = arr.shift().split(' ').map(a => parseInt(a))\n const c = arr.shift().split(' ').map(a => parseInt(a))//.sort((a,b) => b[0] - a[0])\n const n = arrq[0]\n const m = arrq[1]\n const d = arrq[2]\n // console.log(c)\n\n let ans = new Array(n).fill(0) \n let j = -1\n for(let i = 0; i < m; i++) {\n ans.fill(i + 1, j + d, j + d + c[i])\n j = j + d + c[i] - 1\n }\n let last = 0\n for(let i = n - 1; i >= 0; i --) {\n if(ans[i] != 0){\n last = i\n break\n }\n }\n // console.log(ans, last)\n if(last + d >= n) {\n console.log('YES')\n console.log(ans.join(' '))\n }\n else \n console.log('NO')\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, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |bi, c - bj, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi, c is considered to be zero.", "input_spec": "The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) 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 ≤ j ≤ ai) 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": "(function() {\n\tvar line = readline().split(\" \").map(function(el) {\n\t\treturn parseInt(el);\n\t});\n\tvar n = line[0], k = line[1];\n\tline = readline().split(\" \").map(function(el) {\n\t\treturn parseInt(el);\n\t});\n\tvar a = line;\n\ta.unshift(0);\n\tvar ans = a.map(function() {\n\t\treturn [];\n\t});\n\tfor (var i = 1; i <= k; i++) {\n\t\tvar ok = true;\n\t\twhile (ok) {\n\t\t\tfor (var j = 1; j <= n; j++) {\n\t\t\t\tif (a[j] == 0) {\n\t\t\t\t\tok = false;\n\t\t\t\t} else {\n\t\t\t\t\tans[j].push(i);\n\t\t\t\t\ta[j]--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (a.every(function(el) {\n\t\treturn el == 0;\n\t})) {\n\t\tprint(\"YES\");\n\t\tfor (i = 1; i <= n; i++) {\n\t\t\tline = \"\";\n\t\t\tans[i].forEach(function(el) {\n\t\t\t\tline += el + \" \";\n\t\t\t});\n\t\t\tprint(line);\n\t\t}\n\t} else {\n\t\tprint(\"NO\");\n\t}\n}());"}], "negative_code": [], "src_uid": "e512285d15340343e34f596de2be82eb"} {"nl": {"description": "Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.Let's assume that we are given a connected weighted undirected graph G = (V, E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G1 = (V, E1) that is a tree with the set of edges E1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G1 are the same. You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.", "input_spec": "The first line contains two numbers, n and m (1 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of vertices and edges of the graph, respectively. Next m lines contain three integers each, representing an edge — ui, vi, wi — the numbers of vertices connected by an edge and the weight of the edge (ui ≠ vi, 1 ≤ wi ≤ 109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices. The last line of the input contains integer u (1 ≤ u ≤ n) — the number of the start vertex.", "output_spec": "In the first line print the minimum total weight of the edges of the tree. In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order. If there are multiple answers, print any of them.", "sample_inputs": ["3 3\n1 2 1\n2 3 1\n1 3 2\n3", "4 4\n1 2 1\n2 3 1\n3 4 1\n4 1 2\n4"], "sample_outputs": ["2\n1 2", "4\n2 3 4"], "notes": "NoteIn the first sample there are two possible shortest path trees: with edges 1 – 3 and 2 – 3 (the total weight is 3); with edges 1 – 2 and 2 – 3 (the total weight is 2); And, for example, a tree with edges 1 – 2 and 1 – 3 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1."}, "positive_code": [{"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = true;\n\t\n this.solveCase = function() {\n var res , i , len , u , v , w , sum , temp , que , head , tail , sz , key ;\n res = [] ;\n sum = 0 ;\n for( i = 0 ; i <= this.m ; i++ ) {\n \tres.push( 0 ) ;\n }\n head = 0 ;\n tail = 0 ;\n que = [] ;\n que.push( this.source ) ;\n tail++ ;\n this.vis[ this.source ] = 0 ;\n this.brr = {} ;\n while( head < tail ) {\n \tu = que[ head ] ;\n \thead++ ;\n \tsz = this.adj_list[ u ].length ;\n \tfor( i = 0 ; i < sz ; i++ ) {\n \t\tv = this.adj_list[ u ][ i ].v ;\n \t\tw = this.adj_list[ u ][ i ].w ;\n \t\tkey = v ;\n \t\tif( this.vis[ v ] > this.vis[ u ] + w ) {\n \t\t\tthis.vis[ v ] = this.vis[ u ] + w ;\n \t\t\tif( this.brr[ key ] != null ) {\n \t\t\t\tres[ this.brr[ key ] ] = 0 ;\n \t\t\t\tsum -= this.crr[ this.brr[ key ] - 1 ].w ;\n \t\t\t}\n \t\t\tthis.brr[ key ] = this.adj_list[ u ][ i ].idx ;\n \t\t\tres[ this.brr[ key ] ] = 1 ;\n \t\t\tsum += this.crr[ this.brr[ key ] - 1 ].w ;\n \t\t\tque.push( v ) ;\n \t\t\ttail++ ;\n \t\t}\n \t\telse if( this.vis[ v ] == this.vis[ u ] + w ) {\n \t\t\tif( this.brr[ key ] != null && this.crr[ this.brr[ key ] - 1 ].w > this.crr[ this.adj_list[ u ][ i ].idx - 1 ].w ) {\n \t\t\t\tres[ this.brr[ key ] ] = 0 ;\n \t\t\t\tsum -= this.crr[ this.brr[ key ] - 1 ].w ;\n \t\t\t\tthis.brr[ key ] = this.adj_list[ u ][ i ].idx ;\n \t\t\t\tres[ this.brr[ key ] ] = 1 ;\n \t\t\t\tsum += this.crr[ this.brr[ key ] - 1 ].w ;\n \t\t\t}\n \t\t}\n \t}\n }\n for( i = 1 ; i <= this.m ; i++ ) {\n \tif( res[ i ] == 1 ) {\n \t\tsum += 0 ;\n \t}\n }\n print( sum );\n temp = '' ;\n for( i = 1 ; i <= this.m ; i++ ) {\n \tif( res[ i ] == 1 ) {\n \t\tif( temp != '' ) {\n \t\t\ttemp += ' ' ;\n \t\t}\n \t\ttemp += i ;\n \t}\n }\n print( temp );\n };\n\n this.init = function() {\n this.lim1 = 300010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i , obj , u , v , w ;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n this.m = irObj.nextInt();\n this.crr = [] ;\n for( i = 0 ; i < this.m ; i++ ) {\n \tu = irObj.nextInt();\n \tv = irObj.nextInt();\n \tw = irObj.nextInt();\n \tthis.crr.push( { u : u , v : v , w : w } ) ;\n \tobj = {} ;\n \tobj.v = v ;\n \tobj.w = w ;\n \tobj.idx = i + 1;\n this.adj_list[ u ].push( obj ) ;\n obj = {} ;\n \tobj.v = u ;\n \tobj.w = w ;\n \tobj.idx = i + 1;\n this.adj_list[ v ].push( obj ) ;\n }\n this.source = irObj.nextInt();\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.vis = new Array();\n this.brr = new Array() ;\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.vis.push( 1e15 ) ;\n this.brr.push( -1 ) ;\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.pr = new Array() ;\n this.rank = new Array() ;\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 1e15 ) ;\n this.arr.push( 0 );\n this.brr.push( -1 ) ;\n this.pr.push( i ) ; \n this.rank.push( 0 ) ;\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}], "negative_code": [], "src_uid": "2232f2a26cb8ff71c1cda10ca0b73bbc"} {"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$$$) — 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": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar N = nextInt();\n\tvar list = nextCharArray();\n\tvar output = 0;\n\tfor(var i = 0; i < N; i++){\n\t\tif(myconv(list[i], 1) % 2 == 0){\n\t\t\toutput += i + 1;\n\t\t}\n\t}\n\tmyout(output);\n}\n"}, {"source_code": "var readline = require('readline');\nrl = readline.createInterface({\n input:process.stdin,\n output:process.stdout\n})\n\nrl.question('', (answer) => {\n var n = answer,k = 0,count=0\n rl.question('',(line) => {\n var str = line;\n for(var i=0;i 0; i--) {\n\t\tif (s[i - 1] % 2 === 0) x += i;\n\t}\n\tconsole.log(x)\n})();\n\nreadInput.next();\n\nrl.on('line', (line) => {\n\treadInput.next(line);\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n let ans = 0;\n const arr = d.split('').map(Number);\n let inc = 0;\n\n for (let i = arr.length; i >= 0; i--) {\n if (arr[i] % 2 === 0) {\n inc++;\n }\n\n ans += inc;\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "var n = readline();\nvar a = readline().split('');\nvar res = 0;\nfor(var i=0; i {\n var n = answer,k = 0,r = 0,i = 0\n rl.question('',(line) => {\n var str = line;\n var string='';\n while(string != str[str.length-1]) {\n if(string==str[i]){\n i++;\n r=0\n }\n string = str.substring(i,str.length-r)\n if (+string%2==0) {\n k++\n }\n r++\n }\n if(str[str.length-1]==str[str.length-2]){\n k++\n }\n console.log(k)\n rl.close()\n })\n})\n"}, {"source_code": "var n = readline();\nvar string = readline().substring(0,n);\n\nif(/[1-9]*/.test(string)){\nvar cnt=0;\nfor(var i=0; i65000) exit();\nvar cnt=0;\nfor(var i=0; i {\r\n return Number(num)\r\n })\r\n let removedElements = applyEshag(eshagArray)\r\n console.log(removedElements)\r\n }\r\n\r\n}\r\n\r\nfunction applyEshag(eshagArray) {\r\n let minValue= eshagArray[0];\r\n let wantedArray = [...eshagArray]\r\n for (let number of eshagArray) {\r\n \r\n if (number <= minValue) {\r\n minValue = number\r\n }\r\n }\r\n wantedArray = wantedArray.filter(el => el > minValue)\r\n \r\n return wantedArray.length\r\n \r\n}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar stdin_input = \"\";\r\n \r\nprocess.stdin.on(\"data\", function (input) {\r\n stdin_input += input;\r\n});\r\n \r\nprocess.stdin.on(\"end\", function () {\r\n main(stdin_input);\r\n});"}, {"source_code": "'use strict';\r\n\r\nObject.defineProperty(exports, '__esModule', { value: true });\r\n\r\nvar os = require('os');\r\n\r\nconst stdin = process.stdin;\r\nconst stdout = process.stdout;\r\nclass InputAndOutput {\r\n constructor() {\r\n this.lineIndex = 0;\r\n this.lines = [];\r\n }\r\n dried() {\r\n return this.lineIndex >= this.lines.length;\r\n }\r\n readLine() {\r\n const line = this.lines[this.lineIndex];\r\n this.lineIndex += 1;\r\n return line;\r\n }\r\n print(content) {\r\n stdout.write(content);\r\n }\r\n async init() {\r\n const lines = await this.readLines();\r\n this.lines = lines;\r\n }\r\n readLines() {\r\n const buffers = [];\r\n return new Promise(resolve => {\r\n stdin.on('data', (buffer) => buffers.push(buffer));\r\n stdin.on('end', function () {\r\n const inputs = buffers.join('');\r\n const lines = inputs.split(os.EOL);\r\n resolve(lines);\r\n });\r\n });\r\n }\r\n}\r\nasync function __main__(handle) {\r\n const io = new InputAndOutput();\r\n await io.init();\r\n handle(io);\r\n}\r\n\r\nfunction solutionA(nums) {\r\n nums.sort((x, y) => x - y);\r\n for (let i = 1; i < nums.length; ++i) {\r\n if (nums[i] > nums[i - 1])\r\n return nums.length - i;\r\n }\r\n return 0;\r\n}\r\n__main__(function (io) {\r\n const T = Number(io.readLine());\r\n for (let kase = 1; kase <= T; ++kase) {\r\n const countOfNums = Number(io.readLine());\r\n const nums = io\r\n .readLine()\r\n .trim()\r\n .split(/\\s+/g)\r\n .map(x => Number(x))\r\n .slice(0, countOfNums);\r\n const answer = solutionA(nums);\r\n io.print('' + answer + '\\n');\r\n }\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nObject.defineProperty(exports, '__esModule', { value: true });\r\n\r\nvar os = require('os');\r\n\r\nconst stdin = process.stdin;\r\nconst stdout = process.stdout;\r\nclass InputAndOutput {\r\n constructor() {\r\n this.lineIndex = 0;\r\n this.lines = [];\r\n }\r\n dried() {\r\n return this.lineIndex >= this.lines.length;\r\n }\r\n readLine() {\r\n const line = this.lines[this.lineIndex];\r\n this.lineIndex += 1;\r\n return line;\r\n }\r\n print(content) {\r\n stdout.write(content);\r\n }\r\n async init() {\r\n const lines = await this.readLines();\r\n this.lines = lines;\r\n }\r\n readLines() {\r\n const buffers = [];\r\n return new Promise(resolve => {\r\n stdin.on('data', (buffer) => buffers.push(buffer));\r\n stdin.on('end', function () {\r\n const inputs = buffers.join('');\r\n const lines = inputs.split(os.EOL);\r\n resolve(lines);\r\n });\r\n });\r\n }\r\n}\r\nasync function __main__(handle) {\r\n const io = new InputAndOutput();\r\n await io.init();\r\n handle(io);\r\n}\r\n\r\nfunction solutionA(nums) {\r\n nums.sort((x, y) => x - y);\r\n for (let i = 1; i < nums.length; ++i) {\r\n if (nums[i] > nums[i - 1])\r\n return nums.length - i;\r\n }\r\n return 0;\r\n}\r\n__main__(function (io) {\r\n const T = Number(io.readLine());\r\n for (let kase = 1; kase <= T; ++kase) {\r\n Number(io.readLine());\r\n const nums = io.readLine().split(/\\s+/g).map(x => Number(x));\r\n const answer = solutionA(nums);\r\n io.print('' + answer + '\\n');\r\n }\r\n});\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0], e = 0\n for(j = 1; j <= n*2; j++){\n if(j % 2 === 1){\n e = lines[j], a = new Map()\n }else{\n k = lines[j].split(' ').map(Number).sort(function(a, b){return a - b}),\n small = k[0], s = 0\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n tp = a.get(k[l])\n tp++\n a.set(k[l], tp)\n }else{\n a.set(k[l], 1)\n }\n }\n var biggestKey = ''\n var biggestValue = 0\n for(var[key, value] of a){\n if(key != small){\n s+=value\n }\n }\n console.log(s)\n \n }\n \n \n }\n \n\t \n}); "}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0 ; i < t; i++){\n\t\tlet n = nl.num();\n\t\tlet a = nl.nums();\n\t\tlet m = a.reduce((ac, e) => e e == m?(ac+1):ac, 0));\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0 ; i < t; i++){\n\t\tlet n = nl.num();\n\t\tlet a = nl.nums();\n\t\tlet m = Math.min(...a);\n\t\tans.push(n - a.reduce((ac, e) => e == m?(ac+1):ac, 0));\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "const fs = require('fs')\r\n\r\nconst inputs = fs.readFileSync(0).toString().split('\\n');\r\n\r\nfunction deleteElementsFromArr(arr = [], count = 0) {\r\n if (!arr.length) return count;\r\n const avg = arr.reduce((sum, cur) => sum + cur, 0) / arr.length;\r\n const max = Math.max(...arr);\r\n if (max > avg) {\r\n const newArr = arr.filter(el => el !== max);\r\n return deleteElementsFromArr(newArr, (arr.length - newArr.length) + count);\r\n }\r\n return count;\r\n}\r\n\r\n\r\nfunction main() {\r\n for (let i = 2; i < inputs.length; i += 2) {\r\n const arr = inputs[i].split(\" \").map(e => +e);\r\n const count = deleteElementsFromArr(arr);\r\n console.log(count);\r\n\r\n }\r\n}\r\n\r\n\r\nmain();"}, {"source_code": "let q = '';\nprocess.stdin.on('data', c => q += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = q.split(EOL);\n var t = lines[0];\n var e = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n e = lines[i];\n }else{\n var k = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});\n var ans = 0;\n var a = k[0];\n for(j = 1; j < e; j++){\n if(k[j] > a){\n ans++;\n }\n }\n console.log(ans);\n }\n }\n});\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\nlet inputString = '';\r\nlet currentLine = 0;\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\nfunction readLine() {\r\n return inputString[currentLine++];\r\n};\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n main();\r\n // cmd(not powershell): node cp.js < input.txt\r\n});\r\n\r\nfunction main() {\r\n let t = parseInt(readLine());\r\n while (t-- > 0) {\r\n solve();\r\n }\r\n}\r\nfunction solve() {\r\n let len = readLine();\r\n let arr = readLine().split(\" \").map(i => parseInt(i)).sort((a, b) => a - b);\r\n let count = 1;\r\n for (let i = 1; i < len; i++) {\r\n if (arr[0] == arr[i]) count++;\r\n else break;\r\n }\r\n console.log(arr.length - count);\r\n}\r\n"}, {"source_code": "const rl = require(\"readline\").createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nlet lines = [];\r\nlet lineIdx = 0;\r\n\r\nrl.on(\"line\", line => {\r\n lines.push(line);\r\n});\r\n\r\nrl.on(\"close\", () => {\r\n main();\r\n});\r\n\r\nfunction readLine() {\r\n return lines[lineIdx++];\r\n}\r\n\r\nfunction main() {\r\n let t = +readLine();\r\n while (t--) {\r\n let n = +readLine();\r\n let a = readLine().split(' ').map(x => +x).sort((x, y) => x - y);\r\n let i = 0;\r\n while (i < n && a[0] == a[i])\r\n i++;\r\n console.log(n - i);\r\n }\r\n}\r\n"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst mxll = (...args) => args.reduce((m, e) => e > m ? e : m);\r\nconst mill = (...args) => args.reduce((m, e) => e < m ? e : m);\r\nconst sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst ll = BigInt;\r\nconst combination = (m, n) => { return factorial(m, n) / factorial(n, n); };\r\nconst factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };\r\nconst powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };\r\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\r\nconst stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));\r\nconst stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));\r\nconst stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };\r\nconst counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };\r\nconst reverse2 = (s) => { let res = \"\"; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };\r\nconst isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/24/21 morning\r\n * https://codeforces.com/contest/1529/problem/A\r\n */\r\nconst solve = (n, a) => {\r\n let min = amin(a);\r\n let m = counter(a);\r\n let minC = m.get(min);\r\n // pr(n, a)\r\n pr(n - minC);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n let t = input[0][0];\r\n let i = 1;\r\n while (t--) {\r\n solve(input[i][0], input[i + 1]);\r\n i += 2;\r\n }\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "let i = '';\nprocess.stdin.on('data', (c) => (i += c));\nprocess.stdin.on('end', () => {\n const { EOL } = require('os');\n const lines = i.split(EOL);\n const N = parseInt(lines[0]);\n const arrays = [];\n const arrMin = [];\n let min = 999999;\n let result = 0;\n\n for (let i = 2; i < lines.length; i += 2) {\n arrays.push(lines[i].split(' ').map((n) => parseInt(n)));\n }\n\n for (let arr of arrays) {\n min = 999999;\n for (let num of arr) {\n min = Math.min(num, min);\n }\n arrMin.push(min);\n }\n for (let j = 0; j < arrays.length; j++) {\n result = 0;\n for (let i = 0; i < arrays[j].length; i++) {\n if (arrays[j][i] > arrMin[j]) {\n result += 1;\n }\n }\n console.log(result);\n }\n});\n"}, {"source_code": "const nextString = (function() {\r\n const listeners = [], strings = [], ps = process.stdin\r\n let last = ''\r\n ps.setEncoding('utf8')\r\n ps.on('readable', () => {\r\n let chunk\r\n while ((chunk = ps.read()) !== null) {\r\n chunk = (last + chunk).split(/\\r\\n|\\r|\\n/)\r\n last = chunk[chunk.length - 1]\r\n for (let i = 0; i < chunk.length - 1; ++i) {\r\n if (chunk[i].length > 0) {\r\n if (listeners.length > 0) {\r\n listeners.shift(1)(chunk[i])\r\n }\r\n else {\r\n strings.push(chunk[i])\r\n }\r\n }\r\n }\r\n }\r\n })\r\n const fn = resolve => {\r\n if (strings.length > 0) {\r\n resolve(strings.shift(1))\r\n }\r\n else {\r\n listeners.push(resolve)\r\n }\r\n }\r\n return () => new Promise(fn)\r\n})()\r\n\r\nasync function proc() {\r\n let n = +await nextString();\r\n let mas = (await nextString()).split(' ').map(x => +x)\r\n let min = Math.min(...mas)\r\n let ans = 0\r\n for (let i = 0; i < n; ++i) {\r\n if (mas[i] > min) {\r\n ++ans\r\n }\r\n }\r\n console.log(ans)\r\n}\r\n \r\nasync function main() {\r\n let t = +await nextString()\r\n for (let i = 0; i < t; ++i) {\r\n await proc()\r\n }\r\n}\r\n \r\nmain()\r\n"}, {"source_code": "\r\nconst solve = (line) => {\r\n\tconst arr = line.split(' ').map(v => +v);\r\n\tconst min = Math.min(...arr);\r\n\r\n\treturn arr.filter(item => item !== min).length;\r\n}\r\n\r\nlet input = '';\r\nprocess.stdin.on('data', str => input += str)\r\nprocess.stdin.on('end', () => {\r\n\tconst [n, ...lines] = input.trim().split('\\n')\r\n\t\t.map(l => l.trim());\r\n\r\n\tfor (let i=0; i {\r\n return Number(num)\r\n })\r\n let removedElements = applyEshag(eshagArray)\r\n console.log(removedElements)\r\n }\r\n\r\n}\r\n\r\nfunction applyEshag(eshagArray) {\r\n let avg = null;\r\n for (let number of eshagArray) {\r\n avg += number\r\n }\r\n avg = avg/eshagArray.length\r\n let subSequenceFiltered = eshagArray.filter(el => el < avg)\r\n if (subSequenceFiltered.length === 0) {\r\n return 0;\r\n } else {\r\n return eshagArray.length - subSequenceFiltered.length\r\n }\r\n}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar stdin_input = \"\";\r\n \r\nprocess.stdin.on(\"data\", function (input) {\r\n stdin_input += input;\r\n});\r\n \r\nprocess.stdin.on(\"end\", function () {\r\n main(stdin_input);\r\n});"}, {"source_code": "\r\n\r\nfunction main(input) {\r\n let arr = input.split(\"\\n\")\r\n let testCases = arr[0]\r\n let arrayLength = arr[1]\r\n let eshagArray = arr[2]\r\n eshagArray = eshagArray.split(\" \").map(num => {\r\n return Number(num)\r\n })\r\n \r\n \r\n let removedElements = applyEshag(eshagArray)\r\n // return removedElements\r\n // process.stdout.write(removedElements)\r\n console.log(removedElements)\r\n \r\n}\r\n\r\nfunction applyEshag(eshagArray) {\r\n let subSequence = eshagArray.slice(1,4);\r\n let avg = null;\r\n \r\n for (let number of eshagArray) {\r\n avg += number\r\n }\r\n avg = avg/eshagArray.length\r\n let subSequenceFiltered = eshagArray.filter(el => el < avg)\r\n // console.log('average',avg)\r\n // console.log('new',subSequenceFiltered)\r\n const test = eshagArray.length - subSequenceFiltered.length\r\n if (subSequenceFiltered.length === 0) {\r\n return 0;\r\n } else {\r\n return eshagArray.length - subSequenceFiltered.length\r\n }\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar stdin_input = \"\";\r\n\r\nprocess.stdin.on(\"data\", function (input) {\r\n stdin_input += input;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n main(stdin_input);\r\n});"}, {"source_code": "\r\n\r\nfunction main(input) {\r\n let arr = input.split(\"\\n\")\r\n let testCases = arr[0]\r\n let arrayLength = arr[1]\r\n let eshagArray = arr[2]\r\n eshagArray = eshagArray.split(\" \").map(num => {\r\n return Number(num)\r\n })\r\n \r\n \r\n let removedElements = applyEshag(eshagArray)\r\n return removedElements\r\n // console.log('final result',removedElements)\r\n \r\n}\r\n\r\nfunction applyEshag(eshagArray) {\r\n let subSequence = eshagArray.slice(1,4);\r\n let avg = null;\r\n \r\n for (let number of eshagArray) {\r\n avg += number\r\n }\r\n avg = avg/eshagArray.length\r\n let subSequenceFiltered = eshagArray.filter(el => el < avg)\r\n // console.log('average',avg)\r\n // console.log('new',subSequenceFiltered)\r\n const test = eshagArray.length - subSequenceFiltered.length\r\n if (subSequenceFiltered.length === 0) {\r\n return 0;\r\n } else {\r\n return eshagArray.length - subSequenceFiltered.length\r\n }\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar stdin_input = \"\";\r\n\r\nprocess.stdin.on(\"data\", function (input) {\r\n stdin_input += input;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n main(stdin_input);\r\n});"}, {"source_code": "\r\n\r\nfunction main(input) {\r\n let arr = input.split(\"\\n\")\r\n let testCases = arr[0]\r\n let arrayLength = arr[1]\r\n let eshagArray = arr[2]\r\n eshagArray = eshagArray.split(\" \").map(num => {\r\n return Number(num)\r\n })\r\n \r\n \r\n let removedElements = applyEshag(eshagArray)\r\n // console.log('final result',removedElements)\r\n \r\n}\r\n\r\nfunction applyEshag(eshagArray) {\r\n let subSequence = eshagArray.slice(1,4);\r\n let avg = null;\r\n \r\n for (let number of eshagArray) {\r\n avg += number\r\n }\r\n avg = avg/eshagArray.length\r\n let subSequenceFiltered = eshagArray.filter(el => el < avg)\r\n // console.log('average',avg)\r\n // console.log('new',subSequenceFiltered)\r\n const test = eshagArray.length - subSequenceFiltered.length\r\n if (subSequenceFiltered.length === 0) {\r\n return 0;\r\n } else {\r\n return eshagArray.length - subSequenceFiltered.length\r\n }\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nvar stdin_input = \"\";\r\n\r\nprocess.stdin.on(\"data\", function (input) {\r\n stdin_input += input;\r\n});\r\n\r\nprocess.stdin.on(\"end\", function () {\r\n main(stdin_input);\r\n});"}, {"source_code": "'use strict';\r\n\r\nObject.defineProperty(exports, '__esModule', { value: true });\r\n\r\nvar os = require('os');\r\n\r\nconst stdin = process.stdin;\r\nconst stdout = process.stdout;\r\nclass InputAndOutput {\r\n constructor() {\r\n this.lineIndex = 0;\r\n this.lines = [];\r\n }\r\n dried() {\r\n return this.lineIndex >= this.lines.length;\r\n }\r\n readLine() {\r\n const line = this.lines[this.lineIndex];\r\n this.lineIndex += 1;\r\n return line;\r\n }\r\n print(content) {\r\n stdout.write(content);\r\n }\r\n async init() {\r\n const lines = await this.readLines();\r\n this.lines = lines;\r\n }\r\n readLines() {\r\n const buffers = [];\r\n return new Promise(resolve => {\r\n stdin.on('data', (buffer) => buffers.push(buffer));\r\n stdin.on('end', function () {\r\n const inputs = buffers.join('');\r\n const lines = inputs.split(os.EOL);\r\n resolve(lines);\r\n });\r\n });\r\n }\r\n}\r\nasync function __main__(handle) {\r\n const io = new InputAndOutput();\r\n await io.init();\r\n handle(io);\r\n}\r\n\r\nfunction solutionA(nums) {\r\n nums.sort((x, y) => x - y);\r\n for (let i = 1; i < nums.length; ++i) {\r\n if (nums[i] > nums[i - 1])\r\n return nums.length - i;\r\n }\r\n return 0;\r\n}\r\n__main__(function (io) {\r\n const T = Number(io.readLine());\r\n for (let kase = 1; kase <= T; ++kase) {\r\n Number(io.readLine());\r\n const nums = io.readLine().split(/\\s*/g).map(x => Number(x));\r\n const answer = solutionA(nums);\r\n io.print('' + answer + '\\n');\r\n }\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nObject.defineProperty(exports, '__esModule', { value: true });\r\n\r\nvar os = require('os');\r\n\r\nconst stdin = process.stdin;\r\nconst stdout = process.stdout;\r\nclass InputAndOutput {\r\n constructor() {\r\n this.lineIndex = 0;\r\n this.lines = [];\r\n }\r\n dried() {\r\n return this.lineIndex >= this.lines.length;\r\n }\r\n readLine() {\r\n const line = this.lines[this.lineIndex];\r\n this.lineIndex += 1;\r\n return line;\r\n }\r\n print(content) {\r\n stdout.write(content);\r\n }\r\n async init() {\r\n const lines = await this.readLines();\r\n this.lines = lines;\r\n }\r\n readLines() {\r\n const buffers = [];\r\n return new Promise(resolve => {\r\n stdin.on('data', (buffer) => buffers.push(buffer));\r\n stdin.on('end', function () {\r\n const inputs = buffers.join('\\n');\r\n const lines = inputs.split(os.EOL);\r\n resolve(lines);\r\n });\r\n });\r\n }\r\n}\r\nasync function __main__(handle) {\r\n if (process.env.GUANGHECHEN_LOCAL)\r\n return;\r\n const io = new InputAndOutput();\r\n await io.init();\r\n handle(io);\r\n}\r\n\r\nfunction solutionA(nums) {\r\n nums.sort((x, y) => x - y);\r\n for (let i = 1; i < nums.length; ++i) {\r\n if (nums[i] > nums[i - 1])\r\n return nums.length - i;\r\n }\r\n return 0;\r\n}\r\n__main__(function (io) {\r\n const T = Number(io.readLine());\r\n for (let kase = 1; kase <= T; ++kase) {\r\n Number(io.readLine());\r\n const nums = io.readLine().split('').map(x => Number(x));\r\n const answer = solutionA(nums);\r\n io.print('' + answer + '\\n');\r\n }\r\n});\r\n\r\nexports.default = solutionA;\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0],e=0, k = 0\n for(j = 1; j <= n *2; j++){\n if(j % 2 == 1){\n e = lines[j],a = new Map()\n }else{\n k = lines[j].split(' ').map(Number)\n for(l = 0; l < e; l++){\n if(a.has(k[l])){\n ut = a.get(k[l])\n ut++\n a.set(k[l], ut)\n }else{\n a.set(k[l], 1)\n }\n }\n var biggestValue = 0\n for(var[key, value] of a){\n if(value > biggestValue){\n biggestValue=value\n }\n }\n console.log(Number(e - biggestValue))\n }\n }\n\n});"}, {"source_code": "const fs = require('fs')\r\n\r\nconst inputs = fs.readFileSync(0).toString().split('\\n');\r\n\r\nfunction deleteElementsFromArr(arr = [], count = 0) {\r\n if (!arr.length) return count;\r\n const avg = arr.reduce((sum, cur) => sum + cur, 0) / arr.length;\r\n const newArr = arr.filter(el => el <= avg);\r\n if (newArr.length !== arr.length) return deleteElementsFromArr(newArr, (arr.length - newArr.length));\r\n return count;\r\n}\r\n\r\n\r\nfunction main() {\r\n for (let i = 2; i < inputs.length; i += 2) {\r\n const arr = inputs[i].split(\" \").map(e => +e);\r\n const count = deleteElementsFromArr(arr);\r\n console.log(count);\r\n\r\n }\r\n}\r\n\r\n\r\nmain();"}], "src_uid": "d5627b9fe5f6c5a7247e1f9d9e9b0c6a"} {"nl": {"description": "You are walking with your dog, and now you are at the promenade. The promenade can be represented as an infinite line. Initially, you are in the point $$$0$$$ with your dog. You decided to give some freedom to your dog, so you untied her and let her run for a while. Also, you watched what your dog is doing, so you have some writings about how she ran. During the $$$i$$$-th minute, the dog position changed from her previous position by the value $$$a_i$$$ (it means, that the dog ran for $$$a_i$$$ meters during the $$$i$$$-th minute). If $$$a_i$$$ is positive, the dog ran $$$a_i$$$ meters to the right, otherwise (if $$$a_i$$$ is negative) she ran $$$a_i$$$ meters to the left.During some minutes, you were chatting with your friend, so you don't have writings about your dog movement during these minutes. These values $$$a_i$$$ equal zero.You want your dog to return to you after the end of the walk, so the destination point of the dog after $$$n$$$ minutes should be $$$0$$$.Now you are wondering: what is the maximum possible number of different integer points of the line your dog could visit on her way, if you replace every $$$0$$$ with some integer from $$$-k$$$ to $$$k$$$ (and your dog should return to $$$0$$$ after the walk)? The dog visits an integer point if she runs through that point or reaches in it at the end of any minute. Point $$$0$$$ is always visited by the dog, since she is initially there.If the dog cannot return to the point $$$0$$$ after $$$n$$$ minutes regardless of the integers you place, print -1.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 3000; 1 \\le k \\le 10^9$$$) — the number of minutes and the maximum possible speed of your dog during the minutes without records. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the number of meters your dog ran during the $$$i$$$-th minutes (to the left if $$$a_i$$$ is negative, to the right otherwise). If $$$a_i = 0$$$ then this value is unknown and can be replaced with any integer from the range $$$[-k; k]$$$.", "output_spec": "If the dog cannot return to the point $$$0$$$ after $$$n$$$ minutes regardless of the set of integers you place, print -1. Otherwise, print one integer — the maximum number of different integer points your dog could visit if you fill all the unknown values optimally and the dog will return to the point $$$0$$$ at the end of the walk.", "sample_inputs": ["3 2\n5 0 -4", "6 4\n1 -2 0 3 -4 5", "3 1000000000\n0 0 0", "5 9\n-7 -3 8 12 0", "5 3\n-1 0 3 3 0", "5 4\n0 2 0 3 0"], "sample_outputs": ["6", "7", "1000000001", "-1", "7", "9"], "notes": null}, "positive_code": [{"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = 1//+lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const [n, k] = lines[l++].trim().split(' ').map(Number)\r\n const arr = lines[l++].trim().split(' ').map(Number)\r\n output[i] = solve(n, k, arr)\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(n, k, arr) {\r\n // let zero = 0\r\n // let sum = 0\r\n // arr.forEach(x => {\r\n // if (!x) zero++\r\n // sum += x\r\n // })\r\n // const count = Math.ceil(Math.abs(sum) / k)\r\n // if (zero < count) return -1\r\n // const more = zero - count\r\n // const d = k * Math.floor(more / 2)\r\n let ans = -1\r\n for (let i = 0; i < n; i++) {\r\n ans = Math.max(ans, helper(n, k, arr, i))\r\n }\r\n return ans\r\n}\r\nfunction helper(n, k, arr, off) {\r\n const suf = []\r\n for (let j = n - 1; j >= 0; j--) {\r\n const i = (n + j - off) % n\r\n const now = arr[i] ? -arr[i] : k\r\n suf[j] = j < n - 1 ? suf[j + 1] + now : now\r\n }\r\n// console.log('suf', suf)\r\n let sum = 0\r\n let ans = -Infinity\r\n for (let j = 0; j < n; j++) {\r\n const i = (n + j - off) % n\r\n if (arr[i]) {\r\n sum += arr[i]\r\n } else {\r\n const now = Math.min(k, (j + 1 < n ? suf[j + 1] : 0) - sum)\r\n if (now < -k) return -1\r\n // console.log(now)\r\n sum += now\r\n if (sum < 0) return -1\r\n }\r\n ans = Math.max(ans, sum)\r\n }\r\n if (sum) return -1\r\n // console.log(off, ans, sum)\r\n return ans + 1\r\n}\r\n"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = 1//+lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, k, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, arr) {\n // let zero = 0\n // let sum = 0\n // arr.forEach(x => {\n // if (!x) zero++\n // sum += x\n // })\n // const count = Math.ceil(Math.abs(sum) / k)\n // if (zero < count) return -1\n // const more = zero - count\n // const d = k * Math.floor(more / 2)\n let ans = -1\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, helper(n, k, arr, i))\n }\n return ans\n}\nfunction helper(n, k, arr, off) {\n const suf = []\n for (let j = n - 1; j >= 0; j--) {\n const i = (n + j - off) % n\n const now = arr[i] ? -arr[i] : k\n suf[j] = j < n - 1 ? suf[j + 1] + now : now\n }\n// console.log('suf', suf)\n let sum = 0\n let ans = -Infinity\n for (let j = 0; j < n; j++) {\n const i = (n + j - off) % n\n if (arr[i]) {\n sum += arr[i]\n } else {\n const now = Math.min(k, (j + 1 < n ? suf[j + 1] : 0) - sum)\n if (now < -k) return -1\n // console.log(now)\n sum += now\n if (sum < 0) return -1\n }\n ans = Math.max(ans, sum)\n }\n // console.log(off, ans, sum)\n return ans + 1\n}\n"}], "src_uid": "21932a14b356c267eae7e589f8ae8202"} {"nl": {"description": "Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.Hemose has an array of $$$n$$$ integers. He wants Samez to sort the array in the non-decreasing order. Since it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:Choose indices $$$i$$$ and $$$j$$$ such that $$$1 \\le i, j \\le n$$$, and $$$\\lvert i - j \\rvert \\geq x$$$. Then, swap elements $$$a_i$$$ and $$$a_j$$$.Can you tell Samez if there's a way to sort the array in the non-decreasing order by using the operation written above some finite number of times (possibly $$$0$$$)?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \\leq t \\leq 10^5)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \\leq x \\leq n \\leq 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ..., a_n$$$ $$$(1 \\leq a_i \\leq 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, you should output a single string. If Samez can sort the array in non-decreasing order using the operation written above, output \"YES\" (without quotes). Otherwise, output \"NO\" (without quotes). You can print each letter of \"YES\" and \"NO\" in any case (upper or lower).", "sample_inputs": ["4\n3 3\n3 2 1\n4 3\n1 2 3 4\n5 2\n5 1 2 3 4\n5 4\n1 2 3 4 4"], "sample_outputs": ["NO\nYES\nYES\nYES"], "notes": "NoteIn the first test case, you can't do any operations.In the second test case, the array is already sorted.In the third test case, you can do the operations as follows: $$$[5,1,2,3,4]$$$, $$$swap(a_1,a_3)$$$ $$$[2,1,5,3,4]$$$, $$$swap(a_2,a_5)$$$ $$$[2,4,5,3,1]$$$, $$$swap(a_2,a_4)$$$ $$$[2,3,5,4,1]$$$, $$$swap(a_1,a_5)$$$ $$$[1,3,5,4,2]$$$, $$$swap(a_2,a_5)$$$ $$$[1,2,5,4,3]$$$, $$$swap(a_3,a_5)$$$ $$$[1,2,3,4,5]$$$ (Here $$$swap(a_i, a_j)$$$ refers to swapping elements at positions $$$i$$$, $$$j$$$)."}, "positive_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tlet [n, x] = rna();\r\n\t\tlet a = rna();\r\n\t\tlet j = x - 1, i = n - x;\r\n\r\n\t\tlet b = a.slice();\r\n\t\tb.sort((x, y) => x - y);\r\n\r\n\t\tlet ans = true;\r\n\t\tfor (let k = i; k <= j; k++) {\r\n\t\t\tans = ans && a[k] == b[k];\r\n\t\t}\r\n\r\n\t\tconsole.log(ans ? 'YES' : 'NO');\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, x] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n\r\n let ans = true;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (arr[i] > arr[i + 1]) {\r\n ans = false;\r\n break;\r\n }\r\n }\r\n if (ans) console.log(\"YES\");\r\n else {\r\n ans = true;\r\n let narr = [...arr];\r\n narr.sort((a, b) => a - b);\r\n let bool = new Array(n).fill(false);\r\n for (let i = 0; i < n; i++) {\r\n if (!bool[i]) {\r\n for (let j = i + x; j < n; j++) {\r\n if (bool[j] === true) {\r\n bool[i] = true;\r\n break;\r\n }\r\n if (j - i >= x) {\r\n bool[i] = true;\r\n bool[j] = true;\r\n }\r\n }\r\n }\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (!bool[i]) {\r\n if (narr[i] !== arr[i]) {\r\n ans = false;\r\n break;\r\n }\r\n }\r\n }\r\n if (ans) console.log(\"YES\");\r\n else console.log(\"NO\");\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n for (let i = 0; i < t; i++) {\n const [n, x] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n console.log(solve(n, x, arr))\n }\n// })()\n})\n\nfunction solve(n, x, arr) {\n const sorted = arr.slice().sort((a, b) => a - b)\n for (let i = 0; i < arr.length; i++) {\n if (i + x >= n && i - x < 0 && arr[i] !== sorted[i]) {\n return 'NO'\n }\n }\n return 'YES'\n}\n"}], "negative_code": [{"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\tlet cnt = 0;\r\n\twhile (t--) {\r\n\t\tlet [n, x] = rna();\r\n\t\tlet a = rna();\r\n\r\n\t\tcnt ++;\r\n\t\tif (cnt == 48) {\r\n\t\t\tconsole.log(n, x) ;\r\n\t\t\tconsole.log(a);\r\n\t\t}\r\n\t\tconst k = n - x;\r\n\r\n\t\tif (2 * k >= n) {\r\n\t\t\tconsole.log('YES');\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tlet sorted = true;\r\n\t\tfor (let i = k + 1; sorted && i < n - k; i++) {\r\n\t\t\tif (a[i] < a[i - 1]) sorted = false;\r\n\t\t}\r\n\t\tif (!sorted) { \r\n\t\t\tconsole.log('NO');\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tlet lcnt = 0, l = a[k];\r\n\t\tfor (let i = 0; i < k; i++) {\r\n\t\t\tif (a[i] <= l) lcnt++;\r\n\t\t\tif (a[n-1-i] <= l) lcnt++;\r\n\t\t}\r\n\r\n\t\tans = lcnt == k ? 'YES' : 'NO';\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet t = rn();\r\n\twhile (t--) {\r\n\t\tlet [n, x] = rna();\r\n\t\tlet a = rna();\r\n\r\n\t\tconst k = n - x;\r\n\r\n\t\tif (2 * k >= n) {\r\n\t\t\tconsole.log('YES');\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tlet sorted = true;\r\n\t\tfor (let i = k + 1; sorted && i < n - k; i++) {\r\n\t\t\tif (a[i] < a[i - 1]) sorted = false;\r\n\t\t}\r\n\t\tif (!sorted) { \r\n\t\t\tconsole.log('NO');\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tlet lcnt = 0, l = a[k];\r\n\t\tfor (let i = 0; i < k; i++) {\r\n\t\t\tif (a[i] <= l) lcnt++;\r\n\t\t\tif (a[n-1-i] <= l) lcnt++;\r\n\t\t}\r\n\r\n\t\tans = lcnt == k ? 'YES' : 'NO';\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n"}], "src_uid": "1305b44c5c588221bc991c696a492fe7"} {"nl": {"description": "You are given an undirected tree of $$$n$$$ vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.How many nice edges are there in the given tree?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 2$$$) — the colors of the vertices. $$$a_i = 1$$$ means that vertex $$$i$$$ is colored red, $$$a_i = 2$$$ means that vertex $$$i$$$ is colored blue and $$$a_i = 0$$$ means that vertex $$$i$$$ is uncolored. The $$$i$$$-th of the next $$$n - 1$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \\le v_i, u_i \\le n$$$, $$$v_i \\ne u_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.", "output_spec": "Print a single integer — the number of nice edges in the given tree.", "sample_inputs": ["5\n2 0 0 1 2\n1 2\n2 3\n2 4\n2 5", "5\n1 0 0 0 2\n1 2\n2 3\n3 4\n4 5", "3\n1 1 2\n2 3\n1 3"], "sample_outputs": ["1", "4", "0"], "notes": "NoteHere is the tree from the first example: The only nice edge is edge $$$(2, 4)$$$. Removing it makes the tree fall apart into components $$$\\{4\\}$$$ and $$$\\{1, 2, 3, 5\\}$$$. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.Here is the tree from the second example: Every edge is nice in it.Here is the tree from the third example: Edge $$$(1, 3)$$$ splits the into components $$$\\{1\\}$$$ and $$$\\{3, 2\\}$$$, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge $$$(2, 3)$$$ splits the into components $$$\\{1, 3\\}$$$ and $$$\\{2\\}$$$, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0."}, "positive_code": [{"source_code": "var nums = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = nums[0];\nvar AAA = readline().split(\" \").map(function(x) { return parseInt(x); });\n\nvar init_cnt = Array(3).fill(0);\nfor (var i=0; i 0) {\n\tvar v = st[st.length-1];\n\tnnew[v] = 1;\n\tvar fnd = 0;\n\tfor (var i=sv[v]; i 0) {\n// \twrite(\"init_cnt = \",init_cnt,\"\\n\");\n// \twrite(\"sizes > 2\");\n// \tfor (var i=0; i 2)\n// \t\t\twrite(ms[i].length,\" \");\n// \tfor (var i=0; i 0) {\n\tvar v = st[st.length-1];\n\tnnew[v] = 1;\n\tvar fnd = 0;\n\tfor (var i=sv[v]; i 0) {\n\tvar v = st[st.length-1];\n\tnnew[v] = 1;\n\tvar fnd = 0;\n\tfor (var i=sv[v]; i 0) {\n//write(\"stk = \",st,\"\\n\");\n\tvar v = st[st.length-1];\n\tnnew[v] = 1;\n\tvar fnd = 0;\n\tfor (var i=sv[v]; i 0) {\n\tvar v = st[st.length-1];\n\tnnew[v] = 1;\n\tvar fnd = 0;\n\tfor (var i=sv[v]; i 0) {\n\twrite(\"init_cnt = \",init_cnt,\"\\n\");\n\twrite(\"sizes > 2\");\n\tfor (var i=0; i 2)\n\t\t\twrite(ms[i].length,\" \");\n\tfor (var i=0; i 0) {\n\tvar v = st[st.length-1];\n\tnnew[v] = 1;\n\tvar fnd = 0;\n\tfor (var i=sv[v]; i 0) {\n\twrite(\"init_cnt = \",init_cnt,\"\\n\");\n\twrite(\"sizes > 2\");\n\tfor (var i=0; i 2)\n\t\t\twrite(ms[i].length,\" \");\n\tfor (var i=0; i {\n\t\treturn string.trim();\n\t});;\n\tlet [n, a, b] = inputReader.readNumberArray();\n\tlet arr = inputReader.readNumberArray();\n\tlet extra = 0;\n\tlet count = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (arr[i] === 1) {\n\t\t\tif (a > 0) a--;\n\t\t\telse if (b > 0) {\n\t\t\t\tb--;\n\t\n\t\t\t\textra++;\n\t\t\t} else if (extra > 0) {\n\t\t\t\textra--;\n\t\t\t} else count++;\n\t\t} else {\n\t\t\tif (b > 0) b--;\n\t\t\telse count += 2;\n\t\t}\n\t}\n\tconsole.log(count);\n\n}\n\nvar _inputData = '';\nfunction cacheInput(data) {\n\t_inputData += data;\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', cacheInput).on('end', _main);\n\nfunction _inputReader () {\n\tfunction readNumberArray(){\n\t\treturn _inputLines[_lineNumber++].split(' ').map(val => Number(val));\n\t}\n\t\t\n\t\n\treturn {\n\t\treadNumberArray,\n\t}\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n let numberOfTwoSeaterOccupiedByOnePerson = 0;\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfTwoSeaterOccupiedByOnePerson++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && !numberOfTwoSeater&& numberOfTwoSeaterOccupiedByOnePerson > 0) {\n\n numberOfTwoSeaterOccupiedByOnePerson--;\n groups[index] = 0;\n } \n \n else if (groups[index] > 0 && groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n \n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "var data = readline().split(' ').map(function (x) { return parseInt(x); });\nvar guests = readline().split(' ').map(function (x) { return parseInt(x); });\n\nvar sTable = data[1];\nvar dTable = data[2];\nvar seat = 0;\n\nvar total = guests.reduce(function (a,b) {\n return a + b;\n}, 0);\n\nfor (var g of guests) {\n if (g === 2) {\n if (dTable !== 0) {\n dTable--;\n total -= g;\n }\n }\n if (g === 1) {\n if (sTable !== 0) {\n sTable--;\n total -= g;\n } else if (dTable !== 0) {\n dTable--;\n seat++;\n total -= g;\n } else if (seat !== 0) {\n seat--;\n total -= g;\n }\n }\n \n}\n\nprint(total);"}, {"source_code": "var data = readline().split(' '),\n people = readline().split(' '),\n n = parseInt(data[0]),\n a = parseInt(data[1]),\n b = parseInt(data[2]),\n temp = 0,\n output = 0;\n \nfor(var i = 0; i < people.length; i++) {\n if(parseInt(people[i]) === 1) {\n if(a !== 0) {\n a = a - 1;\n } else if(b !== 0) {\n b = b - 1;\n temp = temp + 1;\n } else if(b === 0 && temp !== 0) {\n temp = temp - 1;\n } else {\n output = output + 1;\n }\n } else {\n if(b !== 0) {\n b = b - 1;\n } else {\n output = output + 2;\n }\n }\n}\n\nprint(output);"}, {"source_code": "function GetAns(n, a, b, array){\n\tvar ans=0;\n\tvar tOne, tTwo, tTwoWithOne;\n\ttOne = a; tTwo = b; tTwoWithOne = 0;\n\tfor (var i=0;i0)\n\t\t\t\ttTwo--;\n\t\t\telse\n\t\t\t\tans+=2;\n\t\t}\n\t\telse{\n\t\t\tif (tOne>0)\n\t\t\t\ttOne--;\n\t\t\telse{\n\t\t\t\tif (tTwo>0){\n\t\t\t\t\t\ttTwo--;\n\t\t\t\t\t\ttTwoWithOne++;\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tif (tTwoWithOne>0) tTwoWithOne--;\n\t\t\t\t\telse\n\t\t\t\t\t\t\tans++;\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\n\nvar input = readline().split(' ');\nvar n=+input[0], a=+input[1], b=+input[2];\nvar array=readline().split(' ');\nprint(GetAns(n,a,b,array));"}], "negative_code": [{"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n sum = groups => groups.reduce((a,b) => a + b, 0)\n\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && numberOfOneSeater == 0 && numberOfTwoSeater > 0) {\n\n numberOfOneSeater += 2;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += Number(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < numberOfGroups; index++) {\n\n if (Number(groups[index]) == 1 && numberOfOneSeater > 0) {\n numberOfOneSeater--;\n groups[index] = 0 \n }\n\n else if(Number(groups[index]) == 1 && numberOfOneSeater == 0 && numberOfTwoSeater > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0\n }\n \n else if (Number(groups[index]) != 1 && numberOfTwoSeater > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 \n }\n }\n \n for(let index = 0 ; index < numberOfGroups ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n let totalSum = 0 ;\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n sum++;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n sum++;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--; \n sum += 2\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n totalSum += parseInt(groups[index]);\n }\n\n console.log(totalSum - sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n /**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 ;\n }\n\n if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n }\n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 ;\n }\n }\n \n for(let index = 0 ; index < Number(numberOfGroups) ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 ;\n }\n\n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 ;\n }\n }\n \n for(let index = 0 ; index < Number(numberOfGroups) ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater -= 2;\n groups[index] = 0;\n } \n \n else if (groups[index] > 0 && groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater -= 2;\n groups[index] = 0;\n } \n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < numberOfGroups; index++) {\n\n if (Number(groups[index]) == 1 && numberOfOneSeater > 0) {\n numberOfOneSeater--;\n groups[index] = 0 \n }\n\n else if(Number(groups[index]) == 1 && numberOfOneSeater == 0 && numberOfTwoSeater > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0\n }\n \n else if (Number(groups[index]) != 1 && numberOfTwoSeater > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 \n }\n\n if (Number(groups[index]) != 1 && numberOfTwoSeater ==0) {\n groups[index] = 2 \n }\n }\n \n for(let index = 0 ; index < numberOfGroups ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 ;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n }\n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 \n }\n }\n \n for(let index = 0 ; index < Number(numberOfGroups) ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 2 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 ;\n }\n\n if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n }\n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 ;\n }\n }\n \n for(let index = 0 ; index < Number(numberOfGroups) ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < numberOfGroups; index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 \n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0\n }\n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 \n }\n }\n \n for(let index = 0 ; index < numberOfGroups ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n }\n \n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) == 0){\n\n sum++\n }\n\n else if(Number(groups[index]) != 1 && Number(numberOfTwoSeater) == 0){\n\n sum +=2 \n }\n }\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] > 0 && groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < numberOfGroups; index++) {\n\n if (Number(groups[index]) == 1 && numberOfOneSeater > 0) {\n numberOfOneSeater--;\n groups[index] = 0 \n }\n\n else if(Number(groups[index]) == 1 && numberOfOneSeater == 0 && numberOfTwoSeater > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0\n }\n \n else if (Number(groups[index]) != 1 && numberOfTwoSeater > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 \n }\n\n else if (Number(groups[index]) != 1 && numberOfTwoSeater ==0) {\n groups[index] = 2 \n }\n }\n \n for(let index = 0 ; index < numberOfGroups ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] > 0 && groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 \n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0\n }\n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 \n }\n }\n \n for(let index = 0 ; index < Number(numberOfGroups) ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n sum = function(arr){\n return arr.reduce(function(a,b){\n return a + b\n }, 0);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 ;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n }\n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 ;\n }\n }\n \n for(let index = 0 ; index < Number(numberOfGroups) ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && numberOfOneSeater == 0 && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += Number(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n }\n \n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) == 0){\n\n sum++\n }\n\n else if(Number(groups[index]) != 2 && Number(numberOfTwoSeater) == 0){\n\n sum +=2 \n }\n }\n console.log(sum)\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && numberOfOneSeater == 0 && numberOfTwoSeater > 0) {\n\n numberOfOneSeater += 2;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += groups[index];\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n let numberOfTwoSeaterOccupiedByOnePerson = 0;\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfTwoSeaterOccupiedByOnePerson++;\n numberOfTwoSeater--;\n } \n \n if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeaterOccupiedByOnePerson > 0) {\n\n numberOfTwoSeaterOccupiedByOnePerson--;\n groups[index] = 0 ;\n } \n \n\n else if (groups[index] > 0 && groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n let oldNumberOfOneSeater = numberOfOneSeater;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n\n oldNumberOfOneSeater = numberOfOneSeater;\n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && oldNumberOfOneSeater > 1 && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfOneSeater++;\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = Number(inputString[0].split(\" \")[0]);\n let numberOfOneSeater = Number(inputString[0].split(\" \")[1]);\n let numberOfTwoSeater = Number(inputString[0].split(\" \")[2]);\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0;\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n if (groups[index] == 1 && numberOfOneSeater > 0) {\n \n numberOfOneSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] == 1 && !numberOfOneSeater && numberOfTwoSeater > 0) {\n\n numberOfTwoSeater--;\n groups[index] = 0;\n } \n \n else if (groups[index] > 0 && groups[index] != 1 && numberOfTwoSeater > 0) {\n \n numberOfTwoSeater--;\n groups[index] = 0;\n }\n \n }\n\n for (let index = 0; index < numberOfGroups; index++) {\n\n sum += parseInt(groups[index]);\n }\n\n console.log(sum);\n}"}, {"source_code": "/**\n * \nIn a small restaurant there are a tables for one person and b tables for two persons.\n\nIt it known that n groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, \nit is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person.\n If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.\n\nInput\nThe first line contains three integers n, a and b (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ 2·105) — the number of groups coming to the restaurant, \nthe number of one-seater and the number of two-seater tables.\n\nThe second line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 2) — the description of clients in chronological order.\n If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.\n\nOutput\nPrint the total number of people the restaurant denies service to.\n\nExamples\ninput\n4 1 2\n1 2 1 1\noutput\n0\ninput\n4 1 1\n1 1 2 1\noutput\n2\nNote\nIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. \nThe third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person,\n he is seated at the remaining seat at the two-seater table. Thus, all clients are served.\n\nIn the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, \nit occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. \nThe fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.\n */\n\n\nlet inputString = '';\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n let numberOfGroups = inputString[0].split(\" \")[0];\n let numberOfOneSeater = inputString[0].split(\" \")[1];\n let numberOfTwoSeater = inputString[0].split(\" \")[2];\n let groups = inputString[1].split(\" \")\n\n solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups)\n\n});\n\nfunction solution(numberOfGroups, numberOfOneSeater, numberOfTwoSeater, groups) {\n\n let sum = 0 ; \n let numberOfTwoSeaterOccupiedByOnePerson = 0;\n for (let index = 0; index < Number(numberOfGroups); index++) {\n\n if (Number(groups[index]) == 1 && Number(numberOfOneSeater) > 0) {\n numberOfOneSeater--;\n groups[index] = 0 ;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfOneSeater) == 0 && Number(numberOfTwoSeater) > 0){\n\n numberOfTwoSeaterOccupiedByOnePerson++;\n numberOfTwoSeater--;\n // groups[index] = 0;\n }\n\n else if(Number(groups[index]) == 1 && Number(numberOfTwoSeaterOccupiedByOnePerson) > 0 ){\n numberOfTwoSeaterOccupiedByOnePerson--;\n groups[index] = 0;\n\n }\n \n else if (Number(groups[index]) != 1 && Number(numberOfTwoSeater) > 0) {\n numberOfTwoSeater--;\n groups[index] = 0 ;\n }\n }\n \n for(let index = 0 ; index < Number(numberOfGroups) ; index ++){\n\n sum += Number(groups[index])\n }\n\n console.log(sum)\n}"}, {"source_code": "var data = readline().split(' ').map(function (x) { return parseInt(x); });\nvar guests = readline().split(' ').map(function (x) { return parseInt(x); });\n\nvar sTable = data[1];\nvar dTable = data[2];\n\nvar total = guests.reduce(function (a,b) {\n return parseInt(a)+parseInt(b);\n}, 0);\n\nfor (var g of guests) {\n if (g === 2) {\n if (dTable > 0) {\n dTable--;\n total -= g;\n }\n }\n if (g === 1) {\n if (sTable > 0) {\n sTable--;\n total -= g;\n } else if (dTable > 0) {\n dTable--;\n sTable++;\n total -= g;\n }\n }\n \n}\n\nprint(total);"}, {"source_code": "function GetAns(n, a, b, array){\n\tvar ans=0;\n\tvar tOne, tTwo, tTwoWithOne;\n\ttOne = a; tTwo = b; tTwoWithOne = 0;\n\tfor (var i=0;i0)\n\t\t\t\ttTwo--;\n\t\t\telse\n\t\t\t\tans+=2;\n\t\t}\n\t\telse{\n\t\t\tif (tOne>0)\n\t\t\t\ttOne--;\n\t\t\telse{\n\t\t\t\tif (tTwoWithOne>0) tTwoWithOne--;\n\t\t\t\telse\n\t\t\t\t\tif (tTwo>0){\n\t\t\t\t\t\ttTwo--;\n\t\t\t\t\t\ttTwoWithOne++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tans++;\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\n\nvar input = readline().split(' ');\nvar n=+input[0], a=+input[1], b=+input[2];\nvar array=readline().split(' ');\nprint(GetAns(n,a,b,array));"}], "src_uid": "e21e768dbb2e5f72873dc1c7de4879fd"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.Let's define a substring as a contiguous subsegment of a string. For example, \"acab\" is a substring of \"abacaba\" (it starts in position $$$3$$$ and ends in position $$$6$$$), but \"aa\" or \"d\" aren't substrings of this string. So the substring of the string $$$s$$$ from position $$$l$$$ to position $$$r$$$ is $$$s[l; r] = s_l s_{l + 1} \\dots s_r$$$.You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $$$s[l; r] = s_r s_{r - 1} \\dots s_l$$$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.If it is impossible to reverse some substring of the given string to obtain a string that is less, print \"NO\". Otherwise print \"YES\" and any suitable substring.String $$$x$$$ is lexicographically less than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x \\ne y$$$), or there exists such $$$i$$$ ($$$1 \\le i \\le min(|x|, |y|)$$$), that $$$x_i < y_i$$$, and for any $$$j$$$ ($$$1 \\le j < i$$$) $$$x_j = y_j$$$. Here $$$|a|$$$ denotes the length of the string $$$a$$$. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.", "output_spec": "If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print \"NO\". Otherwise print \"YES\" and two indices $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) denoting the substring you have to reverse. If there are multiple answers, you can print any.", "sample_inputs": ["7\nabacaba", "6\naabcfg"], "sample_outputs": ["YES\n2 5", "NO"], "notes": "NoteIn the first testcase the resulting string is \"aacabba\"."}, "positive_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n\n var n = read.number();\n var s = read.arr();\n\n for(var i = 1; i < n; i ++) {\n if(s[i - 1] > s[i]) {\n print('YES');\n print((i) + ' ' + (i + 1));\n return;\n }\n }\n\n print('NO');\n\n\n\n}());"}], "negative_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n\n var n = read.number();\n var s = read.arr();\n\n for(var i = 1; i < n; i ++) {\n if(s[i - 1] > s[i]) {\n print('YES');\n print((i) + ' ' + (i + 1));\n }\n }\n\n print('NO');\n\n\n\n}());\n"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var s = read.arr();\n\n for(var i = 0; i < n; i ++) {\n for(var j = i ; j < n; j++) {\n if(s[i] > s[j]) {\n print('YES');\n print(i + ' ' + j)\n return;\n }\n }\n }\n print('NO');\n\n //abacaba\n //aacabba\n\n //abacaba\n //aabcaba\n}());\n"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var s = read.arr();\n\n for(var i = 0; i < n; i ++) {\n for(var j = i ; j < n; j++) {\n if(s[i] > s[j]) {\n print('YES');\n return;\n }\n }\n }\n print('NO');\n}());\n"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n\n var n = read.number();\n var s = read.arr();\n\n for(var i = 2; i < n; i ++) {\n if(s[i] < s[i - 1]) {\n print('YES');\n print((i) + ' ' + (i + 1)); \n return;\n }\n }\n\n print('NO');\n\n\n\n}());\n"}], "src_uid": "d45f775613e701bbdaa4e457e6e189e2"} {"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 — 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$$$) — 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$$$) — 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 — 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": "function solve() {\n var n = readInt()\n var arr = readIntArray()\n\n var sumArr = []\n var i\n var curSum = arr[0]\n var max = arr[0]\n for(i=1;i max) {\n max = arr[i]\n }\n }\n\n var seen = new Set(sumArr)\n sumArr.unshift(arr[0])\n var arrSeen = new Set(arr)\n var j\n var k\n for(j=1;j max) {\n max = arr[i]\n }\n }\n\n var seen = new Array(max + 1)\n for(i=1;i max) {\n max = arr[i]\n }\n }\n\n var seen = new Array(max + 1)\n for(i=1;i 0) {\n count += mark[n]\n mark[n] = 0\n }\n }\n }\n }\n print(count)\n}\n\nvar tc = Number(readline())\nwhile (tc--) {\n var n = Number(readline())\n var arr = readline().split(\" \").map(function(x) { return +x })\n countSpecialElements(n,arr)\n}"}, {"source_code": "'use strict';\n\nconst parseProblem = (line, problem) => {\n if (!problem.T || problem.T === 0) {\n problem.T = parseInt(line);\n return problem;\n }\n\n const cases = problem.cases;\n\n if (cases.length === 0 || cases[cases.length - 1].arr) {\n cases.push({\n t: line\n });\n } else {\n cases[cases.length - 1].arr = line;\n }\n\n const isProcessing = cases.length < problem.T || !cases[cases.length - 1].arr;\n problem.isProcessing = isProcessing;\n\n return problem;\n};\n\nconst solve = data => {\n const {t, arr} = data;\n const a = arr.split(' ').map(i => +i);\n let count = 0;\n let set = [];\n\n for(let i = 0; i < t; i++) { // a[i]\n let sum = a[i];\n for(let j = i + 1; j < t; j++) {\n sum += a[j];\n if(sum > t) break;\n set[sum] = 1;\n }\n }\n\n for(let i = 0; i < t; i++) {\n if(set[a[i]]) count++;\n }\n \n return count;\n}\n\nconst solveCases = cases => {\n for (let index = 0; index < cases.length; index++) {\n const result = solve(cases[index]);\n console.log(result);\n }\n};\n\nconst main = () => {\n const readline = require('readline');\n\n let problem = {\n T: 0,\n cases: [],\n isProcessing: true\n };\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n rl.on('line', line => {\n problem = parseProblem(line, problem);\n\n if (!problem.isProcessing) {\n rl.close();\n }\n }).on('close', () => {\n solveCases(problem.cases);\n process.exit(0);\n });\n};\n\nif (!module.parent) {\n main();\n}"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\n\nvar input = []\nrl.on('line', function(line){\n input.push(line);\n})\n\nrl.on(\"close\", ContestResponse); \n\n\nfunction ContestResponse(){\n let index = 0;\n let nCases = +input[index];\n for (let c = 0; c < nCases; c++){\n index += 2;\n let cnt = 0;\n let map = {};\n let arr = input[index].split(\" \").map((val)=>+val);\n for (let i = 0; i < arr.length - 1; i++){\n let sum = arr[i];\n for (let j = i + 1; j < arr.length; j++){\n sum += arr[j];\n if (sum > arr.length)\n break;\n map[sum] = 1;\n }\n }\n for (let i = 0; i < arr.length; i++)\n if (arr[i] in map)\n cnt++;\n console.log(cnt);\n }\n}"}], "negative_code": [{"source_code": "function countSpecialElements(len,arr) {\n if (len < 3) {\n print(0)\n return\n }\n var prefixSum = new Array(len)\n var mx = prefixSum[0] = arr[0]\n for (var i=1; i 0) {\n ++count\n --mark[n]\n }\n }\n }\n }\n print(count)\n}\n\nvar tc = Number(readline())\nwhile (tc--) {\n var n = Number(readline())\n var arr = readline().split(\" \").map(function(x) { return +x })\n countSpecialElements(n,arr)\n}"}, {"source_code": "function solve() {\n var n = readInt()\n var arr = readIntArray()\n\n var sumArr = []\n var i\n var curSum = arr[0]\n for(i=1;i max) {\n max = arr[i]\n }\n }\n\n var seen = new Set(sumArr)\n sumArr.unshift(arr[0])\n var arrSeen = new Set(arr)\n var j\n var k\n for(j=1;j 0) {\n ++count\n --mark[n]\n }\n }\n }\n }\n print(count)\n}\n\nvar tc = Number(readline())\nwhile (tc--) {\n var n = Number(readline())\n var arr = readline().split(\" \").map(function(x) { return +x })\n countSpecialElements(arr)\n}"}, {"source_code": "function countSpecialElements(len,arr) {\n if (len < 3) {\n print(0)\n return\n }\n var prefixSum = new Array(len)\n var mx = prefixSum[0] = arr[0]\n for (var i=1; i 0) {\n count += mark[n]\n //--mark[n]\n }\n }\n }\n }\n print(count)\n}\n\nvar tc = Number(readline())\nwhile (tc--) {\n var n = Number(readline())\n var arr = readline().split(\" \").map(function(x) { return +x })\n countSpecialElements(n,arr)\n}"}], "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 ≤ k ≤ n ≤ 100) — 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": "var input = readline().split(\" \").map(x=>parseInt(x));\nvar bz = input[0];\nvar lp = input[1];\nvar banner = readline().split(\"\");\nvar middle = Math.ceil(banner.length/2);\nif(middle>=lp && lp < banner.length){\n for(var i=lp-1; i>0; i--){\n print('LEFT');\n lp--; \n }\n}else if(middle1){\n for(var j=lp; j=0; l--){\n print(\"PRINT\",banner[l]);\n if(banner[l-1] !== undefined){\n print(\"LEFT\")\n }\n } \n}"}, {"source_code": "function main() {\n\n var temp = readline().split(' ').map(Number);\n var n = temp[0],\n k = temp[1];\n\n var arr = readline();\n\n var res = [];\n\n if (k - 1 < n - k) {\n for (var i = 0; i < k - 1; i++) {\n res.push(\"LEFT\");\n }\n for (var j = 0; j < n - 1; j++) {\n res.push(\"PRINT \" + arr[j]);\n res.push(\"RIGHT\");\n }\n res.push(\"PRINT \" + arr[n - 1]);\n } else {\n for (var i = 0; i < n - k; i++) {\n res.push(\"RIGHT\");\n }\n for (var j = n-1; j >0; j--) {\n res.push(\"PRINT \" + arr[j]);\n res.push(\"LEFT\");\n }\n res.push(\"PRINT \" + arr[0]);\n }\n\n print(res.join(\"\\n\"));\n}\n\nmain();"}], "negative_code": [{"source_code": "var input = readline().split(\" \").map(x=>parseInt(x));\nvar bz = input[0];\nvar lp = input[1];\nvar banner = readline().split(\"\");\nvar middle = Math.ceil(banner.length/2);\nif(middle>lp && lp < banner.length){\n for(var i=lp; i>0; i--){\n print('LEFT');\n lp--; \n }\n}else if(middle<=lp && lp>1){\n for(var j=lp; j=0; l--){\n print(\"PRINT\",banner[l]);\n if(banner[l-1] !== undefined){\n print(\"LEFT\")\n }\n } \n}"}, {"source_code": "var input = readline().split(\" \").map(x=>parseInt(x));\nvar bz = input[0];\nvar lp = input[1];\nvar banner = readline().split(\"\");\nvar middle = Math.ceil(banner.length/2);\nif(middle>lp && lp < banner.length){\n for(var i=lp-1; i>0; i--){\n print('LEFT');\n lp--; \n }\n}else if(middle<=lp && lp>1){\n for(var j=lp; j=0; l--){\n print(\"PRINT\",banner[l]);\n if(banner[l-1] !== undefined){\n print(\"LEFT\")\n }\n } \n}"}, {"source_code": "function main() {\n\n var temp = readline().split(' ').map(Number);\n var n = temp[0],\n k = temp[1];\n\n var arr = readline();\n\n var res = [];\n\n if (k - 1 < n - k) {\n for (var i = 0; i < k - 1; i++) {\n res.push(\"LEFT\");\n }\n for (var j = 0; j < n - 1; j++) {\n res.push(\"PRINT \" + arr[j]);\n res.push(\"RIGHT\");\n }\n res.push(\"PRINT \" + arr[n - 1]);\n } else {\n for (i = 0; i < n - k; i++) {\n res.push(\"RIGHT\");\n }\n for (j = 0; j < n - 1; j++) {\n res.push(\"PRINT \" + arr[j]);\n res.push(\"LEFT\");\n }\n res.push(\"PRINT \" + arr[0]);\n }\n\n print(res.join(\"\\n\"));\n}\n\nmain();"}], "src_uid": "e3a03f3f01a77a1983121bab4218c39c"} {"nl": {"description": "Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.More formally, we have two permutations, p and s of numbers from 1 to n. We can swap pi and pj, by paying |i - j| coins for it. Find and print the smallest number of coins required to obtain permutation s from permutation p. Also print the sequence of swap operations at which we obtain a solution. ", "input_spec": "The first line contains a single number n (1 ≤ n ≤ 2000) — the length of the permutations. The second line contains a sequence of n numbers from 1 to n — permutation p. Each number from 1 to n occurs exactly once in this line. The third line contains a sequence of n numbers from 1 to n — permutation s. Each number from 1 to n occurs once in this line.", "output_spec": "In the first line print the minimum number of coins that you need to spend to transform permutation p into permutation s. In the second line print number k (0 ≤ k ≤ 2·106) — the number of operations needed to get the solution. In the next k lines print the operations. Each line must contain two numbers i and j (1 ≤ i, j ≤ n, i ≠ j), which means that you need to swap pi and pj. It is guaranteed that the solution exists.", "sample_inputs": ["4\n4 2 1 3\n3 2 4 1"], "sample_outputs": ["3\n2\n4 3\n3 1"], "notes": "NoteIn the first sample test we swap numbers on positions 3 and 4 and permutation p becomes 4 2 3 1. We pay |3 - 4| = 1 coins for that. On second turn we swap numbers on positions 1 and 3 and get permutation 3241 equal to s. We pay |3 - 1| = 2 coins for that. In total we pay three coins."}, "positive_code": [{"source_code": "res1 = [],res2 = [];\nind = [], need = [];\na = [],b = [];\nans = 0;\nvar n,i;\n\nfunction _swap(i, j)\n {\n //swap(ind[a[i]],ind[a[j]]);\n var temp = ind[a[i]];\n ind[a[i]] = ind[a[j]];\n ind[a[j]] = temp;\n\n ans += Math.abs(j-i);\n res1.push(i);\n res2.push(j);\n temp = a[i];\n a[i] = a[j];\n a[j] = temp;\n }\n\nfunction solve(i, j)\n {\n if (need[a[i]] >= j)\n {\n _swap(i,j);\n return;\n }\n for (var k=i;i<=j;k++)\n if (need[a[k]] >= j)\n {\n _swap(k,j);\n solve(i,k);\n return;\n }\n }\n\nfunction main()\n {\n\n n = +readline();\n a = readline().split(\" \").map(Number);\n b = readline().split(\" \").map(Number);\n for (var i = a.length; i > 0; --i) {\n a[i] = a[i-1];\n b[i] = b[i-1];\n ind[a[i]]=i;\n need[b[i]]=i;\n }\n\n for (i=1;i<=n;i++)\n if (a[i] != b[i])\n solve(i,ind[b[i]]);\n\n //cout<=l && (+i)<=r){\r\n myArr.push(+i);\r\n }\r\n }\r\n myArr = myArr.sort((a,b) => a-b);\r\n var count = 0, left = k;\r\n for (var i of myArr){\r\n if (left >= i){\r\n count++;\r\n left -= i;\r\n }\r\n else{\r\n break;\r\n }\r\n }\r\n print(count);\r\n}"}, {"source_code": "var t = readline();\r\nwhile(t--){\r\n var y = readline().split(\" \");\r\n var n = parseInt(y[0]), l = parseInt(y[1]), \r\n r = parseInt(y[2]), k = parseInt(y[3]);\r\n var arr = readline().split(\" \");\r\n \r\n var new_arr = [];\r\n for(var i = 0; i < n; i++){\r\n arr[i] = parseInt(arr[i]);\r\n if(arr[i] >= l && arr[i] <= r)\r\n new_arr.push(parseInt(arr[i]));\r\n }\r\n \r\n var ans = 0;\r\n new_arr.sort(function(a, b){return a - b;});\r\n for(var i = 0; i < new_arr.length; i++){\r\n if(new_arr[i] <= k){\r\n k -= new_arr[i];\r\n ans++;\r\n }else{\r\n break;\r\n }\r\n }\r\n print(ans);\r\n}"}, {"source_code": "var t = readline();\r\nwhile(t--){\r\n var y = readline().split(\" \");\r\n var n = parseInt(y[0]), l = parseInt(y[1]), \r\n r = parseInt(y[2]), k = parseInt(y[3]);\r\n var arr = readline().split(\" \");\r\n \r\n var new_arr = [];\r\n for(var i = 0; i < n; i++){\r\n arr[i] = parseInt(arr[i]);\r\n if(arr[i] >= l && arr[i] <= r)\r\n new_arr.push(parseInt(arr[i]));\r\n }\r\n \r\n var ans = 0;\r\n new_arr.sort(function(a, b){return a - b;});\r\n for(var i = 0; i < new_arr.length; i++){\r\n if(new_arr[i] <= k){\r\n k -= new_arr[i];\r\n ans++;\r\n }else{\r\n break;\r\n }\r\n }\r\n print(ans);\r\n}"}, {"source_code": "var t = parseInt(readline());\r\n\r\n function solve() {\r\n var input = readline()\r\n .split(\" \")\r\n .map((data) => +data)\r\n var n = input[0]\r\n var l = input[1]\r\n var r = input[2]\r\n var k = input[3]\r\n var a = readline()\r\n .split(\" \")\r\n .map((data) => +data).sort((a, b) => {\r\n if (a > b) {\r\n return 1;\r\n } else if (a < b) {\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n })\r\n\r\n var price = 0;\r\n var count = 0;\r\n\r\n for (var i = 0; i < n; i++) {\r\n var lastprice = price + a[i]\r\n if (lastprice <= k) {\r\n if (a[i] >= l && a[i] <= r) {\r\n price += a[i]\r\n count++\r\n }\r\n }\r\n if (a[i] > r) {\r\n break;\r\n }\r\n }\r\n print(count)\r\n }\r\n\r\n while (t--) {\r\n solve()\r\n }"}, {"source_code": "let i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL).filter(line => line) /*your input text, split by lines*/\n const lineNumbers = lines.slice(1).map((line) => line.split(' ').map(x => +x))\n for (let i = 0; i < lineNumbers.length; i+=2) {\n let [n, l, r, k] = lineNumbers[i];\n const sortedPrices = lineNumbers[i+1].sort((a, b) => a-b);\n let nOfBars = 0;\n sortedPrices.forEach(price => {\n if (price <= r && price >= l && k >= price) {\n nOfBars++;\n k-=price;\n }\n })\n console.log(nOfBars)\n }\n})"}, {"source_code": "data = \"\";\r\n\r\nprocess.stdin.on(\"data\", (c) => (data += c));\r\nprocess.stdin.on(\"end\", () => {\r\n let [_, ...input] = data\r\n .trim()\r\n .split(/\\n/)\r\n .map((el) =>\r\n el\r\n .trim()\r\n .split(\" \")\r\n .map((el) => +el.trim())\r\n );\r\n\r\n for (let i = 0; i < input.length; i += 2) {\r\n let sum = 0;\r\n let result = [];\r\n\r\n let [_, l, r, k] = input[i];\r\n let arr = input[i + 1].sort((a, b) => a - b);\r\n\r\n arr = arr.filter((el) => el >= l && el <= r && el <= k);\r\n\r\n arr.forEach((el) => {\r\n sum += el;\r\n if (sum <= k) result.push(el);\r\n });\r\n\r\n console.log(result.length);\r\n }\r\n});\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n let t, n, l, r, k, arr;\r\n\r\n t = parseInt(readline());\r\n while(t--) {\r\n [n, l, r, k] = readline().split(' ').map(x => parseInt(x));\r\n arr = readline().split(' ').map(x => parseInt(x));\r\n console.log(solve(n, l, r, k, arr));\r\n }\r\n}\r\n\r\nfunction solve(n, l, r, k, arr) {\r\n let sum = 0, cnt = 0;\r\n arr.sort((a, b) => a - b);\r\n for(let i = 0; i < n; i++) {\r\n if(arr[i] < l || arr[i] > r || sum + arr[i] > k) continue;\r\n cnt++;\r\n sum += arr[i];\r\n }\r\n return cnt;\r\n}"}, {"source_code": "var readline = require(\"readline\");\r\n\r\nvar input = [];\r\n\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\n\r\n\r\nrl.on(\"line\", function (cmd) {\r\n input.push(cmd);\r\n});\r\n\r\nrl.on(\"close\", function (cmd) {\r\n let a = [], b = [];\r\n let count = input.shift();\r\n\r\n for(let i = 0; i < count; i++){\r\n\r\n a = input.shift().split(' ');\r\n b = input.shift().split(' ');\r\n\r\n let n = 0, l = +a[1], r = +a[2], k = +a[3], min = Infinity;\r\n\r\n b = b.filter(elem => (+elem >= l && +elem <= r))\r\n b.sort(sort);\r\n for(let j = 0; k >= 0;j++){\r\n k -= b[j];\r\n n++;\r\n }\r\n\r\n console.log(--n);\r\n }\r\n\r\n function sort(a,b){\r\n return +a - +b;\r\n }\r\n process.exit(0);\r\n});"}, {"source_code": "data = \"\";\r\n \r\nprocess.stdin.on(\"data\", (c) => (data += c));\r\nprocess.stdin.on(\"end\", () => {\r\n let [_, ...input] = data\r\n .trim()\r\n .split(/\\n/)\r\n .map((el) =>\r\n el\r\n .trim()\r\n .split(\" \")\r\n .map((el) => +el.trim())\r\n );\r\n \r\n for (let i = 0; i < input.length; i += 2) {\r\n let sum = 0;\r\n let result = [];\r\n \r\n let [_, l, r, k] = input[i];\r\n let arr = input[i + 1].sort((a, b) => a - b);\r\n \r\n arr = arr.filter((el) => el >= l && el <= r && el <= k);\r\n \r\n arr.forEach((el) => {\r\n sum += el;\r\n if (sum <= k) result.push(el);\r\n });\r\n \r\n console.log(result.length);\r\n }\r\n});"}, {"source_code": "const { mainModule } = require(\"process\");\r\nvar readline = require(\"readline\");\r\n\r\nvar input = [];\r\n\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\n\r\nrl.on(\"line\", function (cmd) {\r\n input.push(cmd);\r\n});\r\n\r\nrl.on(\"close\", function () {\r\n let result = [];\r\n for (let i = 1; i < input.length; i += 2) {\r\n let temp = input[i].split(\" \").map((el) => +el);\r\n let a = input[i + 1].split(\" \").map((el) => +el);\r\n let l = a.length;\r\n for (let j = 0; j < l; ++j) {\r\n if (a[j] < temp[1] || a[j] > temp[2]) {\r\n a.splice(j, 1);\r\n j--;\r\n l--;\r\n }\r\n }\r\n let sum = 0;\r\n let counter = -1;\r\n while (sum <= temp[3]) {\r\n let x = Math.min(...a);\r\n sum += x;\r\n a.splice(a.indexOf(x), 1);\r\n counter++;\r\n }\r\n result.push(counter);\r\n }\r\n for (let k = 0; k < result.length; ++k) {\r\n console.log(result[k]);\r\n }\r\n process.exit(0);\r\n});"}, {"source_code": "process.stdin.setEncoding('utf-8')\r\nconst readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n }\r\n)\r\n\r\nlet count = -1\r\nlet inputArr = []\r\n\r\nrl.on('line', data => {\r\n if (count === -1) {\r\n count = +data * 2\r\n } else if (count !== 0) {\r\n inputArr.push(data.trim())\r\n count--\r\n }\r\n // max number 2^(53) - 1 ~~ 10^(15)\r\n if (count === 0) {\r\n inputArr = inputArr.map(i => i.split(' ').map(j => +j))\r\n main()\r\n process.exit(0)\r\n }\r\n})\r\n\r\n\r\nfunction solve([n, l, r, k], arr) {\r\n let ans = 0, sum = 0\r\n arr.sort((a, b) => a - b)\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] > r) {\r\n break\r\n }\r\n if (arr[i] >= l) {\r\n sum += arr[i]\r\n if (sum > k) {\r\n break\r\n }\r\n ans++\r\n }\r\n }\r\n console.log(ans)\r\n}\r\n\r\nfunction main() {\r\n for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])\r\n}"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, left, right, k] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, left, right, k, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, left, right, k, arr) {\n arr = arr.filter(x => x >= left && x <= right)\n .sort((a, b) => a - b)\n// console.log(arr)\n let now = 0\n let count = 0\n for (let i = 0; i < arr.length; i++) {\n if (now + arr[i] <= k) {\n now += arr[i]\n count++\n } else {\n break\n }\n }\n return count\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar L = nextInt();\r\n\t\tvar R = nextInt();\r\n\t\tvar K = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tlist.sort(function(a,b){\r\n\t\t\treturn a - b;\r\n\t\t});\r\n\t\tvar output = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tif(L <= list[i] && list[i] <= R){\r\n\t\t\t\tif(list[i] <= K){\r\n\t\t\t\t\tK -= list[i];\r\n\t\t\t\t\toutput++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}], "negative_code": [{"source_code": "let data = \"\";\r\n\r\nfunction solve() {\r\n let [_, ...arr] = data\r\n .trim()\r\n .split(/ |\\n/)\r\n .map((el) => el.trim())\r\n .map((el) => +el);\r\n\r\n arr = arr.sort((a, b) => a - b);\r\n let firstSum = 0;\r\n\r\n if (arr[1] === 10374) {\r\n console.log(476226);\r\n return 0;\r\n }\r\n\r\n for (let i = 0; i < arr.length; i++) {\r\n firstSum += arr[i];\r\n if (firstSum === arr[i] * arr.length) {\r\n console.log(firstSum);\r\n return 0;\r\n }\r\n }\r\n\r\n function gcd_two_numbers(x, y) {\r\n while (y) {\r\n let t = y;\r\n y = x % y;\r\n x = t;\r\n }\r\n return x;\r\n }\r\n\r\n let sum = 0;\r\n let counter = 0;\r\n let bigNum = 0;\r\n let eachGcd = 0;\r\n let divansArray = [];\r\n const firstArray = arr.length;\r\n\r\n for (let i = arr.length - 1; i >= 0; i--) {\r\n sum = arr[i];\r\n\r\n for (let i = arr.length - 1; i >= 0; i--) {\r\n counter += gcd_two_numbers(sum, arr[i]);\r\n\r\n if (i === 0) {\r\n if (counter > bigNum || counter === bigNum) {\r\n bigNum = counter;\r\n eachGcd = sum;\r\n }\r\n\r\n counter = 0;\r\n }\r\n }\r\n }\r\n\r\n for (let i = 0; i < arr.length; i++)\r\n if (arr[i] === eachGcd) divansArray.push(arr[i]);\r\n\r\n function result(el) {\r\n let gcd = 0;\r\n bigNum = 0;\r\n counter = 0;\r\n\r\n for (let i = arr.length - 1; i >= 0; i--) {\r\n if (el === arr[i]) {\r\n arr.splice(i, 1);\r\n continue;\r\n }\r\n\r\n counter += gcd_two_numbers(el, arr[i]);\r\n\r\n if (counter > bigNum) {\r\n bigNum = counter;\r\n gcd = arr[i];\r\n }\r\n\r\n if (arr[i] === arr[i - 1]) {\r\n counter = counter;\r\n } else {\r\n counter = 0;\r\n }\r\n }\r\n\r\n return gcd;\r\n }\r\n\r\n for (let i = 0; i <= firstArray; i++) {\r\n result(eachGcd);\r\n\r\n for (let i = 0; i < arr.length; i++)\r\n if (arr[i] === result(eachGcd)) divansArray.push(arr[i]);\r\n\r\n eachGcd = result(eachGcd);\r\n }\r\n\r\n let arrResult = [divansArray[0]];\r\n\r\n for (let i = 0; i < divansArray.length; i++) {\r\n if (i === divansArray.length - 1) continue;\r\n\r\n if (\r\n gcd_two_numbers(divansArray[0], divansArray[i + 1]) === 1 ||\r\n gcd_two_numbers(divansArray[0], divansArray[i - 1]) === 1\r\n ) {\r\n arrResult.push(1);\r\n } else {\r\n arrResult.push(gcd_two_numbers(divansArray[i], divansArray[i + 1]));\r\n }\r\n }\r\n\r\n console.log(arrResult.reduce((a, b) => a + b, 0));\r\n}\r\n\r\nprocess.stdin.on(\"data\", (c) => (data += c));\r\nprocess.stdin.on(\"end\", solve);\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n let t, n, l, r, k, arr;\r\n\r\n t = parseInt(readline());\r\n while(t--) {\r\n [n, l, r, k] = readline().split(' ').map(x => Number(x));\r\n arr = readline().split(' ').map(x => Number(x));\r\n console.log(solve(n, l, r, k, arr));\r\n }\r\n}\r\n\r\nfunction solve(n, l, r, k, arr) {\r\n let sum = 0, cnt = 0;\r\n arr.sort();\r\n for(let i = 0; i < n; i++) {\r\n if(arr[i] < l || arr[i] > r || sum >= k) continue;\r\n cnt++;\r\n sum += arr[i];\r\n }\r\n return cnt;\r\n}"}], "src_uid": "f577695d39a11e8507681f307677c883"} {"nl": {"description": "Let's say string $$$s$$$ has period $$$k$$$ if $$$s_i = s_{i + k}$$$ for all $$$i$$$ from $$$1$$$ to $$$|s| - k$$$ ($$$|s|$$$ means length of string $$$s$$$) and $$$k$$$ is the minimum positive integer with this property.Some examples of a period: for $$$s$$$=\"0101\" the period is $$$k=2$$$, for $$$s$$$=\"0000\" the period is $$$k=1$$$, for $$$s$$$=\"010\" the period is $$$k=2$$$, for $$$s$$$=\"0011\" the period is $$$k=4$$$.You are given string $$$t$$$ consisting only of 0's and 1's and you need to find such string $$$s$$$ that: String $$$s$$$ consists only of 0's and 1's; The length of $$$s$$$ doesn't exceed $$$2 \\cdot |t|$$$; String $$$t$$$ is a subsequence of string $$$s$$$; String $$$s$$$ has smallest possible period among all strings that meet conditions 1—3. Let us recall that $$$t$$$ is a subsequence of $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $$$t$$$=\"011\" is a subsequence of $$$s$$$=\"10101\".", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains string $$$t$$$ ($$$1 \\le |t| \\le 100$$$) consisting only of 0's and 1's.", "output_spec": "Print one string for each test case — string $$$s$$$ you needed to find. If there are multiple solutions print any one of them.", "sample_inputs": ["4\n00\n01\n111\n110"], "sample_outputs": ["00\n01\n11111\n1010"], "notes": "NoteIn the first and second test cases, $$$s = t$$$ since it's already one of the optimal solutions. Answers have periods equal to $$$1$$$ and $$$2$$$, respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string $$$s$$$. String $$$s$$$ has period equal to $$$1$$$."}, "positive_code": [{"source_code": "var ttt = parseInt(readline());\n\nfunction mapper(s) { return +s; }\n \nfor(var qq = 0; qq < ttt; qq++) {\n var t = readline();\n var tl = t.length;\n \n if (tl <= 2) {\n print(t);\n } else {\n var same = true;\n for(var i = 0; i < tl - 1; i++) {\n if (t[i] !== t[i+1]) {\n same = false;\n break;\n }\n }\n \n if (same) {\n print(t);\n } else {\n var ch = t[0] === '0' ? '01' : '10';\n var s = ch.repeat(tl);\n print(s);\n }\n }\n}"}, {"source_code": "const readline = require('readline');\n\nlet input = [];\n\nconst rl = readline.createInterface({\n\tinput: process.stdin,\n\toutput: process.stdout,\n});\n\nrl.on('line', lineInput => {\n\tinput.push(lineInput);\n});\n\nrl.on('close', () => {\n\tconst test = parseInt(input[0]);\n\tfor (let i=0; i < test; i++) {\n\t\tlet t = input[i+1].split('');\n\t\tconsole.log(solution(t));\n\t}\n});\n\nfunction solution(t) {\n\tfor (let i = 1; i < t.length; i++) {\n\t\tif (t[i] !== t[i-1]) {\n\t\t\treturn constructString(t.length-1)\n\t\t}\n\t}\n\treturn t.join('');\n}\nfunction constructString(l) {\n\tlet str = '01'\n\tfor (let j = 0; j < l; j++) {\n\t\tstr += '01';\n\t}\n\treturn str;\n}"}, {"source_code": "const processData = (lines) => {\n const nums = +lines[0]\n for (let i =0; i +x)\n\n const sum = nums.reduce((r, x) => r+x, 0)\n if (sum === 0 || sum === nums.length) {\n console.log(nums.join(''))\n } else {\n let res = ''\n let i = nums[0] === '0' ? 1 : 0\n for (const ch of nums) {\n const awaitingChar = i%2 === 0 ? '1' : '0'\n if (awaitingChar == ch) {\n res += ch\n i+= 1\n } else {\n res += awaitingChar + ch\n i+= 2\n }\n }\n console.log(res)\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin; \n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.replace(/\\s*$/, '')\n .split('\\n')\n .map(str => str.replace(/\\s*$/, ''));\n main();\n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction solve(s) {\n let zero = 0;\n let one = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] == 0) zero++;\n else one++;\n }\n if (zero === 0 || one === 0) return s;\n let s1 = s[0];\n for (let i = 1; i < s.length; i++) {\n if (s[i] === s[i - 1]) {\n let insert = s[i] == '1' ? '0' : '1';\n s1 += insert;\n }\n s1 += s[i];\n }\n return s1;\n}\n\nfunction main() {\n const t = parseInt(readLine());\n for (let i = 0; i < t; i++) {\n let s = readLine();\n // let a = readLine().split(' ').map((val) => parseInt(val));\n let res = solve(s);\n console.log(res);\n }\n //process.stdout.write(\"hello: \");\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let range = readline();\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let range = readline();\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction main() {\n let range = readline();\n for(let r=0;r {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\nfunction ceilPow2(n) {\n let x = 0\n while ((1 << x) < n) x++\n return x\n}\n\nclass SegTree {\n constructor(nOrArray, options) {\n const { op, e } = options\n this.op = op\n this.e = e\n const v = Array.isArray(nOrArray) ? nOrArray : Array(nOrArray).fill(0).map(() => e())\n\n const n = v.length\n const log = ceilPow2(n)\n const size = 1 << log\n const d = Array(2 * size)\n this.n = n\n this.log = log\n this.size = size\n this.d = d\n\n for (let i = 0; i < d.length; i++) {\n d[i] = e()\n }\n for (let i = 0; i < n; i++) {\n d[size + i] = v[i]\n }\n for (let i = size - 1; i >= 1; i--) {\n this.update(i)\n }\n }\n set(p, x) {\n p += this.size\n this.d[p] = x\n for (let i = 1; i <= this.log; i++) this.update(p >> i)\n }\n get(p) {\n return this.d[p + this.size]\n }\n prod(l, r) {\n const { size, d, op, e } = this\n let sml = e(), smr = e()\n l += size\n r += size\n\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++])\n if (r & 1) smr = op(d[--r], smr)\n l >>= 1\n r >>= 1\n }\n return op(sml, smr)\n }\n allProd() {\n return this.d[1]\n }\n maxRight(l, f) {\n const { n, size, d, op, e} = this\n if (l == n) return n\n l += size\n let sm = e()\n do {\n while (l % 2 == 0) l >>= 1\n if (!f(op(sm, d[l]))) {\n while (l < size) {\n l = (2 * l)\n if (f(op(sm, d[l]))) {\n sm = op(sm, d[l])\n l++\n }\n }\n return l - size\n }\n sm = op(sm, d[l])\n l++\n } while ((l & -l) != l)\n return n\n }\n minLeft(r, f) {\n if (r == 0) return 0\n const { size, d, op, e} = this\n r += size\n let sm = e()\n do {\n r--\n while (r > 1 && (r % 2)) r >>= 1\n if (!f(op(d[r], sm))) {\n while (r < size) {\n r = (2 * r + 1)\n if (f(op(d[r], sm))) {\n sm = op(d[r], sm)\n r--\n }\n }\n return r + 1 - size\n }\n sm = op(d[r], sm)\n } while ((r & -r) != r)\n return 0\n }\n\n update(k) {\n const { d, op } = this\n d[k] = op(d[2 * k], d[2 * k + 1])\n }\n}\n\nfunction solve(n, arr) {\n let ok = 1\n const map = arr.reduce((o, x) => {\n // o[x] = 1\n o[x] = (o[x] || 0) + 1\n if (o[x] > 1) {\n ok = false\n }\n return o\n }, {})\n if (!ok) return -1\n const dp = Array(n + 1).fill(0)\n for (let i = 1; i <= n; i++) {\n if (!map[i]) {\n dp[i] = 1 // able to be selected\n }\n }\n const s = new SegTree(dp, {\n op: Math.max,\n e: () => -Infinity,\n })\n const r = Array(n)\n let p = n - 1\n for (let i = arr.length - 1; i >= 0; i--) {\n const x = arr[i]\n const j = s.minLeft(x, v => v === 0) - 1\n if (j < 1) return -1\n s.set(j, 0)\n r[p--] = x\n r[p--] = j\n }\n return r.join(' ')\n}\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction _defineProperty(obj, key, value) {\r\n if (key in obj) {\r\n Object.defineProperty(obj, key, {\r\n value: value,\r\n enumerable: true,\r\n configurable: true,\r\n writable: true\r\n });\r\n } else {\r\n obj[key] = value;\r\n }\r\n\r\n return obj;\r\n}\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns();\r\n const set = new Set(a),\r\n tr = new BinarySearchTree();\r\n if (set.size !== n / 2) return -1;\r\n for (let i = 1; i <= n; i++) {\r\n if (set.has(i)) continue;\r\n tr.insert(i);\r\n }\r\n const res = new Array(n);\r\n for (let i = n - 2; i >= 0; i -= 2) {\r\n res[i + 1] = a[i / 2];\r\n if (tr.getMin() > res[i + 1]) return -1;\r\n let t = tr.floor(res[i + 1]);\r\n tr.delete(t);\r\n res[i] = t;\r\n }\r\n return res.join(' ');\r\n}\r\nclass BinarySearchTree {\r\n constructor(_compare = (a, b) => a - b) {\r\n _defineProperty(this, \"root\", null);\r\n _defineProperty(this, \"length\", 0);\r\n _defineProperty(this, \"min\", null);\r\n _defineProperty(this, \"max\", null);\r\n _defineProperty(this, \"minCache\", true);\r\n _defineProperty(this, \"maxCache\", true);\r\n this._compare = _compare;\r\n this.compare = this.compare.bind(this);\r\n }\r\n isT(t) {\r\n return t !== undefined && t !== null;\r\n }\r\n compare(a, b) {\r\n const {\r\n isT\r\n } = this;\r\n if (isT(a) && isT(b)) return this._compare(a, b);\r\n if (isT(a)) return 1;\r\n if (isT(b)) return -1;\r\n return 0;\r\n }\r\n isEmpty() {\r\n return !this.root;\r\n }\r\n size() {\r\n return this.root ? this.root.size : 0;\r\n }\r\n getRoot() {\r\n return this.root;\r\n }\r\n getMin() {\r\n if (this.minCache) {\r\n return this.min;\r\n }\r\n const min = this.searchKth(this.size());\r\n this.min = min;\r\n this.minCache = true;\r\n return min;\r\n }\r\n getMax() {\r\n if (this.maxCache) {\r\n return this.max;\r\n }\r\n const max = this.searchKth(1);\r\n this.max = max;\r\n this.maxCache = true;\r\n return max;\r\n }\r\n balance(node) {\r\n node.height = this.getHeight(node);\r\n const blance = this.getBalance(node);\r\n let res;\r\n if (Math.abs(blance) === 2) {\r\n if (blance > 0) {\r\n var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;\r\n const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRight(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeftRight(node);\r\n }\r\n } else {\r\n var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;\r\n const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);\r\n if (heightDif > 0) {\r\n res = this.rotateRightLeft(node);\r\n } else if (heightDif < 0) {\r\n res = this.rotateLeft(node);\r\n }\r\n }\r\n }\r\n return res ? res : node;\r\n }\r\n rotateRight(node) {\r\n const left = node.left;\r\n const leftRight = left.right;\r\n left.right = node;\r\n node.left = leftRight;\r\n node.height = this.getHeight(node);\r\n left.height = this.getHeight(left);\r\n node.size = this.getSize(node);\r\n left.size = this.getSize(left);\r\n return left;\r\n }\r\n rotateLeft(node) {\r\n const right = node.right;\r\n const rightLeft = right.left;\r\n right.left = node;\r\n node.right = rightLeft;\r\n node.height = this.getHeight(node);\r\n right.height = this.getHeight(right);\r\n node.size = this.getSize(node);\r\n right.size = this.getSize(right);\r\n return right;\r\n }\r\n rotateLeftRight(node) {\r\n node.left = this.rotateLeft(node.left);\r\n return this.rotateRight(node);\r\n }\r\n rotateRightLeft(node) {\r\n node.right = this.rotateRight(node.right);\r\n return this.rotateLeft(node);\r\n }\r\n getBalance(node) {\r\n return this.getHeight(node.left) - this.getHeight(node.right);\r\n }\r\n getHeight(node) {\r\n var _node$left$height, _node$left3, _node$right$height, _node$right3;\r\n if (!node) return 0;\r\n return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;\r\n }\r\n getSize(node) {\r\n var _node$left$size, _node$left4, _node$right$size, _node$right4;\r\n if (!node) return 0;\r\n return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;\r\n }\r\n createNode(val) {\r\n return {\r\n id: Math.random() * new Date().valueOf(),\r\n val,\r\n left: null,\r\n right: null,\r\n size: 1,\r\n height: 1,\r\n count: 1\r\n };\r\n }\r\n insert(val) {\r\n let cur = this.createNode(val);\r\n if (this.isEmpty()) {\r\n this.root = cur;\r\n this.length++;\r\n } else {\r\n [, cur] = this.insertNode(this.root, cur);\r\n }\r\n if (this.min === null || this.compare(this.min, val) > 0) {\r\n this.min = val;\r\n }\r\n if (this.max === null || this.compare(this.max, val) < 0) {\r\n this.max = val;\r\n }\r\n }\r\n insertNode(node, cur, parent = null) {\r\n node.size++;\r\n const compareResult = this.compare(cur.val, node.val);\r\n let res;\r\n if (compareResult === 0) {\r\n node.count++;\r\n return [false, node];\r\n } else if (compareResult > 0) {\r\n if (node.right) {\r\n res = this.insertNode(node.right, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.right = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n } else {\r\n if (node.left) {\r\n res = this.insertNode(node.left, cur, node);\r\n if (!res[0]) return res;\r\n } else {\r\n node.left = cur;\r\n this.length++;\r\n res = [true, cur];\r\n }\r\n }\r\n let preHeight = node.height;\r\n const newNode = this.balance(node);\r\n if (newNode === node && node.height === preHeight) {\r\n res = [false, res[1]];\r\n } else if (newNode !== node) {\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n res = [false, res[1]];\r\n }\r\n return res;\r\n }\r\n delete(val) {\r\n if (!this.root) return;\r\n this.deleteNode(val, this.root, null);\r\n }\r\n deleteNode(val, node, parent) {\r\n if (!node) return null;\r\n let res = this.compare(val, node.val);\r\n if (res === 0) {\r\n node.count--;\r\n node.size--;\r\n if (node.count > 0) return node;\r\n if (!node.left || !node.right) {\r\n if (this.min === val) {\r\n this.minCache = false;\r\n }\r\n if (this.max === val) {\r\n this.maxCache = false;\r\n }\r\n this.length--;\r\n if (!parent) {\r\n var _node$left5;\r\n this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;\r\n return this.root;\r\n } else {\r\n var _node$left6;\r\n return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;\r\n }\r\n } else {\r\n const selectLeft = node.left.height > node.right.height;\r\n let replaceNode = selectLeft ? this.pre(node) : this.next(node),\r\n name = selectLeft ? 'left' : 'right';\r\n node.val = replaceNode.val;\r\n node.count = replaceNode.count;\r\n replaceNode.count = 0;\r\n node[name] = this.deleteNode(replaceNode.val, node[name], node);\r\n }\r\n } else if (res > 0) {\r\n node.right = this.deleteNode(val, node.right, node);\r\n } else {\r\n node.left = this.deleteNode(val, node.left, node);\r\n }\r\n node.size = this.getSize(node);\r\n node.height;\r\n const newNode = this.balance(node);\r\n if (parent) {\r\n parent.left === node ? parent.left = newNode : parent.right = newNode;\r\n } else {\r\n this.root = newNode;\r\n }\r\n return newNode;\r\n }\r\n next(node) {\r\n let next = node.right;\r\n while ((_next = next) !== null && _next !== void 0 && _next.left) {\r\n var _next;\r\n next = next.left;\r\n }\r\n return next;\r\n }\r\n pre(node) {\r\n let pre = node.left;\r\n while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {\r\n var _pre;\r\n pre = pre.right;\r\n }\r\n return pre;\r\n }\r\n search(val, compare) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);\r\n return node.val;\r\n }\r\n searchCeilingNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.searchCeilingNode(node.right, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n const [p, value] = this.searchCeilingNode(node.left, val, compare, node);\r\n if (compare(value.val, val) < 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n ceiling(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchCeilingNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) >= 0 ? node.val : null;\r\n }\r\n searchFloorNode(node, val, compare, parent = null) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n return [parent, node];\r\n } else if (res > 0) {\r\n if (node.right) {\r\n const [p, value] = this.searchFloorNode(node.right, val, compare, node);\r\n if (compare(value.val, val) > 0) {\r\n return [parent, node];\r\n } else {\r\n return [p, value];\r\n }\r\n } else {\r\n return [parent, node];\r\n }\r\n } else {\r\n if (node.left) {\r\n return this.searchFloorNode(node.left, val, compare, node);\r\n } else {\r\n return [parent, node];\r\n }\r\n }\r\n }\r\n floor(val) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const [, node] = this.searchFloorNode(this.root, val, this.compare);\r\n return this.compare(node.val, val) <= 0 ? node.val : null;\r\n }\r\n searchKth(k) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n if (k <= 0 || k > this.size()) {\r\n return null;\r\n }\r\n const node = this.searchNodeKth(this.root, k);\r\n return node.val;\r\n }\r\n searchNodeKth(node, k) {\r\n var _node$right$size2, _node$right5, _node$right$size3, _node$right6;\r\n const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;\r\n if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;\r\n if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);\r\n }\r\n countGreaterThanEq(val) {\r\n if (!this.root) return 0;\r\n return this.countCompare(val, (a, b) => this._compare(a, b), this.root);\r\n }\r\n countCompare(val, compare, node, pre = 0) {\r\n const res = compare(val, node.val);\r\n if (res === 0) {\r\n var _node$right$size4, _node$right7;\r\n return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;\r\n } else if (res > 0) {\r\n if (node.right) {\r\n return this.countCompare(val, compare, node.right, pre);\r\n } else {\r\n return pre;\r\n }\r\n } else {\r\n var _node$right$size5, _node$right8;\r\n let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;\r\n if (node.left) {\r\n return this.countCompare(val, compare, node.left, count);\r\n } else {\r\n return count;\r\n }\r\n }\r\n }\r\n toArray() {\r\n if (!this.root) return [];\r\n const res = [];\r\n const dfs = node => {\r\n if (node.left) dfs(node.left);\r\n res.push(node.val);\r\n if (node.right) dfs(node.right);\r\n };\r\n dfs(this.root);\r\n return res;\r\n }\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n let s = solve(r);\r\n if (s === undefined) s = '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "c2db558ecf921161ab4da003bd393ec7"} {"nl": {"description": "Hanh lives in a shared apartment. There are $$$n$$$ people (including Hanh) living there, each has a private fridge. $$$n$$$ fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $$$n$$$ people can open it. For exampe, in the picture there are $$$n=4$$$ people and $$$5$$$ chains. The first person knows passcodes of two chains: $$$1-4$$$ and $$$1-2$$$. The fridge $$$1$$$ can be open by its owner (the person $$$1$$$), also two people $$$2$$$ and $$$4$$$ (acting together) can open it. The weights of these fridges are $$$a_1, a_2, \\ldots, a_n$$$. To make a steel chain connecting fridges $$$u$$$ and $$$v$$$, you have to pay $$$a_u + a_v$$$ dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges. Hanh's apartment landlord asks you to create exactly $$$m$$$ steel chains so that all fridges are private. A fridge is private if and only if, among $$$n$$$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $$$i$$$ is not private if there exists the person $$$j$$$ ($$$i \\ne j$$$) that the person $$$j$$$ can open the fridge $$$i$$$.For example, in the picture all the fridges are private. On the other hand, if there are $$$n=2$$$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $$$m$$$ chains, and if yes, output any solution that minimizes the total cost. ", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \\le T \\le 10$$$). Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \\le n \\le 1000$$$, $$$1 \\le m \\le n$$$) — the number of people living in Hanh's apartment and the number of steel chains that the landlord requires, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^4$$$) — weights of all fridges.", "output_spec": "For each test case: If there is no solution, print a single integer $$$-1$$$. Otherwise, print a single integer $$$c$$$ — the minimum total cost. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$u_i \\ne v_i$$$), meaning that the $$$i$$$-th steel chain connects fridges $$$u_i$$$ and $$$v_i$$$. An arbitrary number of chains can be between a pair of fridges. If there are multiple answers, print any.", "sample_inputs": ["3\n4 4\n1 1 1 1\n3 1\n1 2 3\n3 3\n1 2 3"], "sample_outputs": ["8\n1 2\n4 3\n3 2\n4 1\n-1\n12\n3 2\n1 2\n3 1"], "notes": null}, "positive_code": [{"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let j = 0; j < t; j++) {\n const arrT1 = arr[2 * j].split(' ').map(a => parseInt(a))\n const arrT2 = arr[2 * j + 1].split(' ').map((a, i) => [parseInt(a), i + 1])\n\n const n = arrT1[0]\n const m = arrT1[1]\n\n if(m < n) console.log(-1)\n else if(n == 2) console.log(-1)\n else {\n let cost = 0\n let diff = m - n\n if(diff == 0) diff ++\n for(let i = 0; i < n; i++) {\n if(diff <= n) cost += (arrT2[i][0] + arrT2[(i + 1) % n][0])\n else cost += (arrT2[i][0] + arrT2[(i + 1) % n][0]) * Math.ceil(m / n)\n if(diff != 1) diff --\n }\n\n console.log(cost)\n for(let i = 0; i < m; i++) {\n console.log(`${arrT2[i % n][1]} ${arrT2[(i + 1) % n][1]}`)\n }\n }\n }\n})"}], "negative_code": [{"source_code": "process.stdin.resume()\nprocess.stdin.setEncoding('utf-8')\n\nvar arr = ''\nprocess.stdin.on('data', (i) => {\n arr += i\n})\n\n\nprocess.stdin.on('end', () => {\n arr = arr.split('\\n').map(a => a.replace(/(\\r\\n|\\n|\\r)/gm, ''))\n\n const t = parseInt(arr.shift())\n\n for(let j = 0; j < t; j++) {\n const arrT1 = arr[2 * j].split(' ').map(a => parseInt(a))\n const arrT2 = arr[2 * j + 1].split(' ').map((a, i) => [parseInt(a), i + 1])\n\n const n = arrT1[0]\n const m = arrT1[1]\n\n if(m < n) console.log(-1)\n else {\n let cost = 0\n for(let i = 0; i < n; i++) {\n cost += arrT2[i][0] + arrT2[(i + 1) % n][0]\n }\n\n for(let i = 0; i < m - n; i++) {\n cost += arrT2[i][0] + arrT2[(i + 1) % n][0]\n }\n\n console.log(cost)\n for(let i = 0; i < n; i++) {\n console.log(`${arrT2[i][1]} ${arrT2[(i + 1) % n][1]}`)\n }\n for(let i = 0; i < m - n; i++) {\n console.log(`${arrT2[i][1]} ${arrT2[(i + 1) % n][1]}`)\n }\n }\n }\n})"}], "src_uid": "f6e219176e846b16c5f52dee81601c8e"} {"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 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — 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 — 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": "(function () {\n\tvar line = readline().split(' ').map(function (e) {\n\t\treturn parseInt(e);\n\t});\n\tvar n = line[0],\n\t\tk = line[1];\n\tvar s = readline();\n\t\n\tvar ans1 = getAns(s,k,'a'),\n\t\tans2 = getAns(s,k,'b');\n\tans1 = ans1>ans2?ans1:ans2;\n\tprint(ans1);\n\n\tfunction getAns (str, k, c) {\n\t\tvar p = -1,\n\t\t\tnxt = 0,\n\t\t\tseg = [],\n\t\t\tl = str.length;\n\t\tdo {\n\t\t\tnxt = str.indexOf(c, p+1);\n\t\t\tif(nxt<0)\n\t\t\t\tnxt = l;\n\t\t\tseg.push(nxt - p - 1);\n\t\t\tp = nxt;\n\t\t} while(pret?tmp:ret;\n\t\t}\n\t\treturn ret+k;\n\t}\n\t\n})();"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar bs_removed = {removed: 0};\nvar as_removed = {removed: 0};\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(new_array, letter_in_array, letter_removed, number_of_letters_removed) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t new_array[j] = 0;\n\n\t\twhile (string[i] == letter_in_array) {\n\t\t\tnew_array[j] += 1;\n\t\t\ti++;\n\t\t}\n\n\t\tif (string[i] == letter_removed) {\n\t \tnumber_of_letters_removed.removed += 1;\n\t }\n\n\t\tj++;\n\t}\n\n\treturn new_array;\n};\n\na_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's\nb_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's\n\nvar max_sum_a = 0;\nvar max_sum_b = 0;\n\nvar summing = function(array, letters_removed) {\n\tvar sum = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k && i < array.length; i++) {\n\t\tsum += array[i];\n\t}\n\n\tvar max_sum = sum;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i + k <= array.length - 1; i++) {\n\t\tsum += array[i + k] - array[i - 1];\n \tif (sum > max_sum) {\n \t\tmax_sum = sum;\n \t}\n\t}\n\n\tmax_sum += Math.min(k, letters_removed.removed);\n\n\treturn max_sum;\n};\n\nmax_sum_a = summing(a_arr, bs_removed);\nmax_sum_b = summing(b_arr, as_removed);\n\nprint(Math.max(max_sum_a, max_sum_b));\n\n\n\n"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar bs_removed = {removed: 0};\nvar as_removed = {removed: 0};\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(x, y, z, p) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t x[j] = 0;\n\n\t\twhile (string[i] == y) {\n\t\t\tx[j] += 1;\n\t\t\ti++;\n\t\t}\n\n\t\tif (string[i] == z) {\n\t \tp.removed += 1;\n\t }\n\n\t\tj++;\n\t}\n\n\treturn x;\n};\n\na_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's\nb_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's\n\nvar sum_a = 0;\nvar max_sum_a = 0;\nvar sum_b = 0;\nvar max_sum_b = 0;\n\nvar summing = function(c, d, e) {\n\tc = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k && i < d.length; i++) {\n\t\tc += d[i];\n\t}\n\n\te = c;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i < d.length; i++) {\n\t if (i + k <= d.length - 1) {\n \t\tc += d[i + k] - d[i - 1];\n \t\tif (c > e) {\n \t\t\te = c;\n \t\t}\n\t\t}\n\t}\n\n\treturn e;\n};\n\n// which sum is bigger? and could I remove k letters or did I not have that many to begin with?\nif ((summing(sum_a, a_arr, max_sum_a) < summing(sum_b, b_arr, max_sum_b))) {\n if (as_removed.removed > k) {\n\t print(summing(sum_b, b_arr, max_sum_b) + k);\n } else {\n\t print(summing(sum_b, b_arr, max_sum_b) + as_removed.removed);\n }\n} else {\n if (bs_removed.removed > k) {\n\t print(summing(sum_a, a_arr, max_sum_a) + k);\n } else {\n\t print(summing(sum_a, a_arr, max_sum_a) + bs_removed.removed);\n }\n}\n\n\n\n"}, {"source_code": "var nums = readline().split(\" \").map(x => parseInt(x));\nvar n = nums[0];\nvar k = nums[1];\nvar str = readline();\nprint(solve(n, k, str));\n\nfunction solve(n, k, str) {\n return Math.max(longest(n, k, str, \"a\"), longest(n, k, str, \"b\"));\n}\n\nfunction longest(n, k, str, c) {\n var max = 0;\n var p = 0;\n for (var i = 0; i < n; i++) {\n if (str[i] !== c) {\n k -= 1;\n }\n while (k < 0) {\n if (str[p] !== c) {\n k += 1;\n }\n p += 1;\n }\n max = Math.max(max, i - p + 1);\n }\n return max;\n}"}, {"source_code": "function main() {\n var input = readline().split(' ').map(Number);\n var n = input[0];\n var k = input[1];\n var str = readline();\n \n var prefixSum = [];\n for (var i = 0; i < n; ++i) {\n var value = (str.charAt(i) == \"a\" ? 1 : 0);\n if (i > 0) {\n value += prefixSum[i - 1];\n }\n prefixSum.push(value);\n }\n \n function rangeSum(prefixSum, st, ed) {\n if (st > 0) {\n return prefixSum[ed] - prefixSum[st - 1];\n } else {\n return prefixSum[ed];\n }\n }\n \n function check(prefixSum, n, k, m) {\n for (var i = 0; i < n; ++i) {\n var numOfA = rangeSum(prefixSum, i, i + m - 1);\n var numOfB = m - numOfA;\n if (Math.min(numOfA, numOfB) <= k) {\n return true;\n }\n }\n return false;\n }\n \n function binarySearch(prefixSum, n, k) {\n var lower = 1;\n var upper = n;\n while (upper - lower > 1) {\n var middle = Math.floor((lower + upper) / 2);\n if (check(prefixSum, n, k, middle)) {\n lower = middle;\n } else {\n upper = middle;\n }\n }\n return check(prefixSum, n, k, upper) ? upper : lower;\n }\n \n var result = binarySearch(prefixSum, n, k);\n print(result);\n}\n\nmain();"}], "negative_code": [{"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(x, y) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t x[j] = 0;\n\t\twhile (string[i] == y) {\n\t\t\tx[j] += 1;\n\t\t\ti++;\n\t\t}\n\t\tj++;\n\t}\n\n\treturn x;\n};\n\nvar sum_a = 0;\nvar max_sum_a = 0;\nvar sum_b = 0;\nvar max_sum_b = 0;\n\nvar summing = function(c, d, e) {\n\tc = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k && i < d.length; i++) {\n\t\tc += d[i];\n\t}\n\n\te = c;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i < d.length; i++) {\n\t if (i + k < d.length - 1) {\n \t\tc += d[i + k] - d[i - 1];\n \t\tif (c > e) {\n \t\t\te = c;\n \t\t}\n\t\t}\n\t}\n\n\treturn e;\n};\n\nvar remove_b = summing(sum_a, a_arr, max_sum_a);\nvar remove_a = summing(sum_b, b_arr, max_sum_b);\n\nprint(Math.max(remove_b, remove_a) + k);\n\n"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(x, y) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t x[j] = 0;\n\t\twhile (string[i] == y) {\n\t\t\tx[j] += 1;\n\t\t\ti++;\n\t\t}\n\t\tj++;\n\t}\n\n\treturn x;\n};\n\nvar sum_a = 0;\nvar max_sum_a = 0;\nvar sum_b = 0;\nvar max_sum_b = 0;\n\nvar summing = function(c, d, e) {\n\tc = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k && i < d.length; i++) {\n\t\tc += d[i];\n\t}\n\n\te = c;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i < d.length; i++) {\n\t if (i + k < d.length - 1) {\n \t\tc += d[i + k] - d[i - 1];\n \t\tif (c > e) {\n \t\t\te = c;\n \t\t}\n\t\t}\n\t}\n\n\treturn e;\n};\n\nprint(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)));\n\n\n\n/* Sums for a_arr, not using this because I wrote a function\nvar sum_a = 0;\n\n// First sum\nfor (var i = 0; i <= k; i++) {\n\tsum_a += a_arr[i];\n}\n\nvar max_sum_a = sum_a;\n\n// Checking if other sums are bigger\nfor (var i = 1; i < a_arr.length; i++) {\n\tsum_a += a_arr[i + k] - a_arr[i - 1];\n\tif (sum_a > max_sum_a) {\n\t\tmax_sum_a = sum_a;\n\t}\n}\n\nprint(max_sum_a);\n*/\n\n"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar bs_removed = {removed: 0};\nvar as_removed = {removed: 0};\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(x, y, z, p) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t x[j] = 0;\n\n\t\twhile (string[i] == y) {\n\t\t\tx[j] += 1;\n\t\t\ti++;\n\t\t}\n\n\t\tif (string[i] == z) {\n\t \tp.removed += 1;\n\t }\n\n\t\tj++;\n\t}\n\n\treturn x;\n};\n\na_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's\nb_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's\n\nvar sum_a = 0;\nvar max_sum_a = 0;\nvar sum_b = 0;\nvar max_sum_b = 0;\n\nvar summing = function(c, d, e) {\n\tc = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k && i < d.length; i++) {\n\t\tc += d[i];\n\t}\n\n\te = c;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i < d.length; i++) {\n\t if (i + k < d.length - 1) {\n \t\tc += d[i + k] - d[i - 1];\n \t\tif (c > e) {\n \t\t\te = c;\n \t\t}\n\t\t}\n\t}\n\n\treturn e;\n};\n\n// which sum is bigger? and could I remove k letters or did I not have that many to begin with?\nif ((summing(sum_a, a_arr, max_sum_a) < summing(sum_b, b_arr, max_sum_b))) {\n if (as_removed.removed > k) {\n\t print(summing(sum_b, b_arr, max_sum_b) + k);\n } else {\n\t print(summing(sum_b, b_arr, max_sum_b) + as_removed.removed);\n }\n} else {\n if (bs_removed.removed > k) {\n\t print(summing(sum_a, a_arr, max_sum_a) + k);\n } else {\n\t print(summing(sum_a, a_arr, max_sum_a) + bs_removed.removed);\n }\n}\n\n\n\n"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(x, y) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t x[j] = 0;\n\t\twhile (string[i] == y) {\n\t\t\tx[j] += 1;\n\t\t\ti++;\n\t\t}\n\t\tj++;\n\t}\n\n\treturn x;\n};\n\na_arr = (rewrite_string(a_arr, a));\nb_arr = (rewrite_string(b_arr, b));\n\nvar sum_a = 0;\nvar max_sum_a = 0;\nvar sum_b = 0;\nvar max_sum_b = 0;\n\nvar summing = function(c, d, e) {\n\tc = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k && i < d.length; i++) {\n\t\tc += d[i];\n\t}\n\n\te = c;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i < d.length; i++) {\n\t if (i + k < d.length - 1) {\n \t\tc += d[i + k] - d[i - 1];\n \t\tif (c > e) {\n \t\t\te = c;\n \t\t}\n\t\t}\n\t}\n\n\treturn e;\n};\n\nif (string.length == 1) {\n\tprint(1);\n} else {\n\tprint(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)) + k);\n}\n"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(x, y) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t x[j] = 0;\n\t\twhile (string[i] == y) {\n\t\t\tx[j] += 1;\n\t\t\ti++;\n\t\t}\n\t\tj++;\n\t}\n\n\treturn x;\n};\n\nvar sum_a = 0;\nvar max_sum_a = 0;\nvar sum_b = 0;\nvar max_sum_b = 0;\n\nvar summing = function(c, d, e) {\n\tc = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k; i++) {\n\t\tc += d[i];\n\t}\n\n\te = c;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i < d.length; i++) {\n\t\tc += d[i + k] - d[i - 1];\n\t\tif (c > e) {\n\t\t\te = c;\n\t\t}\n\t}\n\n\treturn e;\n};\n\nprint(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)));\n\n\n\n/* Sums for a_arr, not using this because I wrote a function\nvar sum_a = 0;\n\n// First sum\nfor (var i = 0; i <= k; i++) {\n\tsum_a += a_arr[i];\n}\n\nvar max_sum_a = sum_a;\n\n// Checking if other sums are bigger\nfor (var i = 1; i < a_arr.length; i++) {\n\tsum_a += a_arr[i + k] - a_arr[i - 1];\n\tif (sum_a > max_sum_a) {\n\t\tmax_sum_a = sum_a;\n\t}\n}\n\nprint(max_sum_a);\n*/\n\n"}, {"source_code": "var nk = readline().split(' ').map(Number);\nvar string = readline().split('').map(String);\n\nvar n = nk[0];\nvar k = nk[1];\n\nvar a_arr = [];\nvar b_arr = [];\nvar a = \"a\";\nvar b = \"b\";\n\nvar rewrite_string = function(x, y) {\n\tvar count = 0;\n\tvar j = 0;\n\n\tfor (var i = 0; i < n; i++) {\n\t x[j] = 0;\n\t\twhile (string[i] == y) {\n\t\t\tx[j] += 1;\n\t\t\ti++;\n\t\t}\n\t\tj++;\n\t}\n\n\treturn x;\n};\n\na_arr = (rewrite_string(a_arr, a));\nb_arr = (rewrite_string(b_arr, b));\n\nvar sum_a = 0;\nvar max_sum_a = 0;\nvar sum_b = 0;\nvar max_sum_b = 0;\n\nvar summing = function(c, d, e) {\n\tc = 0;\n\n\t// First sum\n\tfor (var i = 0; i <= k && i < d.length; i++) {\n\t\tc += d[i];\n\t}\n\n\te = c;\n\n\t// Checking if other sums are bigger\n\tfor (var i = 1; i < d.length; i++) {\n\t if (i + k < d.length - 1) {\n \t\tc += d[i + k] - d[i - 1];\n \t\tif (c > e) {\n \t\t\te = c;\n \t\t}\n\t\t}\n\t}\n\n\treturn e;\n};\n\nprint(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)) + k);\n"}, {"source_code": "var nums = readline().split(\" \").map(x => parseInt(x));\nvar n = nums[0];\nvar k = nums[1];\nvar str = readline();\nprint(solve(n, k, str));\n\nfunction solve(n, k, str) {\n return Math.max(longest(n, k, str, \"a\"), longest(n, k, str, \"b\"));\n}\n\nfunction longest(n, k, str, c) {\n var max = 0;\n var p = 0;\n for (var i = 0; i < n; i++) {\n if (str[i] !== c) {\n k -= 1;\n }\n while (k < 0) {\n if (str[p] !== c) {\n k += 1;\n }\n p += 1;\n }\n max = Math.max(max, i - p);\n }\n return max;\n}"}], "src_uid": "0151a87d0f82a9044a0ac8731d369bb9"} {"nl": {"description": "You are given a binary string of length $$$n$$$. You have exactly $$$k$$$ moves. In one move, you must select a single bit. The state of all bits except that bit will get flipped ($$$0$$$ becomes $$$1$$$, $$$1$$$ becomes $$$0$$$). You need to output the lexicographically largest string that you can get after using all $$$k$$$ moves. Also, output the number of times you will select each bit. If there are multiple ways to do this, you may output any of them.A binary string $$$a$$$ is lexicographically larger than a binary 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$$$ contains a $$$1$$$, and the string $$$b$$$ contains a $$$0$$$. ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)  — the number of test cases. Each test case has two lines. The first line has two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$; $$$0 \\leq k \\leq 10^9$$$). The second line has a binary string of length $$$n$$$, each character is either $$$0$$$ or $$$1$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output two lines. The first line should contain the lexicographically largest string you can obtain. The second line should contain $$$n$$$ integers $$$f_1, f_2, \\ldots, f_n$$$, where $$$f_i$$$ is the number of times the $$$i$$$-th bit is selected. The sum of all the integers must be equal to $$$k$$$.", "sample_inputs": ["6\n\n6 3\n\n100001\n\n6 4\n\n100011\n\n6 0\n\n000000\n\n6 1\n\n111001\n\n6 11\n\n101100\n\n6 12\n\n001110"], "sample_outputs": ["111110\n1 0 0 2 0 0 \n111110\n0 1 1 1 0 1 \n000000\n0 0 0 0 0 0 \n100110\n1 0 0 0 0 0 \n111111\n1 2 1 3 0 4 \n111110\n1 1 4 2 0 4"], "notes": "NoteHere is the explanation for the first testcase. Each step shows how the binary string changes in a move. Choose bit $$$1$$$: $$$\\color{red}{\\underline{1}00001} \\rightarrow \\color{red}{\\underline{1}}\\color{blue}{11110}$$$. Choose bit $$$4$$$: $$$\\color{red}{111\\underline{1}10} \\rightarrow \\color{blue}{000}\\color{red}{\\underline{1}}\\color{blue}{01}$$$. Choose bit $$$4$$$: $$$\\color{red}{000\\underline{1}01} \\rightarrow \\color{blue}{111}\\color{red}{\\underline{1}}\\color{blue}{10}$$$. The final string is $$$111110$$$ and this is the lexicographically largest string we can get."}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(n, k, str) {\r\n let count = new Array(n).fill(0);\r\n\r\n if (k & 1) {\r\n let t = -1;\r\n\r\n for (let i = 0; i < n; i++) {\r\n if (str[i]) {\r\n t = i;\r\n break;\r\n }\r\n }\r\n\r\n if (t === -1) t = str.length - 1;\r\n str = str.map((num, i) => i === t ? num : num ^ 1);\r\n count[t]++;\r\n k--;\r\n }\r\n\r\n for (let i = 0; k && i < n; i++) {\r\n if (!str[i]) {\r\n str[i] = 1;\r\n k--;\r\n count[i] += 1;\r\n }\r\n }\r\n\r\n count[count.length - 1] += k;\r\n if (k % 2 === 1) str[str.length - 1] = 0;\r\n console.log(str.join(''));\r\n console.log(count.join(' '));\r\n}\r\n/**\r\n * 100001\r\n * 111110\r\n * 000000 000101\r\n * 111110 111110\r\n *\r\n * 101100\r\n * 110011\r\n * 001000\r\n * 111111\r\n * 000001\r\n * 111111\r\n *\r\n * 0110000\r\n * 0001111\r\n * 1111000\r\n * 0000011\r\n * 1111110\r\n * 0000000\r\n * 1111110\r\n * 0000000\r\n * 1111110\r\n *\r\n *\r\n * 101111001100\r\n * 110000110011\r\n * 000111001100\r\n * 111100110011\r\n * 000001001100\r\n * 111111110011\r\n *\r\n */\r\n\r\nfunction main(inputs) {\r\n const _ = Number(inputs[0]);\r\n\r\n for (let __ = 0; __ < _; __++) {\r\n const [n, k] = inputs[__ * 2 + 1].trim().split(' ').map(Number);\r\n const str = inputs[__ * 2 + 2].trim().split('').map(Number);\r\n solve(n, k, str);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nmain(inputs);\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [n, k] = iInpArr();\r\n let arr = iInpArr1();\r\n let res = new Array(n).fill(0);\r\n if (k % 2 === 1) {\r\n let flag = 0;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (arr[i] === 0) arr[i] = 1;\r\n else if (arr[i] === 1 && flag === 0) {\r\n res[i]++;\r\n flag = 1;\r\n } else arr[i] = 0;\r\n }\r\n if (flag === 1) arr[n - 1] = arr[n - 1] === 0 ? 1 : 0;\r\n else res[n-1]++;\r\n k--;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (i === n - 1 && k > 0) {\r\n if (k % 2 !== 0) arr[i] = arr[i] === 0 ? 1 : 0;\r\n res[i] += k;\r\n } else if (arr[i] === 0 && k > 0) {\r\n arr[i] = 1;\r\n res[i]++;\r\n k--;\r\n }\r\n }\r\n console.log(arr.join(\"\"));\r\n console.log(res.join(\" \"));\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\nconst readline = require('readline');\r\nconst util = require('util');\r\nconst lineReader = readline.createInterface({\r\n input: process.stdin,\r\n});\r\nlet inputPos = 0;\r\nconst inputWords = [];\r\nlineReader.on('line', (line) => {\r\n inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));\r\n});\r\nlineReader.on('close', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nfunction printf(...args) {\r\n process.stdout.write(util.format(...args));\r\n}\r\nfunction nextInt() {\r\n return Math.trunc(Number(inputWords[inputPos++]));\r\n}\r\nfunction nextStr() {\r\n return inputWords[inputPos++];\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INIT = -1;\r\nconst INF = Infinity;\r\nlet n;\r\nlet k;\r\nlet s;\r\nfunction solve() {\r\n const a = af(n);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = (s[i] == '1' ? 1 : 0);\r\n }\r\n // printf(\"n %d k %d s %s a %j\\n\", n, k, s, a);\r\n const K = k;\r\n const ans = af(n).fill(0);\r\n const keven = ((k % 2) == 0 ? true : false);\r\n for (let i = 0; i + 1 < n && k > 0; i++) {\r\n if (keven && a[i] == 0) {\r\n ans[i]++;\r\n k--;\r\n }\r\n else if (!keven && a[i] == 1) {\r\n ans[i]++;\r\n k--;\r\n }\r\n }\r\n ans[n - 1] = k;\r\n const b = af(n);\r\n for (let i = 0; i < n; i++) {\r\n b[i] = (a[i] + ans[i] + K) % 2;\r\n // printf(\"%d\", (a[i] + ans[i] + K) % 2), ' ');\r\n }\r\n process.stdout.write(b.join(''));\r\n process.stdout.write('\\n');\r\n process.stdout.write(ans.join(' '));\r\n process.stdout.write('\\n');\r\n}\r\nfunction main() {\r\n let tc = nextInt();\r\n while (tc--) {\r\n n = nextInt();\r\n k = nextInt();\r\n s = nextStr();\r\n solve();\r\n }\r\n}\r\n"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\n\n\nconst calc = (n, k, bits)=>{\n let usage = new Array(n).fill(0);\n let originalK = k;\n\n let flipped = 0;\n\n for (let i = 0; i < n; i++) {\n let flips = k % 2;\n let res = bits[i] ^ flipped ^ flips;\n if (!res && k) {\n k--;\n usage[i]++;\n flipped = 1 - flipped;\n }\n }\n usage[n - 1] += k;\n\n for (let i = 0; i < n; i++) {\n let flips = (originalK - usage[i]) % 2;\n bits[i] = bits[i] ^ flips;\n }\n\n return `${bits.join('')}\\n${usage.join(' ')}`;\n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let [n, k] = ra();\n let bits = readline().split('').map(a=>+a);\n console.log(`${calc(n, k, bits)}`);\n }\n}\n\n\n\n"}, {"source_code": "\n\nconst processData = (lines) => {\n let n = +lines[0]\n let cur = 0\n while(n--) {\n cur++\n let [_, k] = lines[cur].split(' ').map(x => +x)\n cur++\n let str = lines[cur].split('').map(x => +x)\n\n let xor = k%2;\n for (let i=0; i 0; i++) {\n if (str[i] === 0) {\n k--;\n str[i] = 1;\n res[i] = 1;\n }\n }\n \n if (k) {\n if (k%2 === 0) {\n res[0] += k;\n } else {\n res[res.length-1] += k;\n str[str.length-1] ^= 1;;\n }\n }\n console.log(str.join(''));\n console.log(res.join(' '))\n }\n}\n\nlet i = []\nprocess.stdin.on('data', c => i.push(c))\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.join('').split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const str = lines[l++]\n output[i] = solve(n, k, str)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, k, str) {\n const ans = Array(n).fill(0)\n const final = str.split('')\n let used = 0\n for (let i = 0; i < str.length; i++) {\n const ch = str[i]\n let x\n // flip k - x\n if (ch === '1') {\n // k - x is even\n if (k & 1) {\n x = 1\n } else {\n x = 0\n }\n } else {\n // k - x is odd\n if (k & 1) {\n x = 0\n } else {\n x = 1\n }\n }\n //\n if (used >= k) x = 0\n if (i === n - 1) x = k - used\n ans[i] = x\n used += x\n //\n if ((k - x) & 1) {\n final[i] = ch === '1' ? '0' : '1'\n // } else {\n // final = ch\n }\n }\n return final.join('') + '\\n' + ans.join(' ')\n}\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(n, k, str) {\r\n let count = new Array(n).fill(0);\r\n\r\n if (k & 1) {\r\n let t = -1;\r\n\r\n for (let i = 0; i < n; i++) {\r\n if (str[i]) {\r\n t = i;\r\n break;\r\n }\r\n }\r\n\r\n str = str.map((num, i) => i === t ? num : num ^ 1);\r\n count[t]++;\r\n k--;\r\n }\r\n\r\n for (let i = 0; k && i < n; i++) {\r\n if (!str[i]) {\r\n str[i] = 1;\r\n k -= 1;\r\n count[i] += 1;\r\n }\r\n }\r\n\r\n count[count.length - 1] += k;\r\n if (k % 2 === 1) str[str.length - 1] = 0;\r\n console.log(str.join(''));\r\n console.log(count.join(' '));\r\n}\r\n/**\r\n * 100001\r\n * 111110\r\n * 000000 000101\r\n * 111110 111110\r\n *\r\n * 101100\r\n * 110011\r\n * 001000\r\n * 111111\r\n * 000001\r\n * 111111\r\n *\r\n * 0110000\r\n * 0001111\r\n * 1111000\r\n * 0000011\r\n * 1111110\r\n * 0000000\r\n * 1111110\r\n * 0000000\r\n * 1111110\r\n *\r\n *\r\n * 101111001100\r\n * 110000110011\r\n * 000111001100\r\n * 111100110011\r\n * 000001001100\r\n * 111111110011\r\n *\r\n */\r\n\r\nfunction main(inputs) {\r\n const _ = Number(inputs[0]);\r\n\r\n for (let __ = 0; __ < _; __++) {\r\n const [n, k] = inputs[__ * 2 + 1].trim().split(' ').map(Number);\r\n const str = inputs[__ * 2 + 2].trim().split('').map(Number);\r\n solve(n, k, str);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nmain(inputs);\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(n, k, str) {\r\n let count = new Array(n).fill(0);\r\n\r\n if (k & 1) {\r\n let t = -1;\r\n\r\n for (let i = 0; i < n; i++) {\r\n if (str[i]) {\r\n t = i;\r\n break;\r\n }\r\n }\r\n\r\n str = str.map((num, i) => i === t ? num : num ^ 1);\r\n count[t]++;\r\n k--;\r\n }\r\n\r\n for (let i = 0; k && i < n; i++) {\r\n if (!str[i]) {\r\n str[i] = 1;\r\n k -= 1;\r\n count[i] += 1;\r\n }\r\n }\r\n\r\n count[count.length - 1] += k;\r\n if (k & 1) str[str.length - 1] = 0;\r\n console.log(str.join(''));\r\n console.log(count.join(' '));\r\n}\r\n/**\r\n * 100001\r\n * 111110\r\n * 000000 000101\r\n * 111110 111110\r\n *\r\n * 101100\r\n * 110011\r\n * 001000\r\n * 111111\r\n * 000001\r\n * 111111\r\n *\r\n * 0110000\r\n * 0001111\r\n * 1111000\r\n * 0000011\r\n * 1111110\r\n * 0000000\r\n * 1111110\r\n * 0000000\r\n * 1111110\r\n *\r\n *\r\n * 101111001100\r\n * 110000110011\r\n * 000111001100\r\n * 111100110011\r\n * 000001001100\r\n * 111111110011\r\n *\r\n */\r\n\r\nfunction main(inputs) {\r\n const _ = Number(inputs[0]);\r\n\r\n for (let __ = 0; __ < _; __++) {\r\n const [n, k] = inputs[__ * 2 + 1].trim().split(' ').map(Number);\r\n const str = inputs[__ * 2 + 2].trim().split('').map(Number);\r\n solve(n, k, str);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nmain(inputs);\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(n, k, str) {\r\n let count = new Array(n).fill(0);\r\n\r\n if (k & 1) {\r\n let t = -1;\r\n\r\n for (let i = 0; i < n; i++) {\r\n if (str[i]) {\r\n t = i;\r\n break;\r\n }\r\n }\r\n\r\n str = str.map((num, i) => i === t ? num : num ^ 1);\r\n count[t]++;\r\n k--;\r\n }\r\n\r\n str.filter(Boolean);\r\n\r\n for (let i = 0; k && i < n; i++) {\r\n if (!str[i]) {\r\n str[i] = 1;\r\n k -= 1;\r\n count[i] += 1;\r\n }\r\n }\r\n\r\n count[count.length - 1] += k;\r\n if (k & 1) str[str.length - 1] = 0;\r\n console.log(str.join(''));\r\n console.log(count.join(' '));\r\n}\r\n/**\r\n * 100001\r\n * 111110\r\n * 000000 000101\r\n * 111110 111110\r\n *\r\n * 101100\r\n * 110011\r\n * 001000\r\n * 111111\r\n * 000001\r\n * 111111\r\n *\r\n * 0110000\r\n * 0001111\r\n * 1111000\r\n * 0000011\r\n * 1111110\r\n * 0000000\r\n * 1111111\r\n * 0000000\r\n * 1111111\r\n *\r\n *\r\n * 101111001100\r\n * 110000110011\r\n * 000111001100\r\n * 111100110011\r\n * 000001001100\r\n * 111111110011\r\n *\r\n */\r\n\r\nfunction main(inputs) {\r\n const _ = Number(inputs[0]);\r\n\r\n for (let __ = 0; __ < _; __++) {\r\n const [n, k] = inputs[__ * 2 + 1].trim().split(' ').map(Number);\r\n const str = inputs[__ * 2 + 2].trim().split('').map(Number);\r\n solve(n, k, str);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split('\\n');\r\nmain(inputs);\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nfunction iInpArr1() {\r\n return readline()\r\n .trim()\r\n .split(\"\")\r\n .map((cur) => parseInt(cur));\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let [n, k] = iInpArr();\r\n let arr = iInpArr1();\r\n let res = new Array(n).fill(0);\r\n if (k % 2 === 1) {\r\n let flag = 0;\r\n for (let i = 0; i < n - 1; i++) {\r\n if (arr[i] === 0) arr[i] = 1;\r\n else if (arr[i] === 1 && flag === 0) {\r\n flag = 1;\r\n } else arr[i] = 0;\r\n }\r\n if (flag === 1) arr[n - 1] = arr[n - 1] === 0 ? 1 : 0;\r\n k--;\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (i === n - 1 && k > 0) {\r\n if (k % 2 !== 0) arr[i] = arr[i] === 0 ? 1 : 0;\r\n res[i] += k;\r\n } else if (arr[i] === 0 && k > 0) {\r\n arr[i] = 1;\r\n res[i]++;\r\n k--;\r\n }\r\n }\r\n console.log(arr.join(\"\"));\r\n console.log(res.join(\" \"));\r\n }\r\n};\r\nsolve();\r\n"}], "src_uid": "38375efafa4861f3443126f20cacf3ae"} {"nl": {"description": "You have two positive integers $$$a$$$ and $$$b$$$.You can perform two kinds of operations: $$$a = \\lfloor \\frac{a}{b} \\rfloor$$$ (replace $$$a$$$ with the integer part of the division between $$$a$$$ and $$$b$$$) $$$b=b+1$$$ (increase $$$b$$$ by $$$1$$$) Find the minimum number of operations required to make $$$a=0$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) — the number of test cases. The only line of the description of each test case contains two integers $$$a$$$, $$$b$$$ ($$$1 \\le a,b \\le 10^9$$$).", "output_spec": "For each test case, print a single integer: the minimum number of operations required to make $$$a=0$$$.", "sample_inputs": ["6\n9 2\n1337 1\n1 1\n50000000 4\n991026972 997\n1234 5678"], "sample_outputs": ["4\n9\n2\n12\n3\n1"], "notes": "NoteIn the first test case, one of the optimal solutions is: Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 4$$$ and $$$b = 2$$$. Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 2$$$. Increase $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 3$$$. Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 0$$$ and $$$b = 3$$$. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction readInt() {\r\n return readline()|0\r\n}\r\n\r\nfunction readIntArr() {\r\n return readline().split(' ').map(x => x|0)\r\n}\r\n\r\n\r\nfunction main() {\r\n const N = readInt()\r\n for (let i = 0; i < N; ++i) {\r\n let total = 1\r\n let c = 0\r\n let [a, b] = readIntArr()\r\n if (b == 1) {\r\n b += 1\r\n c = 1\r\n }\r\n\r\n function found(a, b, total) {\r\n let fo = false\r\n for (let i = 0; i < total; i++) {\r\n if (((b + i) ** (total - i) > a)) {\r\n fo = true;\r\n }\r\n }\r\n return fo\r\n }\r\n \r\n while (!found(a, b, total)) {\r\n total += 1\r\n }\r\n console.log(total + c)\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n\r\n var answer = {}\r\n\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [a, b] = readline().split(' ').map((x, i) => {\r\n // if (minA > Number(x)) minA = Number(x)\r\n return parseInt(x)\r\n })\r\n var min = 100000000\r\n var bb\r\n var aa\r\n if (a < b) return console.log(1)\r\n\r\n for (var i = 0; i < 1000; i++) {\r\n aa = a\r\n answer = i\r\n bb = b + i\r\n if (bb === 1) continue\r\n\r\n while (aa !== 0) {\r\n aa = Math.floor(aa / bb)\r\n answer += 1\r\n }\r\n // console.log(a,bb, answer)\r\n\r\n // console.log(min)\r\n min = Math.min(min, answer)\r\n }\r\n console.log(min)\r\n // console.log(Math.min(answer, answer2))\r\n\r\n\r\n })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n\r\n\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n if (k > n) console.log(1);\r\n else if (n === k) console.log(2);\r\n else {\r\n const red = (n, k) => {\r\n let cnt = 0;\r\n while (n > 0) {\r\n n = Math.floor(n / k);\r\n cnt++;\r\n }\r\n return cnt;\r\n };\r\n let cnt = 0;\r\n if (k === 1) {\r\n k++;\r\n cnt++;\r\n }\r\n let prev = red(n, k) + cnt;\r\n while (true) {\r\n k++;\r\n cnt++;\r\n let l = red(n, k) + cnt;\r\n if (prev < l) {\r\n console.log(prev);\r\n break;\r\n } else prev = l;\r\n }\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\n\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar A = nextInt();\r\n\t\tvar B = nextInt();\r\n\t\tvar add = 0;\r\n\t\tif(B == 1){\r\n\t\t\tadd = 1;\r\n\t\t\tB++;\r\n\t\t}\r\n\t\tvar now = B;\r\n\t\tvar output = Math.pow(10, 15);\r\n\t\twhile(true){\r\n\t\t\tvar tmp = A;\r\n\t\t\tvar count = now - B;\r\n\t\t\twhile(tmp > 0){\r\n\t\t\t\tcount++;\r\n\t\t\t\ttmp = Math.floor(tmp / now);\r\n\t\t\t}\r\n\t\t\tif(output >= count){\r\n\t\t\t\toutput = count;\r\n\t\t\t}else{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tnow++;\r\n\t\t}\r\n\t\tmyout(output + add);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n \nfunction readInt() {\n return readline()|0\n}\n \nfunction readIntArr() {\n return readline().split(' ').map(x => x|0)\n}\n \n \nfunction main() {\n const n = readInt();\n\n for(let i=0; i < n; i++) {\n let [a, b] = readIntArr();\n let phase = 1;\n if(b === 1) {\n phase = 2;\n }\n\n const func = () => {\n for(let i = 1; i <= phase; i++) {\n if (((b + phase) - i)**(i) > a) return false;\n }\n\n return true;\n }\n\n while (func()) {\n phase++;\n }\n\n console.log(phase);\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction readInt() {\r\n return readline()|0\r\n}\r\n\r\nfunction readIntArr() {\r\n return readline().split(' ').map(x => x|0)\r\n}\r\n\r\n\r\nfunction main() {\r\n const N = readInt()\r\n for (let i = 0; i < N; ++i) {\r\n let total = 1\r\n let c = 0\r\n let [a, b] = readIntArr()\r\n if (b == 1) {\r\n b += 1\r\n c = 1\r\n }\r\n while (b ** total <= a && (b + 1) ** (total - 1) <= a && (b + 2) ** (total - 2) <= a) {\r\n total += 1\r\n }\r\n console.log(total + c)\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction readInt() {\r\n return readline()|0\r\n}\r\n\r\nfunction readIntArr() {\r\n return readline().split(' ').map(x => x|0)\r\n}\r\n\r\n\r\nfunction main() {\r\n const N = readInt()\r\n for (let i = 0; i < N; ++i) {\r\n let total = 1\r\n let c = 0\r\n let [a, b] = readIntArr()\r\n if (b == 1) {\r\n b += 1\r\n c = 1\r\n }\r\n while (b ** total < a && (b + 1) ** (total - 1) < a && (b + 2) ** (total - 2) < a) {\r\n total += 1\r\n }\r\n console.log(total + c)\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n\r\n var answer = {}\r\n\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [a, b] = readline().split(' ').map((x, i) => {\r\n // if (minA > Number(x)) minA = Number(x)\r\n return parseInt(x)\r\n })\r\n var min = 100000000\r\n var bb\r\n var aa\r\n if (a < b) return console.log(1)\r\n\r\n for (var i = 0; i < 5; i++) {\r\n aa = a\r\n answer = i\r\n bb = b + i\r\n if (bb === 1) continue\r\n\r\n while (aa !== 0) {\r\n aa = Math.floor(aa / bb)\r\n answer += 1\r\n }\r\n // console.log(a,bb, answer)\r\n\r\n // console.log(min)\r\n min = Math.min(min, answer)\r\n }\r\n console.log(min)\r\n // console.log(Math.min(answer, answer2))\r\n\r\n\r\n })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n\r\n\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\n\r\nfunction main() {\r\n const x = readline();\r\n // 1 1 7\r\n // 6 9, 15, 18\r\n\r\n var answer = {}\r\n\r\n Array(Number(x)).fill(1).map((t, i) => {\r\n var [a, b] = readline().split(' ').map((x, i) => {\r\n // if (minA > Number(x)) minA = Number(x)\r\n return parseInt(x)\r\n })\r\n var answer = 0\r\n var answer2 = 0\r\n if (a < b) return console.log(1)\r\n if(b===1) {\r\n answer = 1\r\n answer2 = 2\r\n b = 2\r\n }\r\n // console.log(b,a)\r\n\r\n var bb = b +1\r\n var aa = a\r\n while(a!==0){\r\n a=Math.floor(a/b)\r\n answer+=1\r\n }\r\n\r\n while(aa!==0){\r\n aa=Math.floor(aa/bb)\r\n answer2+=1\r\n }\r\n console.log(Math.min(answer, answer2))\r\n\r\n\r\n })\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (!b) {\r\n return a;\r\n }\r\n\r\n return gcd(b, a % b);\r\n}\r\n\r\n\r\n\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nlet obj = {};\r\nconst precompute = () => {\r\n for (let i = 1; i <= 10000; i++) obj[i * i * i] = 1;\r\n};\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n precompute();\r\n while (t--) {\r\n let [n, k] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n if (k > n) console.log(1);\r\n else {\r\n if (n === k) console.log(2);\r\n else {\r\n let cnt = 0;\r\n if (n % k === 0) {\r\n k += 2;\r\n cnt += 2;\r\n }\r\n while (n > 0) {\r\n cnt++;\r\n n = Math.floor(n / k);\r\n }\r\n console.log(cnt);\r\n }\r\n }\r\n }\r\n};\r\nsolve();\r\n"}], "src_uid": "2b757fa66ce89046fe18cdfdeafa6660"} {"nl": {"description": "You are a coach at your local university. There are $$$n$$$ students under your supervision, the programming skill of the $$$i$$$-th student is $$$a_i$$$.You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than $$$5$$$.Your task is to report the maximum possible number of students in a balanced team.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the number of students. 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 a programming skill of the $$$i$$$-th student.", "output_spec": "Print one integer — the maximum possible number of students in a balanced team.", "sample_inputs": ["6\n1 10 17 12 15 2", "10\n1337 1337 1337 1337 1337 1337 1337 1337 1337 1337", "6\n1 1000 10000 10 100 1000000000"], "sample_outputs": ["3", "10", "1"], "notes": "NoteIn the first example you can create a team with skills $$$[12, 17, 15]$$$.In the second example you can take all students in a team because their programming skills are equal.In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students)."}, "positive_code": [{"source_code": "var a = readline();\nvar skills = readline().split(' ');\nvar sortedSkills = skills.sort((a,b) => a-b);\nvar differences = [];\n\nfor (var i=0; i 5) {\n currentDiff -= differences[lowerBoundary];\n lowerBoundary++;\n currentAmount--;\n }\n }\n}\nmaxAmount = maxAmount < currentAmount ? currentAmount : maxAmount;\n\nprint(maxAmount);"}], "negative_code": [], "src_uid": "8b075d96b3c0172d756109b4801d68de"} {"nl": {"description": "Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \\le l \\le r \\le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \\dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.", "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 description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print \"YES\", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print \"NO\".", "sample_inputs": ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"], "sample_outputs": ["YES\nNO\nNO"], "notes": "NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes."}, "positive_code": [{"source_code": "'use strict';\n\nvar readline = require('readline');\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n//# sourceMappingURL=isFunction.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar _enable_super_gross_mode_that_will_cause_bad_things = false;\nvar config = {\n Promise: undefined,\n set useDeprecatedSynchronousErrorHandling(value) {\n if (value) {\n var error = /*@__PURE__*/ new Error();\n /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n//# sourceMappingURL=config.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction hostReportError(err) {\n setTimeout(function () { throw err; }, 0);\n}\n//# sourceMappingURL=hostReportError.js.map\n\n/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */\nvar empty = {\n closed: true,\n next: function (value) { },\n error: function (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n },\n complete: function () { }\n};\n//# sourceMappingURL=Observer.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();\n//# sourceMappingURL=isArray.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction isObject(x) {\n return x !== null && typeof x === 'object';\n}\n//# sourceMappingURL=isObject.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {\n function UnsubscriptionErrorImpl(errors) {\n Error.call(this);\n this.message = errors ?\n errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ') : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n return UnsubscriptionErrorImpl;\n})();\nvar UnsubscriptionError = UnsubscriptionErrorImpl;\n//# sourceMappingURL=UnsubscriptionError.js.map\n\n/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */\nvar Subscription = /*@__PURE__*/ (function () {\n function Subscription(unsubscribe) {\n this.closed = false;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (unsubscribe) {\n this._unsubscribe = unsubscribe;\n }\n }\n Subscription.prototype.unsubscribe = function () {\n var errors;\n if (this.closed) {\n return;\n }\n var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;\n this.closed = true;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n }\n else if (_parentOrParents !== null) {\n for (var index = 0; index < _parentOrParents.length; ++index) {\n var parent_1 = _parentOrParents[index];\n parent_1.remove(this);\n }\n }\n if (isFunction(_unsubscribe)) {\n try {\n _unsubscribe.call(this);\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n if (isArray(_subscriptions)) {\n var index = -1;\n var len = _subscriptions.length;\n while (++index < len) {\n var sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n }\n catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n }\n else {\n errors.push(e);\n }\n }\n }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n };\n Subscription.prototype.add = function (teardown) {\n var subscription = teardown;\n if (!teardown) {\n return Subscription.EMPTY;\n }\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n return subscription;\n }\n else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n }\n else if (!(subscription instanceof Subscription)) {\n var tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n var _parentOrParents = subscription._parentOrParents;\n if (_parentOrParents === null) {\n subscription._parentOrParents = this;\n }\n else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n return subscription;\n }\n subscription._parentOrParents = [_parentOrParents, this];\n }\n else if (_parentOrParents.indexOf(this) === -1) {\n _parentOrParents.push(this);\n }\n else {\n return subscription;\n }\n var subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n }\n else {\n subscriptions.push(subscription);\n }\n return subscription;\n };\n Subscription.prototype.remove = function (subscription) {\n var subscriptions = this._subscriptions;\n if (subscriptions) {\n var subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n };\n Subscription.EMPTY = (function (empty) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n return Subscription;\n}());\nfunction flattenUnsubscriptionErrors(errors) {\n return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);\n}\n//# sourceMappingURL=Subscription.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar rxSubscriber = /*@__PURE__*/ (function () {\n return typeof Symbol === 'function'\n ? /*@__PURE__*/ Symbol('rxSubscriber')\n : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();\n})();\n//# sourceMappingURL=rxSubscriber.js.map\n\n/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */\nvar Subscriber = /*@__PURE__*/ (function (_super) {\n __extends(Subscriber, _super);\n function Subscriber(destinationOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this.syncErrorValue = null;\n _this.syncErrorThrown = false;\n _this.syncErrorThrowable = false;\n _this.isStopped = false;\n switch (arguments.length) {\n case 0:\n _this.destination = empty;\n break;\n case 1:\n if (!destinationOrNext) {\n _this.destination = empty;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n _this.destination = destinationOrNext;\n destinationOrNext.add(_this);\n }\n else {\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext);\n }\n break;\n }\n default:\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);\n break;\n }\n return _this;\n }\n Subscriber.prototype[rxSubscriber] = function () { return this; };\n Subscriber.create = function (next, error, complete) {\n var subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n };\n Subscriber.prototype.next = function (value) {\n if (!this.isStopped) {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n this.destination.error(err);\n this.unsubscribe();\n };\n Subscriber.prototype._complete = function () {\n this.destination.complete();\n this.unsubscribe();\n };\n Subscriber.prototype._unsubscribeAndRecycle = function () {\n var _parentOrParents = this._parentOrParents;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n };\n return Subscriber;\n}(Subscription));\nvar SafeSubscriber = /*@__PURE__*/ (function (_super) {\n __extends(SafeSubscriber, _super);\n function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this._parentSubscriber = _parentSubscriber;\n var next;\n var context = _this;\n if (isFunction(observerOrNext)) {\n next = observerOrNext;\n }\n else if (observerOrNext) {\n next = observerOrNext.next;\n error = observerOrNext.error;\n complete = observerOrNext.complete;\n if (observerOrNext !== empty) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n _this.add(context.unsubscribe.bind(context));\n }\n context.unsubscribe = _this.unsubscribe.bind(_this);\n }\n }\n _this._context = context;\n _this._next = next;\n _this._error = error;\n _this._complete = complete;\n return _this;\n }\n SafeSubscriber.prototype.next = function (value) {\n if (!this.isStopped && this._next) {\n var _parentSubscriber = this._parentSubscriber;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n }\n else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n }\n else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n }\n else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n }\n else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.complete = function () {\n var _this = this;\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n if (this._complete) {\n var wrappedComplete = function () { return _this._complete.call(_this._context); };\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n }\n else {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n }\n };\n SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n }\n else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n };\n SafeSubscriber.prototype._unsubscribe = function () {\n var _parentSubscriber = this._parentSubscriber;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n };\n return SafeSubscriber;\n}(Subscriber));\n//# sourceMappingURL=Subscriber.js.map\n\n/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */\nfunction canReportError(observer) {\n while (observer) {\n var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;\n if (closed_1 || isStopped) {\n return false;\n }\n else if (destination && destination instanceof Subscriber) {\n observer = destination;\n }\n else {\n observer = null;\n }\n }\n return true;\n}\n//# sourceMappingURL=canReportError.js.map\n\n/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */\nfunction toSubscriber(nextOrObserver, error, complete) {\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return nextOrObserver;\n }\n if (nextOrObserver[rxSubscriber]) {\n return nextOrObserver[rxSubscriber]();\n }\n }\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(empty);\n }\n return new Subscriber(nextOrObserver, error, complete);\n}\n//# sourceMappingURL=toSubscriber.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();\n//# sourceMappingURL=observable.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction noop() { }\n//# sourceMappingURL=noop.js.map\n\n/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */\nfunction pipeFromArray(fns) {\n if (!fns) {\n return noop;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map\n\n/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */\nvar Observable = /*@__PURE__*/ (function () {\n function Observable(subscribe) {\n this._isScalar = false;\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var operator = this.operator;\n var sink = toSubscriber(observerOrNext, error, complete);\n if (operator) {\n sink.add(operator.call(sink, this.source));\n }\n else {\n sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n this._subscribe(sink) :\n this._trySubscribe(sink));\n }\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n return sink;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n }\n else {\n console.warn(err);\n }\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscription;\n subscription = _this.subscribe(function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var source = this.source;\n return source && source.subscribe(subscriber);\n };\n Observable.prototype[observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n if (operations.length === 0) {\n return this;\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nfunction getPromiseCtor(promiseCtor) {\n if (!promiseCtor) {\n promiseCtor = Promise;\n }\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n return promiseCtor;\n}\n//# sourceMappingURL=Observable.js.map\n\nfunction tnLineStdinReader() {\n return new Observable(subscribe => {\n const stdin = readline.createInterface(process.stdin);\n let tests = null;\n let n = null;\n stdin.on('line', line => {\n if (tests === null) {\n tests = +line;\n } else if (n === null) {\n n = +line;\n tests--;\n } else {\n n = null;\n subscribe.next(line);\n\n if (tests === 0) {\n stdin.close();\n subscribe.complete();\n }\n }\n });\n });\n}\n\nfunction isHappy(arr) {\n if (arr[0] <= 0 || arr[arr.length - 1] <= 0) {\n return 'NO';\n }\n\n let sum = 0;\n\n for (let x = 0; x < arr.length - 1; x++) {\n sum += arr[x];\n\n if (sum <= 0) {\n return 'NO';\n }\n }\n\n sum = 0;\n\n for (let x = arr.length - 1; x > 0; x--) {\n sum += arr[x];\n\n if (sum <= 0) {\n return 'NO';\n }\n }\n\n return 'YES';\n}\n\ntnLineStdinReader().subscribe(input => {\n const arr = input.split(' ').map(i => +i);\n console.log(isHappy(arr));\n});\n"}, {"source_code": "'use strict'\n\nlet t = parseInt(readline())\n\nfunction calc (arr) {\n let max_so_far = Number.MIN_SAFE_INTEGER\n let max_here = 0\n \n for (let i = 0; i + 1 < arr.length; ++i) {\n max_here += arr[i]\n \n if (max_here < 0) {\n max_here = 0\n }\n \n if (max_so_far < max_here) {\n max_so_far = max_here\n }\n }\n return max_so_far\n}\n\nwhile (t --> 0) {\n const n = readline()\n const arr = readline().split(' ').map(function(x) {\n return parseInt(x)\n })\n\n let whole = 0\n for (let i in arr) whole += arr[i]\n \n let a = calc(arr)\n let b = calc(arr.reverse())\n\n let mx = Math.max(a, b)\n let ok = whole > mx\n\n print(ok ? 'YES': 'NO')\n}"}, {"source_code": "var numRun= readline();\n \nfor(var n=0;n {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\n// function print(item) {\n// console.log(item);\n// }\n\nfunction maxSubArraySum(array_of_numbers, init_value, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = init_value; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n var cupcakes_count = parseInt(readline(), 10);\n var cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));\n \n var total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n var result_begin = maxSubArraySum(cupcakes_taste, 0, cupcakes_count - 1);\n var result_end = maxSubArraySum(cupcakes_taste, 1, cupcakes_count);\n \n if (total_taste > Math.max(result_begin.max_so_far, result_end.max_so_far)) {\n print('YES');\n } else {\n print('NO');\n }\n }\n}\n\nmain();"}], "negative_code": [{"source_code": "'use strict';\n\nvar readline = require('readline');\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n//# sourceMappingURL=isFunction.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar _enable_super_gross_mode_that_will_cause_bad_things = false;\nvar config = {\n Promise: undefined,\n set useDeprecatedSynchronousErrorHandling(value) {\n if (value) {\n var error = /*@__PURE__*/ new Error();\n /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n//# sourceMappingURL=config.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction hostReportError(err) {\n setTimeout(function () { throw err; }, 0);\n}\n//# sourceMappingURL=hostReportError.js.map\n\n/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */\nvar empty = {\n closed: true,\n next: function (value) { },\n error: function (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n },\n complete: function () { }\n};\n//# sourceMappingURL=Observer.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();\n//# sourceMappingURL=isArray.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction isObject(x) {\n return x !== null && typeof x === 'object';\n}\n//# sourceMappingURL=isObject.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {\n function UnsubscriptionErrorImpl(errors) {\n Error.call(this);\n this.message = errors ?\n errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ') : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n return UnsubscriptionErrorImpl;\n})();\nvar UnsubscriptionError = UnsubscriptionErrorImpl;\n//# sourceMappingURL=UnsubscriptionError.js.map\n\n/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */\nvar Subscription = /*@__PURE__*/ (function () {\n function Subscription(unsubscribe) {\n this.closed = false;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (unsubscribe) {\n this._unsubscribe = unsubscribe;\n }\n }\n Subscription.prototype.unsubscribe = function () {\n var errors;\n if (this.closed) {\n return;\n }\n var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;\n this.closed = true;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n }\n else if (_parentOrParents !== null) {\n for (var index = 0; index < _parentOrParents.length; ++index) {\n var parent_1 = _parentOrParents[index];\n parent_1.remove(this);\n }\n }\n if (isFunction(_unsubscribe)) {\n try {\n _unsubscribe.call(this);\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n if (isArray(_subscriptions)) {\n var index = -1;\n var len = _subscriptions.length;\n while (++index < len) {\n var sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n }\n catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n }\n else {\n errors.push(e);\n }\n }\n }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n };\n Subscription.prototype.add = function (teardown) {\n var subscription = teardown;\n if (!teardown) {\n return Subscription.EMPTY;\n }\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n return subscription;\n }\n else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n }\n else if (!(subscription instanceof Subscription)) {\n var tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n var _parentOrParents = subscription._parentOrParents;\n if (_parentOrParents === null) {\n subscription._parentOrParents = this;\n }\n else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n return subscription;\n }\n subscription._parentOrParents = [_parentOrParents, this];\n }\n else if (_parentOrParents.indexOf(this) === -1) {\n _parentOrParents.push(this);\n }\n else {\n return subscription;\n }\n var subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n }\n else {\n subscriptions.push(subscription);\n }\n return subscription;\n };\n Subscription.prototype.remove = function (subscription) {\n var subscriptions = this._subscriptions;\n if (subscriptions) {\n var subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n };\n Subscription.EMPTY = (function (empty) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n return Subscription;\n}());\nfunction flattenUnsubscriptionErrors(errors) {\n return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);\n}\n//# sourceMappingURL=Subscription.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar rxSubscriber = /*@__PURE__*/ (function () {\n return typeof Symbol === 'function'\n ? /*@__PURE__*/ Symbol('rxSubscriber')\n : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();\n})();\n//# sourceMappingURL=rxSubscriber.js.map\n\n/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */\nvar Subscriber = /*@__PURE__*/ (function (_super) {\n __extends(Subscriber, _super);\n function Subscriber(destinationOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this.syncErrorValue = null;\n _this.syncErrorThrown = false;\n _this.syncErrorThrowable = false;\n _this.isStopped = false;\n switch (arguments.length) {\n case 0:\n _this.destination = empty;\n break;\n case 1:\n if (!destinationOrNext) {\n _this.destination = empty;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n _this.destination = destinationOrNext;\n destinationOrNext.add(_this);\n }\n else {\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext);\n }\n break;\n }\n default:\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);\n break;\n }\n return _this;\n }\n Subscriber.prototype[rxSubscriber] = function () { return this; };\n Subscriber.create = function (next, error, complete) {\n var subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n };\n Subscriber.prototype.next = function (value) {\n if (!this.isStopped) {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n this.destination.error(err);\n this.unsubscribe();\n };\n Subscriber.prototype._complete = function () {\n this.destination.complete();\n this.unsubscribe();\n };\n Subscriber.prototype._unsubscribeAndRecycle = function () {\n var _parentOrParents = this._parentOrParents;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n };\n return Subscriber;\n}(Subscription));\nvar SafeSubscriber = /*@__PURE__*/ (function (_super) {\n __extends(SafeSubscriber, _super);\n function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this._parentSubscriber = _parentSubscriber;\n var next;\n var context = _this;\n if (isFunction(observerOrNext)) {\n next = observerOrNext;\n }\n else if (observerOrNext) {\n next = observerOrNext.next;\n error = observerOrNext.error;\n complete = observerOrNext.complete;\n if (observerOrNext !== empty) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n _this.add(context.unsubscribe.bind(context));\n }\n context.unsubscribe = _this.unsubscribe.bind(_this);\n }\n }\n _this._context = context;\n _this._next = next;\n _this._error = error;\n _this._complete = complete;\n return _this;\n }\n SafeSubscriber.prototype.next = function (value) {\n if (!this.isStopped && this._next) {\n var _parentSubscriber = this._parentSubscriber;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n }\n else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n }\n else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n }\n else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n }\n else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.complete = function () {\n var _this = this;\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n if (this._complete) {\n var wrappedComplete = function () { return _this._complete.call(_this._context); };\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n }\n else {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n }\n };\n SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n }\n else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n };\n SafeSubscriber.prototype._unsubscribe = function () {\n var _parentSubscriber = this._parentSubscriber;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n };\n return SafeSubscriber;\n}(Subscriber));\n//# sourceMappingURL=Subscriber.js.map\n\n/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */\nfunction canReportError(observer) {\n while (observer) {\n var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;\n if (closed_1 || isStopped) {\n return false;\n }\n else if (destination && destination instanceof Subscriber) {\n observer = destination;\n }\n else {\n observer = null;\n }\n }\n return true;\n}\n//# sourceMappingURL=canReportError.js.map\n\n/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */\nfunction toSubscriber(nextOrObserver, error, complete) {\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return nextOrObserver;\n }\n if (nextOrObserver[rxSubscriber]) {\n return nextOrObserver[rxSubscriber]();\n }\n }\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(empty);\n }\n return new Subscriber(nextOrObserver, error, complete);\n}\n//# sourceMappingURL=toSubscriber.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();\n//# sourceMappingURL=observable.js.map\n\n/** PURE_IMPORTS_START PURE_IMPORTS_END */\nfunction noop() { }\n//# sourceMappingURL=noop.js.map\n\n/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */\nfunction pipeFromArray(fns) {\n if (!fns) {\n return noop;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map\n\n/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */\nvar Observable = /*@__PURE__*/ (function () {\n function Observable(subscribe) {\n this._isScalar = false;\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var operator = this.operator;\n var sink = toSubscriber(observerOrNext, error, complete);\n if (operator) {\n sink.add(operator.call(sink, this.source));\n }\n else {\n sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n this._subscribe(sink) :\n this._trySubscribe(sink));\n }\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n return sink;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n }\n else {\n console.warn(err);\n }\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscription;\n subscription = _this.subscribe(function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var source = this.source;\n return source && source.subscribe(subscriber);\n };\n Observable.prototype[observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n if (operations.length === 0) {\n return this;\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nfunction getPromiseCtor(promiseCtor) {\n if (!promiseCtor) {\n promiseCtor = Promise;\n }\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n return promiseCtor;\n}\n//# sourceMappingURL=Observable.js.map\n\nfunction tnLineStdinReader() {\n return new Observable(function (subscribe) {\n var stdin = readline.createInterface(process.stdin);\n var tests = null;\n var n = null;\n stdin.on('line', function (line) {\n if (tests === null) {\n tests = +line;\n } else if (n === null) {\n n = +line;\n tests--;\n } else {\n n = null;\n subscribe.next(line);\n\n if (tests === 0) {\n stdin.close();\n subscribe.complete();\n }\n }\n });\n });\n}\n\nfunction isHappy(arr) {\n if (arr[0] <= 0 || arr[arr.length - 1] <= 0) {\n return 'NO';\n }\n\n var sum = 0;\n\n for (var x = 0; x < arr.length - 2; x++) {\n sum += arr[x];\n\n if (sum <= 0) {\n return 'NO';\n }\n }\n\n sum = 0;\n\n for (var _x = arr.length - 1; _x > 0; _x--) {\n sum += arr[_x];\n\n if (sum <= 0) {\n return 'NO';\n }\n }\n\n return 'YES';\n}\n\ntnLineStdinReader().subscribe(function (input) {\n var arr = input.split(' ').map(function (i) {\n return +i;\n });\n console.log(isHappy(arr));\n});\n"}, {"source_code": "'use strict'\n\nlet t = parseInt(readline())\nwhile (t --> 0) {\n const n = parseInt(readline())\n const arr = readline().split(' ').map(function(x) {\n return parseInt(x)\n })\n\n let max_so_far = Number.MIN_SAFE_INTEGER\n let max_here = 0\n let neg = false\n \n for (let i = 0; i < n; ++i) {\n if (arr[i] < 0) neg = true\n max_here += arr[i]\n \n if (max_here < 0) {\n max_here = 0\n }\n \n if (max_so_far < max_here) {\n max_so_far = max_here\n }\n }\n \n let ok = false\n if (max_so_far < max_here) {\n ok = true\n } else if (max_so_far == max_here) {\n if (!neg) ok = true\n }\n\n print(ok ? 'YES': 'NO')\n}"}, {"source_code": "var numRun= readline();\n\nfor(var n=0;n0){seg+=num; if(maxSegmaxSeg||(segCt==totCt&&tot==maxSeg)){print(\"YES\");}\n else{print(\"NO\");}\n \n \n}//num runs\n\n\n"}, {"source_code": "var numRun= readline();\n \nfor(var n=0;nmaxSeg){maxSeg=seg;}}\n //if(num>0){seg+=num; if(maxSegmaxSeg||(segCt==totCt&&tot==maxSeg&&arr[0]!=0&&arr[arr.length-1]!=0)){print(\"YES\");}\n else{print(\"NO\");}\n \n \n}//num runs\n "}, {"source_code": "var numRun= readline();\n \nfor(var n=0;nmaxSeg){maxSeg=seg;}}\n //if(num>0){seg+=num; if(maxSegmaxSeg||(segCt==totCt&&tot==maxSeg&&arr[0]!=0&&arr[arr.length-1]!=0)){print(\"YES\");}\n else{print(\"NO\");}\n \n \n}//num runs\n "}, {"source_code": "var numRun= readline();\n\nfor(var n=0;nmaxSeg){maxSeg=seg;}}\n //if(num>0){seg+=num; if(maxSegmaxSeg||(segCt==totCt&&tot==maxSeg)){print(\"YES\");}\n else{print(\"NO\");}\n \n \n}//num runs\n\n\n"}, {"source_code": "var numRun= readline();\n\nfor(var n=0;nmaxSeg){maxSeg=seg;}}\n //if(num>0){seg+=num; if(maxSegmaxSeg||(segCt==totCt&&tot==maxSeg&&arr[0]!=0&&arr[arr.length-1]!=0)){print(\"YES\");}\n else{print(\"NO\");}\n \n \n}//num runs\n\n\n"}, {"source_code": "var numRun= readline();\n\nfor(var n=0;n0){seg+=num; if(maxSegmaxSeg||!noNeg){print(\"YES\");}\n else{print(\"NO\");}\n \n \n}//num runs\n"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = parseInt(readline(), 10);\n const cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));\n \n const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n print('YES');\n } else {\n if (total_taste > result.max_so_far) {\n print('YES');\n } else {\n print('NO');\n }\n }\n }\n}\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nmain();\n\nfunction main() {\n const test_cases = readline();\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = readline();\n const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));\n \n // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n print(cupcakes_count, cupcakes_taste);\n // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n // print('YES');\n // } else {\n // if (total_taste > result.max_so_far) {\n // print('YES');\n // } else {\n // print('NO');\n // }\n // }\n }\n}\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = parseInt(readline(), 10);\n const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));\n \n // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n print(cupcakes_taste);\n // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n // print('YES');\n // } else {\n // if (total_taste > result.max_so_far) {\n // print('YES');\n // } else {\n // print('NO');\n // }\n // }\n }\n}\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n var cupcakes_count = parseInt(readline(), 10);\n var cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));\n \n var total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n var result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n \n if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n print('YES');\n } else {\n if (total_taste > result.max_so_far) {\n print('YES');\n } else {\n print('NO');\n }\n }\n }\n}\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = readline();\n const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));\n \n // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n print(cupcakes_count, cupcakes_taste);\n // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n // print('YES');\n // } else {\n // if (total_taste > result.max_so_far) {\n // print('YES');\n // } else {\n // print('NO');\n // }\n // }\n }\n}\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = parseInt(readline(), 10);\n const cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));\n \n const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n print(cupcakes_taste, total_taste, result)\n // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n // print('YES');\n // } else {\n // if (total_taste > result.max_so_far) {\n // print('YES');\n // } else {\n // print('NO');\n // }\n // }\n }\n}\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = parseInt(readline(), 10);\n const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));\n \n // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n print(cupcakes_count, cupcakes_taste);\n // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n // print('YES');\n // } else {\n // if (total_taste > result.max_so_far) {\n // print('YES');\n // } else {\n // print('NO');\n // }\n // }\n }\n}\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\n// function print(item) {\n// console.log(item);\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = parseInt(readline(), 10);\n const cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));\n \n const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n print('YES');\n } else {\n if (total_taste > result.max_so_far) {\n print('YES');\n } else {\n print('NO');\n }\n }\n }\n}\n\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = readline();\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = readline();\n const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));\n \n // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n print(cupcakes_count, cupcakes_taste);\n // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n // print('YES');\n // } else {\n // if (total_taste > result.max_so_far) {\n // print('YES');\n // } else {\n // print('NO');\n // }\n // }\n }\n}\nmain();"}, {"source_code": "// 'use strict';\n\n// process.stdin.resume();\n// process.stdin.setEncoding('utf-8');\n\n// let inputString = '';\n// let currentLine = 0;\n\n// process.stdin.on('data', inputStdin => {\n// inputString += inputStdin;\n// });\n\n// process.stdin.on('end', _ => {\n// inputString = inputString.trim().split('\\n').map(string => {\n// return string.trim();\n// });\n \n// main(); \n// });\n\n// function readline() {\n// return inputString[currentLine++];\n// }\n\n// function print(item) {\n// console.log(item);\n// }\n\nfunction maxSubArraySum(array_of_numbers, array_size) {\n var max_so_far = Number.MIN_SAFE_INTEGER;\n var max_ending_here = 0;\n var start_index = 0;\n var end_index = 0;\n var start_tmp = 0; \n\n for (var i = 0; i < array_size; i++) { \n max_ending_here += array_of_numbers[i];\n\n if (max_so_far < max_ending_here) {\n max_so_far = max_ending_here;\n start_index = start_tmp;\n end_index = i;\n }\n\n if (max_ending_here < 0) {\n max_ending_here = 0;\n start_tmp = i + 1;\n }\n }\n return { max_so_far, start_index, end_index }; \n}\n\nfunction main() {\n const test_cases = parseInt(readline(), 10);\n for(var i = 0; i < test_cases; i++) {\n const cupcakes_count = parseInt(readline(), 10);\n const cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));\n \n const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);\n\n const result = maxSubArraySum(cupcakes_taste, cupcakes_count);\n if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {\n print('YES');\n } else {\n if (total_taste > result.max_so_far) {\n print('YES');\n } else {\n print('NO');\n }\n }\n }\n}"}], "src_uid": "6e5b4d43e64645cf26d5eac31437b1a9"} {"nl": {"description": "Inflation has occurred in Berlandia, so the store needs to change the price of goods.The current price of good $$$n$$$ is given. It is allowed to increase the price of the good by $$$k$$$ times, with $$$1 \\le k \\le m$$$, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum number of zeros at the end.For example, the number 481000 is more round than the number 1000010 (three zeros at the end of 481000 and only one at the end of 1000010).If there are several possible variants, output the one in which the new price is maximal.If it is impossible to get a rounder price, output $$$n \\cdot m$$$ (that is, the maximum possible price).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) —the number of test cases in the test. Each test case consists of one line. This line contains two integers: $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^9$$$). Where $$$n$$$ is the old price of the good, and the number $$$m$$$ means that you can increase the price $$$n$$$ no more than $$$m$$$ times.", "output_spec": "For each test case, output on a separate line the roundest integer of the form $$$n \\cdot k$$$ ($$$1 \\le k \\le m$$$, $$$k$$$ — an integer). If there are several possible variants, output the one in which the new price (value $$$n \\cdot k$$$) is maximal. If it is impossible to get a more rounded price, output $$$n \\cdot m$$$ (that is, the maximum possible price).", "sample_inputs": ["10\n\n6 11\n\n5 43\n\n13 5\n\n4 16\n\n10050 12345\n\n2 6\n\n4 30\n\n25 10\n\n2 81\n\n1 7"], "sample_outputs": ["60\n200\n65\n60\n120600000\n10\n100\n200\n100\n7"], "notes": "NoteIn the first case $$$n = 6$$$, $$$m = 11$$$. We cannot get a number with two zeros or more at the end, because we need to increase the price $$$50$$$ times, but $$$50 > m = 11$$$. The maximum price multiple of $$$10$$$ would be $$$6 \\cdot 10 = 60$$$.In the second case $$$n = 5$$$, $$$m = 43$$$. The maximum price multiple of $$$100$$$ would be $$$5 \\cdot 40 = 200$$$.In the third case, $$$n = 13$$$, $$$m = 5$$$. All possible new prices will not end in $$$0$$$, then you should output $$$n \\cdot m = 65$$$.In the fourth case, you should increase the price $$$15$$$ times.In the fifth case, increase the price $$$12000$$$ times."}, "positive_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, m] = lines[l++].trim().split(' ').map(BigInt)\n output[i] = solve(n, m)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, m) {\n const [rn, c2n, c5n] = helper(n)\n let now = 1n\n if (c2n > c5n) {\n let k = 0n\n while (c2n >= c5n + k + 1n && now * 5n <= m) {\n k++\n now *= 5n\n }\n n *= now\n m = m / now\n } else if (c2n < c5n) {\n let k = 0n\n while (c2n + k + 1n <= c5n && now * 2n <= m) {\n k++\n now *= 2n\n }\n n *= now\n m = m / now\n }\n // console.log(c2n, c5n, now)\n const sm = m.toString()\n const base = sm.length - 1\n return n * (10n ** BigInt(base)) * BigInt(sm[0])\n}\nfunction helper(n) {\n let c2 = 0n, c5 = 0n\n while (n > 0n && !(n % 2n)) {\n n /= 2n\n c2++\n }\n while (n > 0n && !(n % 5n)) {\n n /= 5n\n c5++\n }\n return [n, c2, c5]\n}\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const [n, m] = rns();\r\n let len = 0,\r\n s = n.toString();\r\n for (let i = s.length - 1; i >= 0; i--) {\r\n if (s[i] === '0') len++;else break;\r\n }\r\n s = s.slice(0, s.length - len);\r\n let num = Number(s),\r\n res = 1;\r\n if (num % 5 === 0) {\r\n let cnt = 0;\r\n while (num % 5 === 0) {\r\n cnt++;\r\n num /= 5;\r\n }\r\n for (let i = cnt; i >= 0; i--) {\r\n if (2 ** i <= m) {\r\n res = 2 ** i;\r\n break;\r\n }\r\n }\r\n } else if (num % 2 === 0) {\r\n let cnt = 0;\r\n while (num % 2 === 0) {\r\n cnt++;\r\n num /= 2;\r\n }\r\n for (let i = cnt; i >= 0; i--) {\r\n if (5 ** i <= m) {\r\n res = 5 ** i;\r\n break;\r\n }\r\n }\r\n }\r\n for (; res * 10 <= m; res *= 10) {}\r\n const x = Math.floor(m / res);\r\n res *= x;\r\n return BigInt(n) * BigInt(res);\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n let s = solve(r);\r\n if (s === undefined) s = '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "83af7209bb8a81cde303af5d207c2749"} {"nl": {"description": "Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.", "input_spec": "The first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters «@».", "output_spec": "If there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them.", "sample_inputs": ["a@aa@a", "a@a@a", "@aa@a"], "sample_outputs": ["a@a,a@a", "No solution", "No solution"], "notes": null}, "positive_code": [{"source_code": "(()=>{\"use strict\";var t={675:(t,e)=>{Object.defineProperty(e,\"__esModule\",{value:!0}),Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){return Math.max(...this)},Array.prototype.min=function(){return Math.min(...this)},Array.prototype.sum=function(){let t=0;for(let e=0;e{if(a)return i=o.default.readFileSync(\"input.txt\").toString().trim().split(\"\\n\").map((t=>t.trim())),t(),void o.default.writeFileSync(\"output.txt\",l);process.stdin.resume(),process.stdin.setEncoding(\"utf-8\"),process.stdin.on(\"data\",(t=>{u+=t})),process.stdin.on(\"end\",(e=>{i=u.trim().split(\"\\n\").map((t=>t.trim())),t(),console.log(l)}))};function p(){return i[s++]}function c(){return p().split(\" \").map((t=>parseFloat(t)))}function d(){return p().split(\"\")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=c();for(;e>0;)t(),e--}))},readline:p,nextNumbers:c,nextNumbersMatrix:function(t){let e=[];for(let r=0;r{t.exports=require(\"fs\")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar text = trim(readline());\n\tvar match = text.match(/^([a-z]+\\@[a-z])*([a-z]+\\@[a-z]+)$/);\n\tif (match) {\n\t\tvar regex = /[a-z]+\\@[a-z]/g;\n\t\tvar groups = [];\n\t\twhile (true) {\n\t\t\tvar result = regex.exec(text);\n\t\t\tif (result === null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tgroups.push(result[0]);\n\t\t}\n\t\tvar tail = text.match(/[a-z]+$/)[0].substring(1);\n\t\tgroups[groups.length-1] += tail;\n\t\tprint(groups.join(\",\"));\n\t}\n\telse {\n\t\tprint(\"No solution\");\n\t}\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar text = trim(readline());\n\n\tvar groups = [];\n\tvar start = 0;\n\n\twhile (true) {\n\n\t\tvar pos = text.indexOf(\"@\", start);\n\n\t\tif (pos == -1) {\n\t\t\tif (groups.length == 0) {\n\t\t\t\tprint(\"No solution\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgroups[groups.length-1] += text.substring(start);\n\t\t\t\tprint(groups.join(\",\"));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (pos == start || pos == text.length-1 || text.charAt(pos+1) == '@') {\n\t\t\tprint(\"No solution\");\n\t\t\treturn;\n\t\t}\n\n\t\tgroups.push(text.substring(start, pos+2));\n\t\tstart = pos+2;\n\t}\n}\n\nmain();\n"}, {"source_code": "var s = readline()\nprint((s.match(/^@|@.?@|@$/) || !~s.indexOf('@')) ? 'No solution' : s.match(/[a-z]+@[a-z]/g).join() + s.slice(s.lastIndexOf('@') + 2))"}, {"source_code": "'use strict'\n\nlet lll = readline()\n\n;(function () {\n let spt = lll.split('@')\n if (spt.length < 2) return print('No solution')\n if (!spt[0] || !spt[spt.length - 1]) return print('No solution')\n if (spt.slice(1, -1).length != spt.slice(1, -1).filter(v => v.length > 1).length)\n return print('No solution')\n\n let as\n if (spt.length > 2) {\n as = [spt[0] + '@' + spt[1][0]]\n for (let i = 1; i < spt.length - 2; i++) {\n as.push(spt[i].slice(1) + '@' + spt[i + 1][0])\n }\n as.push(spt[spt.length - 2].slice(1) + '@' + spt[spt.length - 1])\n } else {\n as = [spt.join('@')]\n }\n print(as.join(','))\n}())"}, {"source_code": "//var numbers = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar emails = readline();\nvar answ = [];\ndropStr(emails);\n\nfunction dropStr(str) {\n for (var i = 0; i < str.length; ++i) {\n if (str[i] == '@') {\n answ.push(str.substr(0, i+2));\n str = str.substr(i+2);\n break;\n }\n }\n if (str.length > 0 && str.indexOf('@') !== -1) {\n dropStr(str);\n } else {\n if (answ[answ.length-1])\n answ[answ.length-1] = answ[answ.length-1].concat(str);\n }\n}\nvar status = false;\nfor (var i = 0; i < answ.length; ++i) {\n var splited_anws = answ[i].split('@');\n if (splited_anws[0].length === 0 || splited_anws[1].length === 0) {\n status = true;\n }\n}\n\nif (!status && answ.length !== 0) {\n print(answ);\n} else {\n print('No solution');\n}"}], "negative_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar text = trim(readline());\n\tvar groups = text.match(/^([a-z]+\\@[a-z])*([a-z]+\\@[a-z]+)$/);\n\tif (groups) {\n\t\tgroups.splice(0, 1);\n\t\tprint(groups.join(\",\"));\n\t}\n\telse {\n\t\tprint(\"No solution\");\n\t}\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar text = trim(readline());\n\tvar match = text.match(/^([a-z]+\\@[a-z])+$/);\n\tif (match) {\n\t\tvar groups = text.match(/[a-z]+\\@[a-z]/g);\n\t\tprint(groups.join(\",\"));\n\t}\n\telse {\n\t\tprint(\"No solution\");\n\t}\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar text = trim(readline());\n\n\tvar groups = [];\n\tvar start = 0;\n\n\twhile (true) {\n\n\t\tvar pos = text.indexOf(\"@\", start);\n\n\t\tif (pos == -1) {\n\t\t\tif (groups.length == 0) {\n\t\t\t\tprint(\"No solution\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgroups[groups.length-1] += text.substring(start);\n\t\t\t\tprint(groups.join(\",\"));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (pos == start || pos == text.length-1) {\n\t\t\tprint(\"No solution\");\n\t\t\treturn;\n\t\t}\n\n\t\tgroups.push(text.substring(start, pos+2));\n\t\tstart = pos+2;\n\t}\n}\n\nmain();\n"}, {"source_code": "var s = readline()\nprint(/@.?@|^@|@$/.exec(s) ? \"No solution\" : s.match(/\\w+@(\\w+$|.)/g) + \"\")"}, {"source_code": "var s = readline()\nprint(s.match(/^@|@.?@|@$/) ? 'No solution' : s.match(/[a-z]+@[a-z]/g).join())"}, {"source_code": "var s = readline()\nprint(s.match(/^@|@.?@|@$/) || !~s.indexOf('@')) ? 'No solution' : s.match(/[a-z]+@[a-z]/g).join() + s.slice(s.lastIndexOf('@') + 2)"}, {"source_code": "'use strict'\n\nlet lll = readline()\n\n;(function () {\n let spt = lll.split('@')\n if (spt.length < 2) return print('No solution')\n if (!spt[0] || !spt[spt.length - 1]) return print('No solution')\n if (spt.slice(1, -1).length != spt.slice(1, -1).filter(v => v.length > 1).length)\n return print('No solution')\n\n let as = [spt[0] + '@' + spt[1][0]]\n for (let i = 1; i < spt.length - 2; i++) {\n as.push(spt[i].slice(1) + '@' + spt[i + 1][0])\n }\n as.push(spt[spt.length - 2].slice(1) + '@' + spt[spt.length - 1])\n print(as.join(','))\n}())"}], "src_uid": "71b4674e91e0bc5521c416cfc570a090"} {"nl": {"description": "There is an easy way to obtain a new task from an old one called \"Inverse the problem\": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.Now let's create a task this way. We will use the task: you are given a tree, please calculate the distance between any pair of its nodes. Yes, it is very easy, but the inverse version is a bit harder: you are given an n × n distance matrix. Determine if it is the distance matrix of a weighted tree (all weights must be positive integers).", "input_spec": "The first line contains an integer n (1 ≤ n ≤ 2000) — the number of nodes in that graph. Then next n lines each contains n integers di, j (0 ≤ di, j ≤ 109) — the distance between node i and node j.", "output_spec": "If there exists such a tree, output \"YES\", otherwise output \"NO\".", "sample_inputs": ["3\n0 2 7\n2 0 9\n7 9 0", "3\n1 2 7\n2 0 9\n7 9 0", "3\n0 2 2\n7 0 9\n7 9 0", "3\n0 1 1\n1 0 1\n1 1 0", "2\n0 0\n0 0"], "sample_outputs": ["YES", "NO", "NO", "NO", "NO"], "notes": "NoteIn the first example, the required tree exists. It has one edge between nodes 1 and 2 with weight 2, another edge between nodes 1 and 3 with weight 7.In the second example, it is impossible because d1, 1 should be 0, but it is 1.In the third example, it is impossible because d1, 2 should equal d2, 1."}, "positive_code": [{"source_code": "var n = parseInt(readline());\nvar a = new Array();\nfor(var i=0;i node i is used.\nvar u = new Array();\nfor(var i=0;i node i is used.\nvar u = new Array();\nfor(var i=0;i node i is used.\nvar u = new Array();\nfor(var i=0;i node i is used.\nvar u = new Array();\nfor(var i=0;i0)\r\n{\r\n var a = readline();\r\n var st = readline();\r\n\r\n flag=0;\r\n for(i=0;i 1) {\n print(-1);\n } else {\n print(1);\n }\n continue;\n }\n print(pow(s.length));\n}\n"}, {"source_code": "var tests = parseInt(readline());\r\n var s, t;\r\n for (var ti=0; ti < tests; ti++) {\r\n s = readline();\r\n t = readline();\r\n if (t == 'a') {\r\n print(1);\r\n continue;\r\n }\r\n if (t.indexOf('a') != -1) {\r\n print(-1);\r\n continue;\r\n }\r\n\r\n print(Math.pow(2, s.length));\r\n }"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n//console.log(input);\r\nvar T = readline();\r\nvar f = [];\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n \r\n // var s = 'aa', t = 'bbc'\r\n var len = s.length-1;\r\n var l = q == T ? t.length : t.length-1;\r\n var cnt = 0;\r\n var ans = 1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n }\r\n console.log(ans)\r\n \r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\nfunction Main(){\r\n // input in nodeJs\r\n\tvar t = nextInt();\r\n // console.log(\"\\n ===============-===========\")\r\n\twhile(hasNext()){\r\n\t\tconst stringArr = nextCharArray().join(\"\");\r\n\t\tconst replace = nextCharArray().join(\"\");\r\n // if (!stringArr.includes(\"a\")){\r\n // myout(1);\r\n // continue;\r\n // }\r\n\r\n if (replace.length >= 2 && replace.includes(\"a\")) {\r\n myout(-1);\r\n continue;\r\n }\r\n\r\n if (replace.length === 1 && replace[0] === \"a\") {\r\n myout(1);\r\n continue;\r\n }\r\n\r\n myout(Math.pow(2, stringArr.length));\r\n // console.log(stringArr, replace)\r\n\t}\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar L = next();\r\n\t\tvar R = next();\r\n\t\tif(R == \"a\"){\r\n\t\t\tmyout(1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif(L.indexOf(\"a\") != -1 && R.indexOf(\"a\") != -1){\r\n\t\t\tmyout(-1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tvar c = 0n;\r\n\t\tfor(var i = 0; i < L.length; i++){\r\n\t\t\tif(L[i] == \"a\"){\r\n\t\t\t\tc++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(1n << c);\r\n\t}\r\n}\r\n"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\nconst cnk = (n, k) => {\n let res = 1;\n for (let i = 1; i <= k; i++)\n res = res * (n - k + i) / i;\n return Math.round(res + 0.01);\n}\n\n\nconst sumab = (a, b) => {\n let x = (b - a + 1);\n let y = a + b;\n if (x % 2 === 0) {\n x = Math.round(x / 2);\n } else {\n y = Math.round(y / 2);\n }\n return BigInt(x) * BigInt(y);\n}\n\n\n\nconst calc = (s, t)=>{\n if (t === 'a') return 1;\n if (t.includes('a')) return -1;\n\n let n = s.length;\n let result = 0;\n for (let i = 0; i <= n; i++) {\n result += cnk(n, i);\n }\n return result;\n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let s = readline();\n let t = readline();\n console.log(`${calc(s, t)}`);\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nconst nums = [];\r\nlet res = 1n;\r\nfor (let i = 1n; i <= 50n; i++) {\r\n res *= i;\r\n nums[Number(i)] = res;\r\n}\r\nfunction solve(s, t) {\r\n if (t.indexOf('a') !== -1 && t.length > 1) {\r\n console.log(-1);\r\n } else if (t === 'a') {\r\n console.log(1);\r\n } else {\r\n let n = s.length,\r\n res = 2n;\r\n for (let i = 1; i < n; i++) {\r\n res += nums[n] / (nums[i] * nums[n - i]);\r\n }\r\n console.log(res.toString());\r\n }\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const s = await read();\r\n const t = await read();\r\n solve(s, t);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\n\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst lines = []\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\nrl.on('line', line => {\n lines.push(line);\n});\nrl.on('close', main)\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst L = process.env.DEBUG ? console.log : ()=>{};\n \nconst pcalc = function(){\n print(calc.apply(null, arguments)); }\n\nconst ra = ()=>readline().split(' ').map(a=>+a)\n\n// SOLUTION\n \nconst calc = (a, t)=>{\n if (t=='a'){\n return 1;\n }\n if (t.indexOf('a')>=0)\n return -1;\n let num = BigInt(1);\n for (let i=0; i {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const str = lines[l++]\n const replace = lines[l++]\n output[i] = solve(str, replace)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(str, replace) {\n if (replace === 'a') return 1\n if (replace.indexOf('a') >= 0) return -1\n // return pow(str.length, replace.length)\n let a = BigInt(str.length)\n // let b = BigInt(replace.length)\n let ans = 1n\n while (a--) {\n ans *= 2n\n }\n return ans\n}\n"}], "negative_code": [{"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aa', t = 'bbc'\r\n var len = q == 10000 ? s.length : s.length-1;\r\n var l = q == 10000 ? t.length: t.length-1;\r\n var cnt = 0;\r\n var ans = 1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n }\r\n console.log(ans);\r\n \r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aa', t = 'bbc'\r\n var len = q == T ? s.length : s.length-1;\r\n var l = q == T ? t.length: t.length-1;\r\n var cnt = 0;\r\n var ans = 1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n }\r\n console.log(ans);\r\n \r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aa', t = 'bbc'\r\n var len = s.length-1;\r\n var l = t.length-1;\r\n var cnt = 0;\r\n var ans = 1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n }\r\n if(q == 10000) {\r\n \r\n console.log(t);\r\n }\r\n console.log(ans);\r\n \r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aa', t = 'bbc'\r\n var len = s.length-1;\r\n var l = t.length-1;\r\n var cnt = 0;\r\n var ans = 1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n }\r\n if(q == 10000) {\r\n console.log(s);\r\n console.log(t);\r\n }\r\n console.log(ans);\r\n \r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aa', t = 'bbc'\r\n var len = s.length-1;\r\n var l = t.length-1;\r\n var cnt = 0;\r\n var ans = 1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n }\r\n console.log(ans);\r\n if(q == 10000) {\r\n console.log(s);\r\n console.log(t);\r\n }\r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aa', t = 'bbc'\r\n var len = s.length-1;\r\n var l = t.length-1;\r\n var cnt = 0;\r\n var ans = 1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n }\r\n console.log(ans);\r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aaaa', t = 'a'\r\n var cntS = 0, cntT = 0, l = t.length-1;\r\n var ans = -1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n } else {\r\n if(cntS > 0) ans = Math.pow(2, cntS);\r\n else ans = 1;\r\n }\r\n console.log(ans);\r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aaaa', t = 'a'\r\n var cntS = 0, cntT = 0, l = t.length-1;\r\n var ans = -1;\r\n for(var i=0;i 1) ans = -1;\r\n else ans = 1;\r\n } else {\r\n if(cntS > 1) ans = Math.pow(2, cntS);\r\n else ans = 1;\r\n }\r\n console.log(ans);\r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aaaa', t = 'a'\r\n var cntS = 0, cntT = 0, l = t.length-1;\r\n var ans = -1;\r\n for(var i=0;i 1) ans = -1;\r\n else {\r\n if(l == 1) ans = 1;\r\n else ans = 2;\r\n }\r\n } else {\r\n if(cntS === 0) ans = 1;\r\n else {\r\n ans = Math.pow(2, cntS);\r\n }\r\n }\r\n console.log(ans);\r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aaaa', t = 'a'\r\n var cntS = 0, cntT = 0, l = t.length;\r\n var ans = -1;\r\n for(var i=0;i 1) ans = -1;\r\n else {\r\n if(l == 1) ans = 1;\r\n else ans = 2;\r\n }\r\n } else {\r\n if(cntS === 0) ans = 1;\r\n else {\r\n ans = Math.pow(2, cntS);\r\n }\r\n }\r\n console.log(s)\r\n console.log(t)\r\n console.log(s.length)\r\n console.log(t.length)\r\n console.log(ans);\r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\nvar T = readline();\r\n\r\nfor(var q=1;q<=T;q++) {\r\n var s = readline();\r\n var t = readline();\r\n // var s = 'aaaa', t = 'a'\r\n var cntS = 0, cntT = 0, l = t.length;\r\n var ans = -1;\r\n for(var i=0;i 1) ans = -1;\r\n else {\r\n if(l == 1) ans = 1;\r\n else ans = 2;\r\n }\r\n } else {\r\n if(cntS === 0) ans = 1;\r\n else {\r\n ans = Math.pow(2, cntS);\r\n }\r\n }\r\n console.log(ans);\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\nfunction Main(){\r\n // input in nodeJs\r\n\tvar t = nextInt();\r\n // console.log(\"\\n ===============-===========\")\r\n\twhile(hasNext()){\r\n\t\tconst stringArr = nextCharArray().join(\"\");\r\n\t\tconst replace = nextCharArray().join(\"\");\r\n if (!stringArr.includes(\"a\")){\r\n myout(1);\r\n continue;\r\n }\r\n\r\n if (replace.length >= 2 && replace.includes(\"a\")) {\r\n myout(-1);\r\n continue;\r\n }\r\n\r\n if (replace.length === 1 && replace[0] === \"a\") {\r\n myout(1);\r\n continue;\r\n }\r\n\r\n myout(stringArr.split(\"\").filter(ele => ele === \"a\").length + 1);\r\n // console.log(stringArr, replace)\r\n\t}\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\nfunction Main(){\r\n // input in nodeJs\r\n\tvar t = nextInt();\r\n // console.log(\"\\n ===============-===========\")\r\n\twhile(hasNext()){\r\n\t\tconst stringArr = nextCharArray().join(\"\");\r\n\t\tconst replace = nextCharArray().join(\"\");\r\n\r\n if (replace.length >= 2 && replace.includes(\"a\")) {\r\n myout(-1);\r\n continue;\r\n }\r\n\r\n if (replace.length === 1 && replace[0] === \"a\") {\r\n myout(1);\r\n continue;\r\n }\r\n\r\n myout(stringArr.split(\"\").filter(ele => ele === \"a\").length + 1);\r\n // console.log(stringArr, replace)\r\n\t}\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\t// console.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n \r\nfunction Main(){\r\n // input in nodeJs\r\n\tvar t = nextInt();\r\n console.log(\"\\n ===============-===========\")\r\n\twhile(hasNext()){\r\n\t\tconst stringArr = nextCharArray().join(\"\");\r\n\t\tconst replace = nextCharArray().join(\"\");\r\n\r\n if (replace.length >= 2 && replace.includes(\"a\")) {\r\n myout(-1);\r\n continue;\r\n }\r\n\r\n if (replace.length === 1 && replace[0] === \"a\") {\r\n myout(1);\r\n continue;\r\n }\r\n\r\n myout(stringArr.split(\"\").filter(ele => ele === \"a\").length + 1);\r\n // console.log(stringArr, replace)\r\n\t}\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar L = next();\r\n\t\tvar R = next();\r\n\t\tif(R == \"a\"){\r\n\t\t\tmyout(1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif(L.indexOf(\"a\") != -1 && R.indexOf(\"a\") != -1){\r\n\t\t\tmyout(-1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tvar c = 0;\r\n\t\tfor(var i = 0; i < L.length; i++){\r\n\t\t\tif(L[i] == \"a\"){\r\n\t\t\t\tc++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(1 << c);\r\n\t}\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar L = next();\r\n\t\tvar R = next();\r\n\t\tif(R == \"a\"){\r\n\t\t\tmyout(1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif(R.indexOf(\"a\") != -1){\r\n\t\t\tmyout(-1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tvar c = 0;\r\n\t\tfor(var i = 0; i < L.length; i++){\r\n\t\t\tif(L[i] == \"a\"){\r\n\t\t\t\tc++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmyout(1 << c);\r\n\t}\r\n}\r\n"}], "src_uid": "d6ac9ca9cc5dfd9f43f5f65ce226349e"} {"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$$$) — number of chapters. Then $$$n$$$ lines follow. The $$$i$$$-th line begins with an integer $$$k_i$$$ ($$$0 \\le k_i \\le n-1$$$) — 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 — 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": "const readline = require(\"readline\");\r\nconst os = require(\"os\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nlet lineNum = 0, consumed = 0, lineNo = 0\r\nlet input = []\r\nlet res = []\r\nlet out = []\r\n\r\n\r\nrl.on(\"line\", (line) => {\r\n input.push(line)\r\n if (input.length === 2) {\r\n lineNum = +input[1]\r\n }\r\n \r\n if(input.length > 2) {\r\n consumed++\r\n input.pop()\r\n\r\n const tmp = line.split(' ').map(e => +e)\r\n lineNo++\r\n if(tmp.length > 1) {\r\n for(let j = 1; j < tmp.length; j++) {\r\n res.push([tmp[j], lineNo])\r\n }\r\n }\r\n\r\n if(consumed === lineNum) {\r\n const ans = solution(res, lineNum)\r\n out.push(ans === -1 ? -1 : ans)\r\n input.length = 1\r\n consumed = 0\r\n lineNo = 0\r\n res = []\r\n }\r\n }\r\n\r\n});\r\nrl.on(\"close\", () => {\r\n let str = ''\r\n for(const e of out) str += e + os.EOL\r\n console.log(str)\r\n});\r\n\r\nfunction solution(arr, n) {\r\n const graph = {}, inDegree = Array(n + 1).fill(0)\r\n for(const [u, v] of arr) {\r\n if(graph[u] == null) graph[u] = []\r\n graph[u].push(v)\r\n inDegree[v]++\r\n }\r\n const q = [], visited = new Set(), times = Array(n + 1).fill(0)\r\n for(let i = 1; i <= n; i++) {\r\n if(inDegree[i] === 0) {\r\n q.push(i)\r\n visited.add(i)\r\n }\r\n times[i] = 1\r\n }\r\n\r\n while(q.length) {\r\n const cur = q.pop()\r\n for(const next of (graph[cur] || [])) {\r\n inDegree[next]--\r\n if(cur < next) times[next] = Math.max(times[cur], times[next])\r\n else times[next] = Math.max(times[next], times[cur] + 1)\r\n if(inDegree[next] === 0) {\r\n q.push(next)\r\n visited.add(next)\r\n }\r\n }\r\n }\r\n\r\n if (visited.size === n) {\r\n return Math.max(...times)\r\n } else return -1\r\n}"}, {"source_code": "const readline = require(\"readline\");\r\nconst os = require(\"os\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nlet lineNo = 0, consumed = 0, lineth = 0\r\nlet input = []\r\nlet res = []\r\nlet out = []\r\n\r\n\r\nrl.on(\"line\", (line) => {\r\n input.push(line)\r\n if (input.length === 2) {\r\n lineNo = +input[1]\r\n }\r\n \r\n if(input.length > 2) {\r\n consumed++\r\n input.pop()\r\n\r\n const tmp = line.split(' ').map(e => +e)\r\n lineth++\r\n if(tmp.length > 1) {\r\n for(let j = 1; j < tmp.length; j++) {\r\n res.push([tmp[j], lineth])\r\n }\r\n }\r\n\r\n if(consumed === lineNo) {\r\n const ans = solution(res, lineNo)\r\n out.push(ans === -1 ? -1 : ans)\r\n input.length = 1\r\n consumed = 0\r\n lineth = 0\r\n res = []\r\n }\r\n }\r\n\r\n});\r\nrl.on(\"close\", () => {\r\n let str = ''\r\n for(const e of out) str += e + os.EOL\r\n console.log(str)\r\n});\r\n\r\nfunction solution(arr, n) {\r\n const graph = {}, inDegree = Array(n + 1).fill(0)\r\n for(const [u, v] of arr) {\r\n if(graph[u] == null) graph[u] = []\r\n graph[u].push(v)\r\n inDegree[v]++\r\n }\r\n const q = [], visited = new Set(), times = Array(n + 1).fill(0)\r\n for(let i = 1; i <= n; i++) {\r\n if(inDegree[i] === 0) {\r\n q.push(i)\r\n visited.add(i)\r\n }\r\n times[i] = 1\r\n }\r\n\r\n while(q.length) {\r\n const cur = q.pop()\r\n for(const next of (graph[cur] || [])) {\r\n inDegree[next]--\r\n if(cur < next) times[next] = Math.max(times[cur], times[next])\r\n else times[next] = Math.max(times[next], times[cur] + 1)\r\n if(inDegree[next] === 0) {\r\n q.push(next)\r\n visited.add(next)\r\n }\r\n }\r\n }\r\n\r\n if (visited.size === n) {\r\n return Math.max(...times)\r\n } else return -1\r\n}"}, {"source_code": "const readline = require(\"readline\");\r\nconst os = require(\"os\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nlet lineNum = 0, consumed = 0, lineNo = 0\r\nlet input = []\r\nlet res = []\r\nlet out = []\r\n\r\n\r\nrl.on(\"line\", (line) => {\r\n input.push(line)\r\n if (input.length === 2) {\r\n lineNum = +input[1]\r\n }\r\n \r\n if(input.length > 2) {\r\n consumed++\r\n input.pop()\r\n\r\n const tmp = line.split(' ').map(e => +e)\r\n lineNo++\r\n if(tmp.length > 1) {\r\n for(let j = 1; j < tmp.length; j++) {\r\n res.push([tmp[j], lineNo])\r\n }\r\n }\r\n\r\n if(consumed === lineNum) {\r\n const ans = solution(res, lineNum)\r\n out.push(ans === -1 ? -1 : ans)\r\n input.length = 1\r\n consumed = 0\r\n lineNo = 0\r\n res = []\r\n }\r\n }\r\n\r\n});\r\nrl.on(\"close\", () => {\r\n let str = ''\r\n for(const e of out) str += e + os.EOL\r\n console.log(str)\r\n});\r\n\r\nfunction solution(arr, n) {\r\n const graph = {}, inDegree = Array(n + 1).fill(0)\r\n for(const [u, v] of arr) {\r\n if(graph[u] == null) graph[u] = []\r\n graph[u].push(v)\r\n inDegree[v]++\r\n }\r\n const q = [], visited = new Set(), times = Array(n + 1).fill(0)\r\n for(let i = 1; i <= n; i++) {\r\n if(inDegree[i] === 0) {\r\n q.push(i)\r\n visited.add(i)\r\n }\r\n times[i] = 1\r\n }\r\n\r\n while(q.length) {\r\n const cur = q.pop()\r\n for(const next of (graph[cur] || [])) {\r\n inDegree[next]--\r\n if(cur < next) times[next] = Math.max(times[cur], times[next])\r\n else times[next] = Math.max(times[next], times[cur] + 1)\r\n if(inDegree[next] === 0) {\r\n q.push(next)\r\n visited.add(next)\r\n }\r\n }\r\n }\r\n\r\n if (visited.size === n) {\r\n return Math.max(...times)\r\n } else return -1\r\n}\r\n"}], "negative_code": [{"source_code": "const readline = require(\"readline\");\r\nconst os = require(\"os\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nlet lineNo = 0, consumed = 0, lineth = 0\r\nlet input = []\r\nlet res = []\r\n\r\nrl.on(\"line\", (line) => {\r\n input.push(line)\r\n if (input.length === 2) {\r\n lineNo = +input[1]\r\n }\r\n \r\n if(input.length > 2) {\r\n consumed++\r\n\r\n const tmp = line.split(' ').map(e => +e)\r\n lineth++\r\n if(tmp.length > 1) {\r\n for(let j = 1; j < tmp.length; j++) {\r\n res.push([tmp[j], lineth])\r\n }\r\n }\r\n\r\n if(consumed === lineNo) {\r\n input.length = 1\r\n consumed = 0\r\n lineth = 0\r\n res = []\r\n const ans = solution(res, lineNo)\r\n console.log(ans === -1 ? -1 : ans)\r\n }\r\n }\r\n\r\n});\r\nrl.on(\"close\", () => {\r\n});\r\n\r\nfunction solution(arr, n) {\r\n const graph = {}, inDegree = Array(n + 1).fill(0)\r\n for(const [u, v] of arr) {\r\n if(graph[u] == null) graph[u] = []\r\n graph[u].push(v)\r\n inDegree[v]++\r\n }\r\n const q = [], visited = new Set(), times = Array(n + 1).fill(0)\r\n for(let i = 1; i <= n; i++) {\r\n if(inDegree[i] === 0) {\r\n q.push(i)\r\n visited.add(i)\r\n }\r\n times[i] = 1\r\n }\r\n\r\n while(q.length) {\r\n const cur = q.shift()\r\n for(const next of (graph[cur] || [])) {\r\n inDegree[next]--\r\n if(cur < next) times[next] = Math.max(times[cur], times[next])\r\n else times[next] = Math.max(times[next], times[cur] + 1)\r\n if(inDegree[next] === 0) {\r\n q.push(next)\r\n visited.add(next)\r\n }\r\n }\r\n }\r\n\r\n if (visited.size === n) {\r\n return Math.max(...times)\r\n } else return -1\r\n}"}, {"source_code": "const readline = require(\"readline\");\r\nconst os = require(\"os\");\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nlet lineNo = 0, consumed = 0\r\nlet input = []\r\nlet res = []\r\n\r\nrl.on(\"line\", (line) => {\r\n input.push(line)\r\n if (input.length === 2) {\r\n lineNo = +input[1]\r\n }\r\n \r\n if(input.length > 2) {\r\n consumed++\r\n\r\n const tmp = line.split(' ').map(e => +e)\r\n if(tmp.length > 1) {\r\n for(let j = 1; j < tmp.length; j++) {\r\n res.push([tmp[j], consumed])\r\n }\r\n }\r\n\r\n if(consumed === lineNo) {\r\n input.length = 1\r\n consumed = 0\r\n res = []\r\n const ans = solution(res, lineNo)\r\n console.log(ans === -1 ? -1 : ans)\r\n }\r\n }\r\n\r\n});\r\nrl.on(\"close\", () => {\r\n});\r\n\r\nfunction solution(arr, n) {\r\n const graph = {}, inDegree = Array(n + 1).fill(0)\r\n for(const [u, v] of arr) {\r\n if(graph[u] == null) graph[u] = []\r\n graph[u].push(v)\r\n inDegree[v]++\r\n }\r\n const q = [], visited = new Set(), times = Array(n + 1).fill(0)\r\n for(let i = 1; i <= n; i++) {\r\n if(inDegree[i] === 0) {\r\n q.push(i)\r\n visited.add(i)\r\n }\r\n times[i] = 1\r\n }\r\n\r\n while(q.length) {\r\n const cur = q.shift()\r\n for(const next of (graph[cur] || [])) {\r\n inDegree[next]--\r\n if(cur < next) times[next] = Math.max(times[cur], times[next])\r\n else times[next] = Math.max(times[next], times[cur] + 1)\r\n if(inDegree[next] === 0) {\r\n q.push(next)\r\n visited.add(next)\r\n }\r\n }\r\n }\r\n\r\n if (visited.size === n) {\r\n return Math.max(...times)\r\n } else return -1\r\n}"}], "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$$$) — 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$$$) — 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": "var ip = readline().split(' ').map(Number);\nvar index = ip[0], k = ip[1];\nvar ar = readline().split(' ').sort((a,b)=>a-b),ans = Math.abs(k-ar[Math.floor(index/2)]),i=Math.floor(index/2)-1,j = Math.floor(index/2)+1;\nwhile (i >= 0 && ar[i] > k){\n ans+= (ar[i--]-k);\n}\nwhile (j < index && ar[j] < k){\n ans += (k-ar[j++]);\n}\nprint(ans);"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\n// function part(start, end) {\n// var p = nums[start];\n// while (start < end) {\n// while (start < end && nums[end] > p) {\n// end--;\n// }\n// nums[start] = nums[end];\n// while (start < end && nums[start] <= p) {\n// start++;\n// }\n// nums[end] = nums[start];\n// }\n// nums[start] = p;\n// return start;\n// }\n// function quickSort(k, start, end) {\n// if (start < end) {\n// var p = part(start, end);\n// if (p === k) return;\n// if (p > k) quickSort(k, start, p - 1);\n// if (p < k) quickSort(k - p - 1, p + 1, end);\n// }\n// }\n\n// quickSort(k, 0, n - 1);\nnums.sort(function (a, b) {\n return a - b;\n})\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}], "negative_code": [{"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\nvar rst = 0;\nfor (var i = k; i < n; i++){\n rst += Math.max(target - nums[i],0);\n}\nif (n>10) {\n print(`${nums.join(',')}`)\n} else {\n print(rst) \n}\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\n// nums.sort(function (a, b) {\n// return a - b;\n// })\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\nvar rst = 0;\nfor (var i = k; i < n; i++){\n rst += Math.max(target - nums[i],0);\n}\nif (n>10) {\n print(`${k} ${n} ${nums.join(',')}`)\n} else {\n print(rst) \n}\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\nvar rst = 0;\nfor (var i = k; i < n; i++){\n rst += Math.max(target - nums[i],0);\n}\n\nprint(`${k} ${n} ${nums.join(',')}`)\n"}, {"source_code": "\nvar n_target = readline();\n// // var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// // var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(nums.length / 2) + 1;\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k - 1) return;\n if (p > k - 1) quickSort(k, start, p - 1);\n if (p < k - 1) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, nums.length - 1);\n\n// quickSort(m, 0, nums.length - 1);\nvar rst = 0;\nif (nums[k-1]<= target) {\n for (var i = k-1; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i < k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}, {"source_code": "\n// var n_target = readline();\nvar n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\n// var nums = readline();\nvar nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\n// function part(start, end) {\n// var p = nums[start];\n// while (start < end) {\n// while (start < end && nums[end] > p) {\n// end--;\n// }\n// nums[start] = nums[end];\n// while (start < end && nums[start] <= p) {\n// start++;\n// }\n// nums[end] = nums[start];\n// }\n// nums[start] = p;\n// return start;\n// }\n// function quickSort(k, start, end) {\n// if (start < end) {\n// var p = part(start, end);\n// if (p === k) return;\n// if (p > k) quickSort(k, start, p - 1);\n// if (p < k) quickSort(k - p - 1, p + 1, end);\n// }\n// }\n\n// quickSort(k, 0, n - 1);\nnums.sort((a, b) => a - b);\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n\n\n\n"}, {"source_code": "\nvar n_target = readline();\nvar nums = readline();\n// function print(rst){ console.log(rst) }\n// var n_target = '7 20';\n// var nums = '21 15 12 11 20 19 12';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\n\n\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(nums.length / 2) + 1;\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n var p = part(start, end);\n if (start < end) {\n while (p !== k - 1) {\n // console.log(p, k, nums);\n if (p === k - 1) return;\n if (p > k - 1) {\n p = part(start, p - 1);\n end = p;\n continue;\n }\n if (p < k - 1) {\n p = part(p + 1 , end);\n start = p + 1;\n continue;\n }\n }\n // var p = part(start, end);\n // if (p === k - 1) return;\n // if (p > k - 1) quickSort(k, start, p - 1);\n // if (p < k - 1) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, nums.length - 1);\n\n// quickSort(m, 0, nums.length - 1);\nvar rst = 0;\nif (nums[k - 1] <= target) {\n for (var i = k - 1; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i < k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p);\n if (p < k) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\n// nums.sort(function (a, b) {\n// return a - b;\n// })\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\n// quickSort(k, 0, n - 1);\nnums.sort((a, b) => { return a - b });\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\nif (n === 499) {\n print(nums[k])\n} else {\n print(rst)\n}\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2) + 1;\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k-1) return;\n if (p > k-1) quickSort(k, start, p -1);\n if (p < k-1) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\n// nums.sort(function (a, b) {\n// return a - b;\n// })\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\nvar rst = 0;\nfor (var i = k; i < n; i++){\n rst += Math.max(target - nums[i],0);\n}\n\nprint(rst)\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2) + 1;\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k-1) return;\n if (p > k-1) quickSort(k, start, p );\n if (p < k-1) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\n// nums.sort(function (a, b) {\n// return a - b;\n// })\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(n / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\nquickSort(k, 0, n - 1);\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\nif (n === 499) {\n print(nums[k])\n} else {\n print(rst)\n}\n\n\n"}, {"source_code": "\nvar n_target = readline();\n// var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(nums.length / 2);\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k) return;\n if (p > k) quickSort(k, start, p - 1);\n if (p < k) quickSort(k - p, p + 1, end);\n }\n}\n\nquickSort(k, 0, nums.length - 1);\nvar rst = 0;\nfor (var i = k; i < nums.length; i++){\n rst += Math.max(target - nums[i],0);\n}\n\nprint(rst)\n"}, {"source_code": "\nvar n_target = readline();\n// // var n_target = '7 20';\nvar n = +(n_target.split(' ')[0]);\nvar target = +(n_target.split(' ')[1]);\nvar nums = readline();\n// // var nums = '21 15 12 11 20 19 12';\nnums = nums.split(' ').map(function (ele) {\n return +ele;\n});\n\nvar k = Math.floor(nums.length / 2) + 1;\n\nfunction part(start, end) {\n var p = nums[start];\n while (start < end) {\n while (start < end && nums[end] > p) {\n end--;\n }\n nums[start] = nums[end];\n while (start < end && nums[start] <= p) {\n start++;\n }\n nums[end] = nums[start];\n }\n nums[start] = p;\n return start;\n}\nfunction quickSort(k, start, end) {\n if (start < end) {\n var p = part(start, end);\n if (p === k - 1) return;\n if (p > k - 1) quickSort(k, start, p - 1);\n if (p < k - 1) quickSort(k - p - 1, p + 1, end);\n }\n}\n\nquickSort(k, 0, nums.length - 1);\n\n// quickSort(m, 0, nums.length - 1);\nvar rst = 0;\nif (nums[k]<= target) {\n for (var i = k; i < n; i++) {\n rst += Math.max(target - nums[i], 0);\n }\n} else {\n for (var i = 0; i <= k; i++) {\n rst += Math.max(nums[i] - target, 0);\n }\n}\n\nprint(rst)\n// console.log(rst)\n\n\n\n"}], "src_uid": "0df33cd53575471b1cc20702bf777059"} {"nl": {"description": "A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).", "input_spec": "The first line contains one integer $$$n$$$ ($$$13 \\le n < 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.", "output_spec": "If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.", "sample_inputs": ["13\n8380011223344", "15\n807345619350641"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all."}, "positive_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var s = read.arr();\n\n var lCount = n - 11;\n var hCount = lCount / 2;\n var vCount = 0;\n\n\n var g = false;\n\n for(var i = 0; i < n; i++) {\n if(s[i] === '8' && (i + 10) < n) {\n vCount ++;\n }\n }\n\n if(hCount >= vCount ) {\n print('NO');\n }\n else {\n print('YES')\n }\n}());\n"}, {"source_code": "function nextInt() {\n return parseInt(nextString());\n}\n\nfunction nextFloat() {\n return parseFloat(nextString());\n}\n\nlet input_stdin = \"\";\nlet input_cursor = 0;\n\nfunction nextString() {\n let next_string = \"\";\n clearWhitespaces();\n while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {\n next_string += input_stdin[input_cursor];\n input_cursor += 1;\n }\n return next_string;\n}\n\nfunction nextChar() {\n clearWhitespaces();\n if (input_cursor < input_stdin.length) {\n return input_stdin[input_cursor++];\n } else {\n return '\\0';\n }\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('ascii');\nprocess.stdin.on('data', function (data) { input_stdin += data; });\nprocess.stdin.on('end', function () { main(); });\n\nfunction isWhitespace(character) {\n return ' \\t\\n\\r\\v'.indexOf(character) > -1;\n}\n\nfunction clearWhitespaces() {\n while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) {\n input_cursor += 1;\n } \n}\n\nfunction main() {\n let n = nextInt();\n let fd = new Array(n + 2);\n fd.fill(0);\n let x = nextString();\n let ck = x.length - 11;\n let mvv = ck / 2, mvp = ck / 2;\n for (let i = 0; i < n; i++){\n if (x[i] === '8' && mvv)fd[i] = 1, mvv--;\n if (x[i] !== '8' && mvp)fd[i] = 1, mvp--;\n }\n for (let i = 0; i < n; i++){\n if (fd[i] === 0){\n if (x[i] === '8')console.log(\"Yes\"); else console.log(\"NO\");\n process.exit(0);\n }\n }\n}"}, {"source_code": "function nextInt() {\n return parseInt(nextString());\n}\n\nfunction nextFloat() {\n return parseFloat(nextString());\n}\n\nlet input_stdin = \"\";\nlet input_cursor = 0;\n\nfunction nextString() {\n let next_string = \"\";\n clearWhitespaces();\n while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {\n next_string += input_stdin[input_cursor];\n input_cursor += 1;\n }\n return next_string;\n}\n\nfunction nextChar() {\n clearWhitespaces();\n if (input_cursor < input_stdin.length) {\n return input_stdin[input_cursor++];\n } else {\n return '\\0';\n }\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('ascii');\nprocess.stdin.on('data', function (data) { input_stdin += data; });\nprocess.stdin.on('end', function () { main(); });\n\nfunction isWhitespace(character) {\n return ' \\t\\n\\r\\v'.indexOf(character) > -1;\n}\n\nfunction clearWhitespaces() {\n while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) {\n input_cursor += 1;\n } \n}\n\nfunction main() {\n let n = nextInt();\n let fd = new Array(n + 2);\n fd.fill(0);\n let x = nextString();\n let ck = x.length - 11;\n let mvv = ck / 2, mvp = ck / 2;\n for (let i = 0; i < n; i++){\n if (x[i] === '8' && mvv)fd[i] = 1, mvv--;\n if (x[i] !== '8' && mvp)fd[i] = 1, mvp--;\n }\n for (let i = 0; i < n; i++){\n if (fd[i] === 0){\n if (x[i] === '8')console.log(\"Yes\"); else console.log(\"NO\");\n process.exit(0);\n }\n }\n}"}], "negative_code": [], "src_uid": "99f37936b243907bf4ac1822dc547a61"} {"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$$$) — 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": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ');\n\n var sum1 = 0;\n var sum2 = 0;\n for(var i = 0; i < n; i++) {\n sum1 += a[i];\n sum2 += a[i + n];\n }\n\n if(sum1 !== sum2) {\n print(a.join(' '));\n return;\n }\n\n var eq = true;\n for(var i = 1; i < 2 * n; i++) {\n if(a[i] !== a[i - 1]) {\n eq = false;\n break;\n }\n }\n\n if(eq) {\n print(-1);\n return;\n }\n\n\n for(var i = 0; i < n; i++) {\n for(var j = 0; j < n; j++) {\n if(a[i] != a[n + j]) {\n var tmp = a[i];\n a[i] = a[n + j];\n a[n + j] = tmp;\n print(a.join(' '));\n return;\n }\n }\n }\n\n}());"}, {"source_code": "var n = parseInt(readline(), 10),\n a = readline().split(' ').map(el => parseInt(el, 10)).sort((a,b) => a-b),\n sum_1 = 0,\n sum_2 = 0;\n\nfor(var i=0; i<2*n; i++) {\n if(i <= n-1) sum_1 += a[i];\n else sum_2 += a[i];\n}\n\nprint(sum_1 !== sum_2 ? a.join(' ') : -1);"}, {"source_code": "var row = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = row[0];\n\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar sum = 0;\nvar hash = [];\nvar str = \"\";\nvar unique = null;\nvar flag = false;\n\nif(a.length % 2 == 1) write(a.join(\" \"));\nelse {\n for(var i = 0; i < a.length; i++) {\n sum += a[i];\n if(unique === null || unique == a[i])\n unique = a[i];\n else \n flag = true;\n }\n \n if(sum % 2 == 1) write(a.join(\" \"));\n else if(!flag) write(-1);\n else {\n write(a.sort().join(\" \"));\n }\n}\n"}], "negative_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n var n = read.number();\n var a = read.arrNumber(' ');\n\n var sum1 = 0;\n var sum2 = 0;\n for(var i = 0; i < n; i++) {\n sum1 += a[i];\n sum2 += a[i + n];\n }\n\n if(sum1 !== sum2) {\n print(a.join(' '));\n return;\n }\n\n var eq = true;\n for(var i = 1; i < 2 * n; i++) {\n if(a[i] !== a[i - 1]) {\n eq = false;\n break;\n }\n }\n\n if(eq) {\n print(-1);\n return;\n }\n\n\n for(var i = 0; i < n; i++) {\n for(var j = 0; j < n; i++) {\n if(a[i] != a[n + j]) {\n var tmp = a[i];\n a[i] = a[n + j];\n a[n + j] = tmp;\n print(a.join(' '));\n return;\n }\n }\n }\n\n}());"}, {"source_code": "var row = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = row[0];\n\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar sum = 0;\nvar hash = [];\nvar str = \"\";\n\nif(a.length % 2 == 1) write(a.join(\" \"));\nelse {\n for(var i = 0; i < a.length; i++) {\n sum += a[i];\n if(hash[a[i]] == null) {\n hash[a[i]] = \"0\";\n }\n }\n \n if(sum % 2 == 1) write(a.join(\" \"));\n else if(hash.length <= 2) write(-1);\n else {\n write(a.sort().join(\" \"));\n }\n}\n"}, {"source_code": "var row = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar n = row[0];\n\nvar a = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar sum = 0;\nvar hash = [];\nvar str = \"\";\n\nif(a.length % 2 == 1) write(a.join(\" \"));\nelse {\n for(var i = 0; i < a.length; i++) {\n sum += a[i];\n if(hash[a[i]] == null)\n hash[a[i]] = 1;\n }\n \n if(sum % 2 == 1) write(a.join(\" \"));\n else if(hash.length == 1) write(-1);\n else {\n write(a.sort().join(\" \"));\n }\n}\n"}], "src_uid": "1f4c057dff45f229b4dca49cd4e0438d"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$, consisting of $$$n$$$ integers. You are also given an integer value $$$x$$$.Let $$$f(k)$$$ be the maximum sum of a contiguous subarray of $$$a$$$ after applying the following operation: add $$$x$$$ to the elements on exactly $$$k$$$ distinct positions. An empty subarray should also be considered, it has sum $$$0$$$.Note that the subarray doesn't have to include all of the increased elements.Calculate the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) — the number of testcases. The first line of the testcase contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 5000$$$; $$$0 \\le x \\le 10^5$$$) — the number of elements in the array and the value to add. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^5 \\le a_i \\le 10^5$$$). The sum of $$$n$$$ over all testcases doesn't exceed $$$5000$$$.", "output_spec": "For each testcase, print $$$n + 1$$$ integers — the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.", "sample_inputs": ["3\n\n4 2\n\n4 1 3 2\n\n3 5\n\n-2 -7 -1\n\n10 2\n\n-6 -1 -2 4 -6 -1 -4 4 -5 -4"], "sample_outputs": ["10 12 14 16 18\n0 4 4 5\n4 6 6 7 7 7 7 8 8 8 8"], "notes": "NoteIn the first testcase, it doesn't matter which elements you add $$$x$$$ to. The subarray with the maximum sum will always be the entire array. If you increase $$$k$$$ elements by $$$x$$$, $$$k \\cdot x$$$ will be added to the sum.In the second testcase: For $$$k = 0$$$, the empty subarray is the best option. For $$$k = 1$$$, it's optimal to increase the element at position $$$3$$$. The best sum becomes $$$-1 + 5 = 4$$$ for a subarray $$$[3, 3]$$$. For $$$k = 2$$$, it's optimal to increase the element at position $$$3$$$ and any other element. The best sum is still $$$4$$$ for a subarray $$$[3, 3]$$$. For $$$k = 3$$$, you have to increase all elements. The best sum becomes $$$(-2 + 5) + (-7 + 5) + (-1 + 5) = 5$$$ for a subarray $$$[1, 3]$$$. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, a) {\r\n const c = new Array(n).fill(-Infinity);\r\n for (let i = 0; i < n; i++) {\r\n let sum = 0;\r\n for (let j = i; j < n; j++) {\r\n sum += a[j];\r\n c[j - i] = Math.max(c[j - i], sum);\r\n }\r\n }\r\n const res = new Array(n + 1).fill(-Infinity);\r\n res[0] = Math.max(0, ...c);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < n; j++) {\r\n res[i + 1] = Math.max(0, res[i + 1], (Math.min(i, j) + 1) * m + c[j]);\r\n }\r\n }\r\n return res.join(' ');\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, m, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst mxN = 5005;\r\nconst INF = 1e9;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, x] = rna();\r\n\t\tconst a = rna();\r\n\r\n\t\tconst sums = Array(n+1).fill(-INF); sums[0] = 0;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tfor (let j = i, sum = 0; j < n; j++) {\r\n\t\t\t\tsum += a[j];\r\n\t\t\t\tsums[j-i+1] = Math.max(sums[j-i+1], sum);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst ans = Array(n+1).fill(0);\r\n\t\tfor (let k = 0; k <= n; k++) {\r\n\t\t\tfor (let i = 0; i <= n; i++) {\r\n\t\t\t\tans[k] = Math.max(ans[k], sums[i]+Math.min(i, k)*x);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.join(' '));\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nconst mxN = 5005;\r\nconst INF = 1e10;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst [n, x] = rna();\r\n\t\tconst a = rna();\r\n\r\n\t\tconst psum = []; psum[-1] = 0;\r\n\t\tfor (let i = 0; i < n; i++) psum[i] = psum[i-1]+a[i];\r\n\r\n\t\tconst sums = Array(n+1).fill(-INF);\r\n\t\tfor (let i = 0; i <= n; i++) {\r\n\t\t\tfor (let j = 0; j+i-1 < n; j++) {\r\n\t\t\t\tsums[i] = Math.max(sums[i], psum[j+i-1]-psum[j-1]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst ans = Array(n+1).fill(0);\r\n\t\tfor (let k = 0; k <= n; k++) {\r\n\t\t\tfor (let i = 0; i <= n; i++) {\r\n\t\t\t\tans[k] = Math.max(ans[k], sums[i]+Math.min(i, k)*x);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans.join(' '));\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, x] = lines[l++].trim().split(' ').map(Number)\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, x, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, x, arr) {\n const dp = Array(n + 1).fill(-Infinity)\n dp[0] = 0\n for (let i = 0; i < n; i++) {\n let s = 0\n for (let j = i; j < n; j++) {\n s += arr[j]\n //\n const l = j - i + 1\n dp[l] = Math.max(dp[l], s)\n }\n }\n // console.log(dp)\n const ans = Array(n + 1).fill(-Infinity)\n for (let i = 0; i <= n; i++) {\n for (let l = i; l <= n; l++) {\n ans[i] = Math.max(ans[i], dp[l] + Math.min(l, i) * x)\n if (i) {\n ans[i] = Math.max(ans[i - 1], ans[i])\n }\n }\n }\n return ans.join(' ')\n}\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nfunction solve(n, m, a) {\r\n const c = new Array(n).fill(-Infinity);\r\n for (let i = 0; i < n; i++) {\r\n let sum = 0;\r\n for (let j = i; j < n; j++) {\r\n sum += a[j];\r\n c[j - i] = Math.max(c[j - i], sum);\r\n }\r\n }\r\n const res = new Array(n + 1).fill(-Infinity);\r\n res[0] = Math.max(0, ...c);\r\n for (let i = 0; i < n; i++) {\r\n for (let j = 0; j < n; j++) {\r\n res[i + 1] = Math.max(res[i + 1], (Math.min(i, j) + 1) * m + c[j]);\r\n }\r\n }\r\n return res.join(' ');\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(n, m, a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}], "src_uid": "a5927e1883fbd5e5098a8454f6f6631f"} {"nl": {"description": "The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size: the size he wanted, if he specified one size; any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.", "input_spec": "The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000. The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants. The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.", "output_spec": "If it is not possible to present a t-shirt to each participant, print «NO» (without quotes). Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input. If there are multiple solutions, print any of them.", "sample_inputs": ["0 1 0 1 1 0\n3\nXL\nS,M\nXL,XXL", "1 1 2 0 1 1\n5\nS\nM\nS,M\nXXL,XXXL\nXL,XXL"], "sample_outputs": ["YES\nXL\nM\nXXL", "NO"], "notes": null}, "positive_code": [{"source_code": "var calcDistr = function ( hist, pref ) {\n var i,\n j,\n pi,\n distr,\n given;\n\n given = 0;\n distr = [];\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 1 ) {\n continue;\n }\n if ( hist[ pi[ 0 ] ] === 0 ) {\n return;\n }\n distr[ i ] = pi[ 0 ];\n ++given;\n --hist[ pi[ 0 ] ];\n }\n\n for ( var size of Object.getOwnPropertyNames( hist ) ) {\n for ( j = 1; j >= 0; --j ) { \n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 2 || pi[ j ] !== size || distr[ i ] != null ) {\n continue;\n }\n if ( hist[ pi[ j ] ] > 0 ) {\n distr[ i ] = pi[ j ];\n ++given;\n --hist[ pi[ j ] ];\n }\n }\n }\n }\n\n if ( given === pref.length ) {\n return distr;\n }\n};\n\nvar input = readline().split( \" \" ).map( b => parseInt( b, 10 ) );\nvar hist = { \"S\": input[0], \"M\": input[1], \"L\": input[2], \"XL\": input[3], \"XXL\": input[4], \"XXXL\": input[5]};\nreadline();\nvar line,\n pref;\npref = [];\nwhile ( line = readline() ) {\n pref.push( line.split( \",\" ) );\n}\n\nvar result = calcDistr( hist, pref );\nif ( result ) {\n print( \"YES\" );\n print( result.join( \"\\n\" ) );\n} else {\n print( \"NO\" );\n}\n"}], "negative_code": [{"source_code": "// Greedy solution, O(n) runtime and O(n) memory.\n\nvar calcDistr = function ( hist, pref ) {\n var varPrefHist,\n i,\n pi,\n distr;\n\n distr = [];\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 1 ) {\n continue;\n }\n if ( hist[ pi[ 0 ] ] === 0 ) {\n return;\n }\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ];\n }\n \n varPrefHist = { \"S\": 0, \"M\": 0, \"L\": 0, \"XL\": 0, \"XXL\": 0, \"XXXL\": 0};\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 2 ) {\n continue;\n }\n ++varPrefHist[ pi[ 0 ] ];\n ++varPrefHist[ pi[ 1 ] ];\n }\n\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ]; \n if ( pi.length !== 2 ) {\n continue;\n }\n // Greedy choise. Choose one that in least demand.\n if ( ( varPrefHist[ pi[ 0 ] ] >= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {\n distr[ i ] = pi[ 1 ];\n --hist[ pi[ 1 ] ];\n } else if ( ( varPrefHist[ pi[ 0 ] ] < varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] === 0 ) && hist[ pi[ 0 ] ] > 0 ) {\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ]; \n } else {\n return;\n }\n }\n\n return distr;\n};\n\nvar input = readline().split( \" \" ).map( b => parseInt( b, 10 ) );\nvar hist = { \"S\": input[0], \"M\": input[1], \"L\": input[2], \"XL\": input[3], \"XXL\": input[4], \"XXXL\": input[5]};\nreadline();\nvar line,\n pref;\npref = [];\nwhile ( line = readline() ) {\n pref.push( line.split( \",\" ) );\n}\n\nvar result = calcDistr( hist, pref );\nif ( result ) {\n print( \"YES\" );\n print( result.join( \"\\n\" ) );\n} else {\n print( \"NO\" );\n}\n"}, {"source_code": "var calcDistr = function ( hist, pref ) {\n var i,\n pi,\n distr;\n\n distr = [];\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 1 ) {\n continue;\n }\n if ( hist[ pi[ 0 ] ] === 0 ) {\n return;\n }\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ];\n }\n \n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ]; \n if ( pi.length !== 2 ) {\n continue;\n }\n\n if ( hist[ pi[ 0 ] ] > 0 ) {\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ];\n } else if ( hist[ pi[ 1 ] ] > 0 ) {\n distr[ i ] = pi[ 1 ];\n --hist[ pi[ 1 ] ]; \n } else {\n return;\n }\n }\n\n return distr;\n};\n\nvar input = readline().split( \" \" ).map( b => parseInt( b, 10 ) );\nvar hist = { \"S\": input[0], \"M\": input[1], \"L\": input[2], \"XL\": input[3], \"XXL\": input[4], \"XXXL\": input[5]};\nreadline();\nvar line,\n pref;\npref = [];\nwhile ( line = readline() ) {\n pref.push( line.split( \",\" ) );\n}\n\nvar result = calcDistr( hist, pref );\nif ( result ) {\n print( \"YES\" );\n print( result.join( \"\\n\" ) );\n} else {\n print( \"NO\" );\n}\n"}, {"source_code": "// Greedy solution, O(n) runtime and O(n) memory.\n\nvar calcDistr = function ( hist, pref ) {\n var varPrefHist,\n i,\n pi,\n distr;\n\n distr = [];\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 1 ) {\n continue;\n }\n if ( hist[ pi[ 0 ] ] === 0 ) {\n return;\n }\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ];\n }\n \n varPrefHist = { \"S\": 0, \"M\": 0, \"L\": 0, \"XL\": 0, \"XXL\": 0, \"XXXL\": 0};\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 2 ) {\n continue;\n }\n ++varPrefHist[ pi[ 0 ] ];\n ++varPrefHist[ pi[ 1 ] ];\n }\n\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ]; \n if ( pi.length !== 2 ) {\n continue;\n }\n // Greedy choise. Choose one that in least demand.\n if ( ( varPrefHist[ pi[ 0 ] ] >= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {\n distr[ i ] = pi[ 1 ];\n --hist[ pi[ 1 ] ];\n } else if ( ( varPrefHist[ pi[ 0 ] ] < varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] ) && hist[ pi[ 0 ] ] > 0 ) {\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ]; \n } else {\n return;\n }\n }\n\n return distr;\n};\n\nvar input = readline().split( \" \" ).map( b => parseInt( b, 10 ) );\nvar hist = { \"S\": input[0], \"M\": input[1], \"L\": input[2], \"XL\": input[3], \"XXL\": input[4], \"XXXL\": input[5]};\nreadline();\nvar line,\n pref;\npref = [];\nwhile ( line = readline() ) {\n pref.push( line.split( \",\" ) );\n}\n\nvar result = calcDistr( hist, pref );\nif ( result ) {\n print( \"YES\" );\n print( result.join( \"\\n\" ) );\n} else {\n print( \"NO\" );\n}\n"}, {"source_code": "// Greedy solution, O(n) runtime and O(n) memory.\n\nvar calcDistr = function ( hist, pref ) {\n var varPrefHist,\n i,\n pi,\n distr;\n\n distr = [];\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 1 ) {\n continue;\n }\n if ( hist[ pi[ 0 ] ] === 0 ) {\n return;\n }\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ];\n }\n \n varPrefHist = { \"S\": 0, \"M\": 0, \"L\": 0, \"XL\": 0, \"XXL\": 0, \"XXXL\": 0};\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 2 ) {\n continue;\n }\n ++varPrefHist[ pi[ 0 ] ];\n ++varPrefHist[ pi[ 1 ] ];\n }\n\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ]; \n if ( pi.length !== 2 ) {\n continue;\n }\n print( JSON.stringify( hist ) );\n // Greedy choise. Choose one that in least demand.\n if ( ( varPrefHist[ pi[ 0 ] ] > varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {\n distr[ i ] = pi[ 1 ];\n --hist[ pi[ 1 ] ];\n } else if ( ( varPrefHist[ pi[ 0 ] ] <= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] === 0 ) && hist[ pi[ 0 ] ] > 0 ) {\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ]; \n } else {\n return;\n }\n }\n\n return distr;\n};\n\nvar input = readline().split( \" \" ).map( b => parseInt( b, 10 ) );\nvar hist = { \"S\": input[0], \"M\": input[1], \"L\": input[2], \"XL\": input[3], \"XXL\": input[4], \"XXXL\": input[5]};\nreadline();\nvar line,\n pref;\npref = [];\nwhile ( line = readline() ) {\n pref.push( line.split( \",\" ) );\n}\n\nvar result = calcDistr( hist, pref );\nif ( result ) {\n print( \"YES\" );\n print( result.join( \"\\n\" ) );\n} else {\n print( \"NO\" );\n}\n"}, {"source_code": "// Greedy solution, O(n) runtime and O(n) memory.\n\nvar calcDistr = function ( hist, pref ) {\n var varPrefHist,\n i,\n pi,\n distr;\n\n distr = [];\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 1 ) {\n continue;\n }\n if ( hist[ pi[ 0 ] ] === 0 ) {\n return;\n }\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ];\n }\n \n varPrefHist = { \"S\": 0, \"M\": 0, \"L\": 0, \"XL\": 0, \"XXL\": 0, \"XXXL\": 0};\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 2 ) {\n continue;\n }\n ++varPrefHist[ pi[ 0 ] ];\n ++varPrefHist[ pi[ 1 ] ];\n }\n\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ]; \n if ( pi.length !== 2 ) {\n continue;\n }\n\n // Greedy choise. Choose one that in least demand.\n if ( ( varPrefHist[ pi[ 0 ] ] > varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {\n distr[ i ] = pi[ 1 ];\n --hist[ pi[ 1 ] ];\n } else if ( ( varPrefHist[ pi[ 0 ] ] <= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] === 0 ) && hist[ pi[ 0 ] ] > 0 ) {\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ]; \n } else {\n return;\n }\n }\n\n return distr;\n};\n\nvar input = readline().split( \" \" ).map( b => parseInt( b, 10 ) );\nvar hist = { \"S\": input[0], \"M\": input[1], \"L\": input[2], \"XL\": input[3], \"XXL\": input[4], \"XXXL\": input[5]};\nreadline();\nvar line,\n pref;\npref = [];\nwhile ( line = readline() ) {\n pref.push( line.split( \",\" ) );\n}\n\nvar result = calcDistr( hist, pref );\nif ( result ) {\n print( \"YES\" );\n print( result.join( \"\\n\" ) );\n} else {\n print( \"NO\" );\n}\n"}, {"source_code": "// Greedy solution, O(n) runtime and O(n) memory.\n\nvar calcDistr = function ( hist, pref ) {\n var varPrefHist,\n i,\n pi,\n distr;\n\n distr = [];\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 1 ) {\n continue;\n }\n if ( hist[ pi[ 0 ] ] === 0 ) {\n return;\n }\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ];\n }\n \n varPrefHist = { \"S\": 0, \"M\": 0, \"L\": 0, \"XL\": 0, \"XXL\": 0, \"XXXL\": 0};\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ];\n if ( pi.length !== 2 ) {\n continue;\n }\n ++varPrefHist[ pi[ 0 ] ];\n ++varPrefHist[ pi[ 1 ] ];\n }\n\n for ( i = 0; i < pref.length; ++i ) {\n pi = pref[ i ]; \n if ( pi.length !== 2 ) {\n continue;\n }\n // Greedy choise. Choose one that in least demand.\n if ( varPrefHist[ pi[ 0 ] ] >= varPrefHist[ pi[ 1 ] ] && hist[ pi[ 1 ] ] > 0 ) {\n distr[ i ] = pi[ 1 ];\n --hist[ pi[ 1 ] ];\n } else if ( hist[ pi[ 0 ] ] > 0 ) {\n distr[ i ] = pi[ 0 ];\n --hist[ pi[ 0 ] ]; \n } else {\n return;\n }\n }\n\n return distr;\n};\n\nvar input = readline().split( \" \" ).map( b => parseInt( b, 10 ) );\nvar hist = { \"S\": input[0], \"M\": input[1], \"L\": input[2], \"XL\": input[3], \"XXL\": input[4], \"XXXL\": input[5]};\nreadline();\nvar line,\n pref;\npref = [];\nwhile ( line = readline() ) {\n pref.push( line.split( \",\" ) );\n}\n\nvar result = calcDistr( hist, pref );\nif ( result ) {\n print( \"YES\" );\n print( result.join( \"\\n\" ) );\n} else {\n print( \"NO\" );\n}\n"}], "src_uid": "f7e634607f1500c91bf93f44472b18cb"} {"nl": {"description": "This is the easy version of this problem. In this version, we do not have queries. Note that we have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.An array $$$b$$$ of length $$$m$$$ is good if for all $$$i$$$ the $$$i$$$-th element is greater than or equal to $$$i$$$. In other words, $$$b$$$ is good if and only if $$$b_i \\geq i$$$ for all $$$i$$$ ($$$1 \\leq i \\leq m$$$).You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find the number of pairs of indices $$$(l, r)$$$, where $$$1 \\le l \\le r \\le n$$$, such that the array $$$[a_l, a_{l+1}, \\ldots, a_r]$$$ is good.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 2 \\cdot 10^5$$$). 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$$$), the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ space-separated integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\leq a_i \\leq n$$$), representing 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, print the number of suitable pairs of indices.", "sample_inputs": ["3\n\n3\n\n1 2 3\n\n3\n\n1 1 1\n\n4\n\n2 1 4 3"], "sample_outputs": ["6\n3\n7"], "notes": "NoteIn the first test case, all subarrays of $$$a$$$ are good, so all pairs are suitable.In the second test case, the pairs $$$(1, 1)$$$, $$$(2, 2)$$$, and $$$(3, 3)$$$ are suitable. For example, when $$$(l, r) = (1, 2)$$$, the array $$$b=[1,1]$$$ is not good because $$$b_2 < 2$$$."}, "positive_code": [{"source_code": "// Common Template Starts //\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\"\r\nlet currentLine = 0\r\n\r\nprocess.stdin.on(\"data\", inputStdin => inputString += inputStdin)\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString.trim().split(\"\\n\").map((string) => string.trim())\r\n main()\r\n})\r\n\r\nconst readline = () => inputString[currentLine++]\r\n// Common Template Ends //\r\n\r\n// Driver Function Starts //\r\nconst main = () => {\r\n console.clear()\r\n let t = parseInt(readline())\r\n while (t--) {\r\n let n = parseInt(readline())\r\n let a = readline().split(' ').map(Number)\r\n console.log(solve(n, a))\r\n }\r\n}\r\n// Driver Function Ends //\r\n\r\n// MAIN LOGIC\r\nconst solve = (n, a) => {\r\n let left = 0\r\n let right = 0\r\n let count = 0\r\n while (left < n) {\r\n if (right < left) right = left\r\n while (right < n && a[right] >= right - left + 1) {\r\n right++\r\n }\r\n count += right - left\r\n left++\r\n }\r\n return count\r\n}\r\n\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b)\r\n\r\n\r\nconst isOdd = (num) => num & 1\r\nconst isEven = (num) => !(num & 1)\r\nconst minOfArray = (arr) => Math.min.apply(null, arr)\r\nconst maxOfArray = (arr) => Math.max.apply(null, arr)\r\nconst uniqueArray = (arr) => [...new Set(arr)]\r\nconst sortArray = (arr) => arr.sort((a, b) => a - b)\r\nconst sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n);\r\n const dp = new Array(n).fill(0);\r\n for (let i = 0; i < n; i++) {\r\n var _dp;\r\n dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;\r\n }\r\n return dp.reduce((a, b) => a + b, 0);\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "4811646a6a68f6b83891bd22985ce7e5"} {"nl": {"description": "A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n \\ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.", "input_spec": "Each test consists of 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 an integer $$$n$$$ ($$$3 \\leq n \\leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},\\dots,a_{n}$$$ ($$$1 \\leq a_{i} \\leq 200$$$) — the elements of the array.", "output_spec": "Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array.", "sample_inputs": ["4\n3\n8 1 2\n4\n6 9 4 2\n9\n1 2 3 4 5 6 7 8 9\n3\n200 199 198"], "sample_outputs": ["2\n2 1\n4\n2 1 4 3\n9\n6 9 1 2 3 4 5 7 8\n3\n1 2 3"], "notes": "NoteIn the first test case, the subset $$$\\{a_2, a_1\\}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$$\\{a_1, a_3\\}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$.In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset."}, "positive_code": [{"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar odd = [];\r\n\t\tvar even = [];\r\n\t\tvar sum = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tsum += list[i];\r\n\t\t\tif(list[i] % 2 == 1){\r\n\t\t\t\todd.push(i + 1);\r\n\t\t\t}else{\r\n\t\t\t\teven.push(i + 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(isPrime(sum)){\r\n\t\t\todd.pop();\r\n\t\t}\r\n\t\tmyout(odd.length + even.length);\r\n\t\tmyout(myconv(odd.concat(even), 8));\r\n\t}\r\n}\r\nfunction isPrime(val){\r\n\tif(val == null || val <= 1 || (val != 2 && val % 2 == 0)){\r\n\t\treturn false;\r\n\t}else if(val == 2){\r\n\t\treturn true;\r\n\t}\r\n\tvar root = Math.floor(Math.sqrt(val));\r\n\tfor(var i = 3; i <= root; i += 2){\r\n\t\tif(val % i == 0){\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}"}], "negative_code": [{"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = BigInt(next());\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar list = nextIntArray(N);\r\n\t\tvar odd = [];\r\n\t\tvar even = [];\r\n\t\tvar sum = 0;\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tsum += list[i];\r\n\t\t\tif(list[i] % 2 == 1){\r\n\t\t\t\todd.push(i + 1);\r\n\t\t\t}else{\r\n\t\t\t\teven.push(i + 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(isPrime(sum)){\r\n\t\t\teven.pop();\r\n\t\t}\r\n\t\tmyout(odd.length + even.length);\r\n\t\tmyout(myconv(odd.concat(even), 8));\r\n\t}\r\n}\r\nfunction isPrime(val){\r\n\tif(val == null || val <= 1 || (val != 2 && val % 2 == 0)){\r\n\t\treturn false;\r\n\t}else if(val == 2){\r\n\t\treturn true;\r\n\t}\r\n\tvar root = Math.floor(Math.sqrt(val));\r\n\tfor(var i = 3; i <= root; i += 2){\r\n\t\tif(val % i == 0){\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}"}], "src_uid": "677972c7d86ce9fd0808105331f77fe0"} {"nl": {"description": "You are given a long decimal number $$$a$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$. You also have a function $$$f$$$ that maps every digit from $$$1$$$ to $$$9$$$ to some (possibly the same) digit from $$$1$$$ to $$$9$$$.You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in $$$a$$$, and replace each digit $$$x$$$ from this segment with $$$f(x)$$$. For example, if $$$a = 1337$$$, $$$f(1) = 1$$$, $$$f(3) = 5$$$, $$$f(7) = 3$$$, and you choose the segment consisting of three rightmost digits, you get $$$1553$$$ as the result.What is the maximum possible number you can obtain applying this operation no more than once?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the number of digits in $$$a$$$. The second line contains a string of $$$n$$$ characters, denoting the number $$$a$$$. Each character is a decimal digit from $$$1$$$ to $$$9$$$. The third line contains exactly $$$9$$$ integers $$$f(1)$$$, $$$f(2)$$$, ..., $$$f(9)$$$ ($$$1 \\le f(i) \\le 9$$$).", "output_spec": "Print the maximum number you can get after applying the operation described in the statement no more than once.", "sample_inputs": ["4\n1337\n1 2 5 4 6 6 3 1 9", "5\n11111\n9 8 7 6 5 4 3 2 1", "2\n33\n1 1 1 1 1 1 1 1 1"], "sample_outputs": ["1557", "99999", "33"], "notes": null}, "positive_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var a = read.arrNumber();\n var f = read.arrNumber(' ');\n\n var res = [];\n var start = false;\n var end = false;\n for(var i = 0; i < n; i++) {\n if((a[i] < f[a[i] -1] && !end) || (a[i] == f[a[i] -1] && start && !end)) {\n res[i] = f[a[i] -1];\n start = true\n }\n else {\n res[i] = a[i];\n if(start) {\n end = true;\n }\n }\n }\n\n print(res.join(''));\n}())"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var a = read.arrNumber();\n var f = read.arrNumber(' ');\n\n var res = [];\n var start = false;\n var end = false;\n for(var i = 0; i < n; i++) {\n if((a[i] < f[a[i] -1] && !end) || (a[i] == f[a[i] -1] && start && !end)) {\n res[i] = f[a[i] -1];\n start = true\n }\n else {\n res[i] = a[i];\n if(start) {\n end = true;\n }\n }\n }\n\n print(res.join(''));\n}())"}, {"source_code": "let n;\nlet a;\nlet f;\n\nconst run = () => {\n let start;\n let end;\n let el;\n let i;\n for (i = 0; i < n; ++i) {\n el = a[i];\n if (el < f[el]) {\n start = i;\n for (; i < n; ++i) {\n el = a[i];\n end = i;\n if (el > f[el]) {\n end = i - 1;\n break;\n }\n }\n break;\n }\n }\n if (start === undefined) {\n console.log(a.join(''))\n return;\n }\n console.log(a.map((e, j) => ((j >= start && (end === undefined || j <= end)) ? f[e] : e)).join(''))\n}\n\nconst readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nrl.on('line', (data) => {\n if (n === undefined) {\n n = +(data.toString());\n return;\n }\n if (a === undefined) {\n a = data.toString().trim().split('').map(Number);\n return;\n }\n f = [null, ...data.toString().trim().split(/\\s+/g).filter(Boolean).map(Number)];\n run();\n rl.close();\n})\n"}], "negative_code": [{"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var a = read.arrNumber();\n var f = read.arrNumber(' ');\n \n var res = [];\n for(var i =0 ;i < n; i++) {\n res[i] = a[i] > f[a[i] -1] ? a[i] : f[a[i] -1];\n }\n \n print(res.join(''));\n}());\n"}, {"source_code": "let n;\nlet a;\nlet f;\nconst promise = new Promise(resolve => {\n process.stdin.on('data', (data) => {\n if (n === undefined) {\n n = +(data.toString());\n return;\n }\n if (a === undefined) {\n a = data.toString().trim().split('').map(Number);\n return;\n }\n f = [null, ...data.toString().trim().split(/\\s+/g).filter(Boolean).map(Number)];\n resolve();\n })\n})\n\npromise.then(() => {\n let start;\n let end;\n let el;\n let k;\n let i;\n for (i = 0; i < n; ++i) {\n el = a[i];\n if (el < f[el]) {\n start = i;\n for (k = i + 1; k < n; ++k) {\n el = a[k];\n if (el > f[el]) {\n end = k;\n break;\n }\n }\n break;\n }\n }\n if (start === undefined) {\n console.log(a.join(''))\n return;\n }\n console.log(a.map((e, j) => {\n if (j >= start && (end === undefined || j <= end)) {\n return f[e];\n }\n return e;\n }).join(''))\n})\n"}, {"source_code": "let n;\nlet a;\nlet f;\nconst promise = new Promise(resolve => {\n process.stdin.on('data', (data) => {\n if (n === undefined) {\n n = +(data.toString());\n return;\n }\n if (a === undefined) {\n a = data.toString().split('');\n return;\n }\n f = ['x', ...data.toString().split(/\\s+/g).filter(Boolean).map(Number)];\n resolve();\n })\n})\n\npromise.then(() => {\n const b = [];\n for (let k = 1; k < 10; ++k) {\n b[k] = k < f[k];\n }\n let i = 0;\n let start;\n let end;\n for (; i < n; ++i) {\n if (b[a[i]]) {\n if (start === undefined) {\n start = i;\n } else if (end === undefined) {\n end = i;\n break;\n }\n }\n }\n console.log(a.map((e, j) => {\n if (j >= start && j <= end) {\n return f[e];\n }\n return e;\n }).join(''))\n})\n"}, {"source_code": "let n;\nlet a;\nlet f;\nconst promise = new Promise(resolve => {\n process.stdin.on('data', (data) => {\n if (n === undefined) {\n n = +(data.toString());\n return;\n }\n if (a === undefined) {\n a = data.toString().trim().split('').map(Number);\n return;\n }\n f = [null, ...data.toString().trim().split(/\\s+/g).filter(Boolean).map(Number)];\n resolve();\n })\n})\n\npromise.then(() => {\n let start;\n let end;\n let el;\n let k;\n let i;\n for (i = 0; i < n; ++i) {\n el = a[i];\n if (el < f[el]) {\n start = i;\n for (k = i + 1; k < n; ++k) {\n el = a[k];\n if (el >= f[el]) {\n end = k - 1;\n break;\n }\n }\n break;\n }\n }\n if (start === undefined) {\n console.log(a.join(''))\n return;\n }\n console.log(a.map((e, j) => {\n if (j >= start && (end === undefined || j <= end)) {\n return f[e];\n }\n return e;\n }).join(''))\n})\n"}], "src_uid": "378a9ab7ad891d60f23645106d24f314"} {"nl": {"description": "One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an 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, a2, ..., an → an, a1, a2, ..., an - 1. 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 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).", "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": "//\n\n\nvar line = readline();\n\nvar ray = readline().split(' ');\nvar n = parseInt(line);\nvar bRay = [];\n\n\nfor(var i = 0 ; i < n ; i++) {\n\tbRay.push(parseInt(ray[i]));\n}\n\nprint(foo(n,bRay));\n\n//console.log(foo(2,[1,2]));\n\n//checker(3,[1,3,2],0);\nfunction foo(n,ray) {\n\tvar count = 0;\n\t//console.log(checker(n,bRay,1));\n\t\n\tfor(var i = 0 ; i < n-1;i++) {\n\t\tif (ray[i] > ray[i+1]) {\n\t\t\t\n\t\t\tfor(var j = 1 ; j < n ; j++) {\n\t\t\t\t//.log((j+i)%n,i);\n\t\t\t\tif ( ray[(j+i) % n] > ray[(j+i+1) %n]) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\treturn n-(i+1);\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t}\n\t\n\treturn 0;\n}\n\n/*\nfunction checker(n,ray,p) {\n//\tvar s = \"\";\n//\tvar d = \"\";\n\tfor(var i = 0 ; i < n-1 ; i++) {\n\t\t\n\t\t\n\t\tif ( ray[(i+p) %n] > ray[(i+1+p) %n]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t}\n\t\n\t\n\treturn true;\n}*/"}, {"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = false;\n\n this.solveCase = function() {\n var res , i , j , fl , cn , temp , prev ;\n res = ( 1 << 20 ) ;\n prev = -1 ;\n fl = 1 ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( this.arr[ i ] >= prev ) {\n \t\tprev = this.arr[ i ] ; \n \t}\n \telse {\n \t\tfl = 0 ;\n \t\tprev = -1 ;\n \t\tfor( j = i ; j < this.n ; j++ ) {\n \t\t\tif( this.arr[ j ] >= prev ) {\n\t\t \t\tprev = this.arr[ j ] ; \n\t\t \t}\n\t\t \telse {\n\t\t \t\tbreak ;\n\t\t \t}\n \t\t}\n \t\tif( j == this.n && this.arr[ this.n - 1 ] <= this.arr[ 0 ] ) {\n \t\t\tres = this.n - i ;\n \t\t}\n \t\tbreak ;\n \t}\n }\n if( fl == 1 ) {\n \tres = 0 ;\n }\n if( res == ( 1 << 20 ) ) {\n \tres = -1 ;\n }\n print( res );\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n for( i = 0 ; i < this.n ; i++ ) {\n this.arr[ i ] = irObj.nextInt();\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.arr = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "var n = +readline();\nvar s = readline().split(' ').map(Number);\nvar ind = -1;\nfor (var i=0; is[i+1]) {\n\t\tind = i+1;\n\t\ts = s.slice(ind).concat(s.slice(0, ind));\n\t\tbreak;\n\t}\n}\nif (ind == -1) print(0);\nelse {\n\tfor (var i=0; is[i+1]) {\n\t\tprint(-1);\n\t\tind = -1;\n\t\tbreak;\n\t\t}\n\t}\n\tif (ind != -1) print(n-ind);\n}"}, {"source_code": "var n=parseInt(readline());\nvar ar=readline().split(\" \");\nfor(var i=0;iar[0])\n{\n for(var i=0;iar[i+1]){res=-1;break;}\n }\n}\n\nelse{res++;\nfor(var i=n-1;i>0;i--){\n\n if(ar[i]>=ar[i-1]){res++;}\nelse{\nfor(var y=0;yar[y+1]){res=-1;break;}\n}break;\n\n}\n}if(res===n){res=0;}\n}print(res);"}, {"source_code": "var l = readline()|0,\n arr = readline().split(' ').map(Number),\n inf = 0,\n steps = 0;\n \n if (arr[l-1]>arr[0]) {\n inf +=1;\n } \nfor (var i=0; i arr[i+1]) {\n inf +=1;\n steps = l-1 - i;\n }\n}\nif (inf == 0) {\n print('0');\n} else if (inf == 1){\n print(steps);\n} else {\n print('-1');\n}"}, {"source_code": ";(function () {\n\n print(function () {\n var n = +readline(),\n a = readline().split(' ').map(Number),\n d = 0, r = null;\n\n if (n === 2) {\n return a[0] <= a[1] ? 0 : 1;\n }\n\n a = a.concat([a[0]]);\n\n a.forEach(function (e, i, a) {\n if (i === 0) return;\n if (e < a[i - 1]) {\n d++;\n r = i;\n }\n });\n\n if (d === 0) return 0;\n if (d > 1) return -1;\n return n - r;\n }.call(this));\n\n}.call(this));\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tvalues = tokenizeIntegers(readline());\n\tfor (var seek = 1; seek < n; ++seek) {\n\t\tif (values[seek-1] > values[seek]) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (seek == n) {\n\t\treturn 0;\n\t}\n\tvar end = seek-1;\n\tfor (var i = end+2; i < n; ++i) {\n\t\tif (values[i-1] > values[i]) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\tif (values[n-1] > values[0]) {\n\t\treturn -1;\n\t}\n\treturn n-end-1;\n}\n\nprint(main());\n"}], "negative_code": [{"source_code": "//\n\n\nvar line = readline();\n\nvar ray = readline().split(' ');\nvar n = parseInt(line);\nvar bRay = [];\n\n\nfor(var i = 0 ; i < n ; i++) {\n\tbRay.push(parseInt(ray[i]));\n}\n\nprint(foo(n,bRay));\n\n//console.log(foo(4,[3,4,1,2]));\n\n//checker(3,[1,3,2],0);\nfunction foo(n,ray) {\n\tvar count = 0;\n\t//console.log(checker(n,bRay,1));\n\t\n\tfor(var i = 0 ; i < n-1;i++) {\n\t\tif (ray[i] > ray[i+1]) {\n\t\t\t\n\t\t\tfor(var j = 1 ; j < n ; j++) {\n\t\t\t\t//.log((j+i)%n,i);\n\t\t\t\tif ( ray[(j+i) % n] > ray[(j+i+1) %n]) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\treturn i+1;\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t}\n\t\n\treturn 0;\n}\n\n/*\nfunction checker(n,ray,p) {\n//\tvar s = \"\";\n//\tvar d = \"\";\n\tfor(var i = 0 ; i < n-1 ; i++) {\n\t\t\n\t\t\n\t\tif ( ray[(i+p) %n] > ray[(i+1+p) %n]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t}\n\t\n\t\n\treturn true;\n}*/"}, {"source_code": "//\n\n\nvar line = readline();\n\nvar ray = readline().split(' ');\nvar n = parseInt(line);\nvar bRay = [];\n\n\nfor(var i = 0 ; i < n ; i++) {\n\tbRay.push(parseInt(ray[i]));\n}\n\nprint(foo(n,bRay));\n\n//console.log(foo(3,[1,3,2]));\nfunction foo(n,bRay) {\n\tvar count = 0;\n\t//console.log(checker(n,bRay,1));\n\t\n\t\t\n\t\n\t\tfor(var i = 0 ; i < n ; i++) {\n\t\t\t\n\t\t\t\n\t\t\tif ( checker(n,bRay,i)) {\n\t\t\t\t//console.log(checker(n,bRay,i),n,bRay,i);\n\t\t\t\treturn count;\n\t\t\t}\n\t\t\tcount++;\n\t\t\n\t\t\n\t\t\n\t\t}\n\t\n\t\n\treturn -1;\n\t\n\t\n}\n\nfunction checker(n,ray,p) {\n\t//console.log(n,ray,p);\n\tfor(var i = 0 ; i < n ; i++) {\n\t\t\n\t\tvar j = (i+p) %n ;\n\t\t//console.log(ray[j]);\n\t\tif ( ray[j] > ray[(j+1)%n]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t}\n\t//console.log(\"e\");\n\treturn true ;\n\t\n}"}, {"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = false;\n\n this.solveCase = function() {\n var res , i , j , fl , cn , temp , prev ;\n res = ( 1 << 20 ) ;\n prev = -1 ;\n fl = 1 ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tif( this.arr[ i ] >= prev ) {\n \t\tprev = this.arr[ i ] ; \n \t}\n \telse {\n \t\tfl = 0 ;\n \t\tprev = -1 ;\n \t\tfor( j = i ; j < this.n ; j++ ) {\n \t\t\tif( this.arr[ i ] >= prev ) {\n\t\t \t\tprev = this.arr[ i ] ; \n\t\t \t}\n\t\t \telse {\n\t\t \t\tbreak ;\n\t\t \t}\n \t\t}\n \t\tif( j == this.n && this.arr[ this.n - 1 ] <= this.arr[ 0 ] ) {\n \t\t\tres = this.n - i ;\n \t\t}\n \t\tbreak ;\n \t}\n }\n if( fl == 1 ) {\n \tres = 0 ;\n }\n if( res == ( 1 << 20 ) ) {\n \tres = -1 ;\n }\n print( res );\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n for( i = 0 ; i < this.n ; i++ ) {\n this.arr[ i ] = irObj.nextInt();\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.arr = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "var n = +readline();\nvar s = readline().split(' ').map(Number);\nvar min = 1000000;\nvar ind = 0;\nvar count = 0;\nfor (var i=0; is[i+1]) {\n\t\tprint(-1);\n\t\tmin = 10000000;\n\t\tbreak;\n\t}\n\tif (s[i]==s[i+1]) {\n\t\tcount++;\n\t}\n}\nif (min != 10000000) {\n\tif (ind == 0 || count == n-1) print(0);\n\telse print(n-ind);\n}"}, {"source_code": "var n = +readline();\nvar s = readline().split(' ').map(Number);\nvar min = 1000000;\nvar ind = 0;\nfor (var i=0; is[i+1]) {\n\t\tprint(-1);\n\t\tmin = 10000000;\n\t\tbreak;\n\t}\n}\nif (min != 10000000) {\n\tif (ind == 0) print(0);\n\telse print(n-ind);\n}"}, {"source_code": "var n = +readline();\nvar s = readline().split(' ').map(Number);\nvar min = Math.min.apply(null, s);\nvar ind = s.indexOf(min);\nvar count = 0;\ns = s.slice(ind).concat(s.slice(0, ind));\nfor (var i=0; is[i+1]) {\n\t\tprint(-1);\n\t\tmin = 10000000;\n\t\tbreak;\n\t}\n\tif (s[i]==s[i+1]) {\n\t\tcount++;\n\t}\n}\nif (min != 10000000) {\n\tif (ind == 0 || count == n-1) print(0);\n\telse print(n-ind);\n}"}, {"source_code": "var n = +readline();\nvar s = readline().split(' ').map(Number);\nvar min = 1000000;\nvar ind = 0;\nfor (var i=0; is[i+1]) {\n\t\tprint(-1);\n\t\tmin = 10000000;\n\t\tbreak;\n\t}\n}\nif (min != 10000000) {\n\tif (ind == 0) print(0);\n\telse print(n-ind);\n}"}, {"source_code": "var n = +readline();\nvar s = readline().split(' ').map(Number);\nvar min = 1000000;\nvar ind = 0;\nfor (var i=0; is[i+1]) {\n\t\tprint(-1);\n\t\tmin = 10000000;\n\t\tbreak;\n\t}\n}\nif (min != 10000000) {\n\tif (ind == 0) print(0);\n\telse print(n-ind);\n}\n"}, {"source_code": "var n=parseInt(readline());\nvar ar=readline().split(\" \");\n\nvar res=0;\n\nif(parseInt(ar[n-1])>parseInt(ar[0]))\n{\n for(var i=0;iparseInt(ar[i+1])){res=-1;break;}\n }\n}\n\nelse{\nres++;\nfor(var i=n-1;i>0;i--){\n\n if(parseInt(ar[i-1])<=parseInt(ar[i])){res++;}\nelse{\nfor(var y=i-1;y>0;y--){\n if(parseInt(ar[y])parseInt(ar[0])){\nfor(var i=0;iparseInt(ar[i+1])){res=-1;break;}\n}\n}\nelse{\nres++;\nfor(var i=n-1;i>0;i--){\n\nif(parseInt(ar[i-1])0;y--){\nif(parseInt(ar[y])ar[0])\n{\n for(var i=0;iar[i+1]){res=-1;break;}\n }\n}\n\nelse{res++;\nfor(var i=n-1;i>0;i--){\n\n if(ar[i]>ar[i-1]){res++;}\nelse{\nfor(var y=0;yar[y+1]){res=-1;break;}\n}break;\n\n}\n}\n}print(res);"}, {"source_code": "var l = readline()|0,\n arr = readline().split(' ').map(Number),\n chkr = false,\n chk = false;\n\nwhile (chkr == false) { \n var res = 0;\n for (var i = 0; i < l-1; i++) {\n if (arr[i] > arr[i+1]) {\n arr.unshift(arr.pop(arr[l-1]));\n chkr = false;\n break;\n }\n chkr = true;\n chk = true;\n res += 1;\n }\n if (res >= l-1) {\n chkr = true;\n chk = false; \n }\n}\nif (chk == true) {\n print(res);\n} \nelse {\n print (\"-1\");\n}"}, {"source_code": ";(function () {\n\n print(function () {\n var n = +readline(),\n a = readline().split(' ').map(Number),\n d = 0, r = null;\n\n if (n === 2) {\n return a[0] <= a[1] ? 0 : 1;\n }\n\n a.forEach(function (e, i, a) {\n if (i === 0) return;\n if (e < a[i - 1]) {\n d++;\n r = i;\n }\n });\n\n if (d === 0) return 0;\n if (d > 1) return -1;\n return n - r;\n }.call(this));\n\n}.call(this));\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i], 10);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar n = parseInt(readline()),\n\t\tvalues = tokenizeIntegers(readline());\n\tfor (var seek = 1; seek < n; ++seek) {\n\t\tif (values[seek-1] > values[seek]) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (seek == n) {\n\t\treturn 0;\n\t}\n\tvar end = seek-1;\n\tfor (var i = end+2; i < n; ++i) {\n\t\tif (values[i-1] > values[i]) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\tif (values[n-1] > values[0]) {\n\t\treturn -1;\n\t}\n\treturn Math.min(end+1, n-end-1);\n}\n\nprint(main());\n"}, {"source_code": "//\n\n\nvar line = readline();\n\nvar ray = readline().split(' ');\nvar n = parseInt(line);\nvar bRay = [];\n\n\nfor(var i = 0 ; i < n ; i++) {\n\tbRay.push(parseInt(ray[i]));\n}\n\nprint(foo(n,bRay));\n\n//console.log(foo(2,[2,1]));\nfunction foo(n,bRay) {\n\tvar count = 0;\n\t//console.log(checker(n,bRay,1));\n\tif ( !checker(n,bRay,0) ) {\n\t\t\n\t\n\t\tfor(var i = 1 ; i < n ; i++) {\n\t\t\t\n\t\t\tcount++;\n\t\t\tif ( checker(n,bRay,i)) {\n\t\t\t\treturn count;\n\t\t\t}\n\t\t\n\t\t\n\t\t\n\t\t}\n\t}\n\t\n\telse {\n\t\treturn 0;\n\t}\n\t\n\treturn -1;\n\t\n\t\n}\n\nfunction checker(n,ray,p) {\n\tfor(var i = 0 ; i < n-1 ; i++) {\n\t\tvar j = (i+p) %n ;\n\t\tif ( ray[j] > ray[j+1]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t}\n\t\n\treturn true ;\n\t\n}"}], "src_uid": "c647e36495fb931ac72702a12c6bfe58"} {"nl": {"description": "This problem is a complicated version of D1, but it has significant differences, so read the whole statement.Polycarp has an array of $$$n$$$ ($$$n$$$ is even) integers $$$a_1, a_2, \\dots, a_n$$$. Polycarp conceived of a positive integer $$$k$$$. After that, Polycarp began performing the following operations on the array: take an index $$$i$$$ ($$$1 \\le i \\le n$$$) and reduce the number $$$a_i$$$ by $$$k$$$.After Polycarp performed some (possibly zero) number of such operations, it turned out that at least half of the numbers in the array became the same. Find the maximum $$$k$$$ at which such a situation is possible, or print $$$-1$$$ if such a number can be arbitrarily large.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even integer $$$n$$$ ($$$4 \\le n \\le 40$$$) ($$$n$$$ is even). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots a_n$$$ ($$$-10^6 \\le a_i \\le 10^6$$$). It is guaranteed that the sum of all $$$n$$$ specified in the given test cases does not exceed $$$100$$$.", "output_spec": "For each test case output on a separate line an integer $$$k$$$ ($$$k \\ge 1$$$) — the maximum possible number that Polycarp used in operations on the array, or $$$-1$$$, if such a number can be arbitrarily large.", "sample_inputs": ["4\n6\n48 13 22 -15 16 35\n8\n-1 0 1 -1 0 1 -1 0\n4\n100 -1000 -1000 -1000\n4\n1 1 1 1"], "sample_outputs": ["13\n2\n-1\n-1"], "notes": null}, "positive_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const map = {}\n for (let i = 0; i < arr.length; i++) {\n const x = arr[i]\n map[x] = (map[x] || 0) + 1\n if (map[x] >= n / 2) return -1\n }\n\n let ans = -1\n for (let i = 0; i < arr.length; i++) {\n // set arr[i] as target\n const ds = []\n for (let j = 0; j < arr.length; j++) {\n ds[j] = arr[j] - arr[i]\n }\n // try each possible gcd\n const gs = {}\n for (let j = 0; j < arr.length; j++) {\n if (ds[j] <= 0) continue\n gs[ds[j]] = 1\n\n for (let k = 0; k < arr.length; k++) {\n if (k === i || k === j || ds[k] <= 0) continue\n\n const g = gcd(ds[j], ds[k])\n gs[g] = 1\n }\n }\n for (let g in gs) {\n g = +g\n if (g > ans) {\n let count = map[arr[i]] // already\n for (let x = 0; x < arr.length; x++) {\n if (ds[x] <= 0 || (ds[x] % g)) continue\n count++\n }\n // console.log(`target=${arr[i]} g=${g} count=${count}`)\n if (count >= n / 2) ans = g\n }\n }\n }\n return ans\n}\nfunction gcd(a, b) {\n if (a === 0) return b\n if (b === 0) return a\n\n while (a) {\n const r = b % a\n b = a\n a = r\n }\n return b\n}\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction gcd(a, b) {\r\n if (b == 0)\r\n return a;\r\n return gcd(b, a % b);\r\n}\r\n\r\nfunction abs(a) {\r\n return Math.max(a, -a);\r\n}\r\nfunction main() {\r\n let t = Number(readline())\r\n for (let j = 1; j <= t; j++) {\r\n let is = 0\r\n const map = new Map()\r\n let n = Number(readline())\r\n let a = readline().split(' ').map(Number)\r\n for (let i = 0; i < n; i++) {\r\n if (map.has(a[i]))\r\n map.set(a[i], map.get(a[i]) + 1)\r\n else\r\n map.set(a[i], 1)\r\n if (map.get(a[i]) >= n / 2)\r\n is = 1\r\n }\r\n if (is) {\r\n console.log(-1)\r\n continue\r\n }\r\n let ans = 0\r\n for (let i = 0; i < n; i++) {\r\n for (let j = i + 1; j < n; j++) {\r\n let big = abs(a[i] - a[j])\r\n for (let cand = 1; cand * cand <= big; cand++) {\r\n let count = 0\r\n if (big % cand) continue;\r\n for (let k = 0; k < n; k++) {\r\n if (abs(a[i] - a[k]) % cand) continue;\r\n count++\r\n }\r\n if (count >= n / 2)\r\n ans = Math.max(cand, ans)\r\n count = 0\r\n let cand1=big/cand\r\n if (big % cand1) continue;\r\n for (let k = 0; k < n; k++) {\r\n if (abs(a[i] - a[k]) % cand1) continue;\r\n count++\r\n }\r\n if (count >= n / 2)\r\n ans = Math.max(cand1, ans)\r\n }\r\n }\r\n }\r\n console.log(ans)\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('ascii');\r\nlet input = '';\r\nprocess.stdin.on('data', (data) => {\r\n input += data;\r\n});\r\nprocess.stdin.on('end', main);\r\nfunction check(b) {\r\n if (!b) {\r\n process.stderr.write(`${new Error().stack}\\n`);\r\n process.exit(-1);\r\n }\r\n}\r\nclass Scanner {\r\n constructor(input) {\r\n this.words = [];\r\n this.pos = 0;\r\n input.split('\\n').forEach((line) => {\r\n this.words.push.apply(this.words, line.split(' ').filter(s => s != ''));\r\n });\r\n }\r\n nextInt() {\r\n return Math.floor(Number(this.words[this.pos++]));\r\n }\r\n nextBigInt() {\r\n return BigInt(this.nextInt());\r\n }\r\n nextStr() {\r\n return this.words[this.pos++];\r\n }\r\n eof() {\r\n return this.pos >= this.words.length;\r\n }\r\n}\r\nfunction af(l) {\r\n return Array.from({ length: l });\r\n}\r\nconst INF = Number.MAX_SAFE_INTEGER;\r\nconst INIT = -1;\r\nlet n;\r\nlet a;\r\nfunction same() {\r\n let cnt = new Map();\r\n for (let i = 0; i < n; i++) {\r\n cnt.set(a[i], (cnt.get(a[i]) || 0) + 1);\r\n }\r\n for (let [k, v] of cnt) {\r\n if (v * 2 >= n) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction main() {\r\n const sc = new Scanner(input);\r\n let tc = sc.nextInt();\r\n while (tc-- > 0) {\r\n n = sc.nextInt();\r\n a = af(n);\r\n for (let i = 0; i < n; i++) {\r\n a[i] = sc.nextInt();\r\n }\r\n if (same()) {\r\n process.stdout.write(`-1\\n`);\r\n continue;\r\n }\r\n let divs = [];\r\n for (let i = 0; i < n; i++) {\r\n for (let j = i + 1; j < n; j++) {\r\n let diff = Math.abs(a[i] - a[j]);\r\n for (let k = 1; k * k <= diff; k++) {\r\n if ((diff % k) == 0) {\r\n divs.push(diff / k);\r\n divs.push(k);\r\n }\r\n }\r\n }\r\n }\r\n divs = Array.from(new Set(divs));\r\n let ans = 0;\r\n for (let div of divs) {\r\n for (let i = 0; i < n; i++) {\r\n let cnt = 0;\r\n for (let j = 0; j < n; j++) {\r\n let diff = Math.abs(a[i] - a[j]);\r\n if ((diff % div) == 0) {\r\n cnt++;\r\n }\r\n }\r\n if (cnt * 2 >= n) {\r\n ans = Math.max(ans, div);\r\n }\r\n }\r\n }\r\n process.stdout.write(`${ans}\\n`);\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const map = {}\n for (let i = 0; i < arr.length; i++) {\n const x = arr[i]\n map[x] = (map[x] || 0) + 1\n if (map[x] >= n / 2) return -1\n }\n\n let ans = -1\n for (let i = 0; i < arr.length; i++) {\n // set arr[i] as target\n const ds = []\n for (let j = 0; j < arr.length; j++) {\n ds[j] = arr[j] - arr[i]\n }\n // try each possible gcd\n const gs = {}\n for (let j = 0; j < arr.length; j++) {\n for (let k = 0; k < arr.length; k++) {\n if (k === i || k === j || ds[j] <= 0) continue\n\n const g = gcd(ds[j], ds[k])\n gs[g] = 1\n }\n }\n for (let g in gs) {\n g = +g\n if (g > ans) {\n let count = map[arr[i]] // already\n for (let x = 0; x < arr.length; x++) {\n if (ds[x] <= 0 || (ds[x] % g)) continue\n count++\n }\n // console.log(`target=${arr[i]} g=${g} count=${count}`)\n if (count >= n / 2) ans = g\n }\n }\n }\n return ans\n}\nfunction gcd(a, b) {\n if (a === 0) return b\n if (b === 0) return a\n\n while (a) {\n const r = b % a\n b = a\n a = r\n }\n return b\n}\n"}], "src_uid": "432411e161af5ef14803e946e2f7fbc3"} {"nl": {"description": "You have a stripe of checkered paper of length $$$n$$$. Each cell is either white or black.What is the minimum number of cells that must be recolored from white to black in order to have a segment of $$$k$$$ consecutive black cells on the stripe?If the input data is such that a segment of $$$k$$$ consecutive black cells already exists, then print 0. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2\\cdot10^5$$$). The second line consists of the letters 'W' (white) and 'B' (black). The line length is $$$n$$$. It is guaranteed that the sum of values $$$n$$$ does not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each of $$$t$$$ test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of $$$k$$$ consecutive black cells.", "sample_inputs": ["4\n\n5 3\n\nBBWBW\n\n5 5\n\nBBWBW\n\n5 1\n\nBBWBW\n\n1 1\n\nW"], "sample_outputs": ["1\n2\n0\n1"], "notes": "NoteIn the first test case, $$$s$$$=\"BBWBW\" and $$$k=3$$$. It is enough to recolor $$$s_3$$$ and get $$$s$$$=\"BBBBW\". This string contains a segment of length $$$k=3$$$ consisting of the letters 'B'.In the second test case of the example $$$s$$$=\"BBWBW\" and $$$k=5$$$. It is enough to recolor $$$s_3$$$ and $$$s_5$$$ and get $$$s$$$=\"BBBBB\". This string contains a segment of length $$$k=5$$$ consisting of the letters 'B'.In the third test case of the example $$$s$$$=\"BBWBW\" and $$$k=1$$$. The string $$$s$$$ already contains a segment of length $$$k=1$$$ consisting of the letters 'B'."}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\n\r\nconst solve = () => {\r\n const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let [n,k] = readline().trim().split(\" \").map(cur=>parseInt(cur));\r\n let arr = readline().trim().split(\"\");\r\n let min = Infinity,i=0,cnt = 0,j=0;\r\n while(i+x);\r\n let str = readline().trim();\r\n console.log(`${solve(str, n, k)}`)\r\n}\r\n\r\nfunction solve(str, n, k){\r\n let result = n;\r\n let currW = 0;\r\n for(let i = 0; i < n; i++){\r\n if(str[i] === 'W') currW++;\r\n \r\n if(i-k +1 >= 0){\r\n result = Math.min(result, currW);\r\n if(str[i-k+1] === \"W\") currW--;\r\n }\r\n if(result === 0) break;\r\n }\r\n return result;\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const [n, k] = lines[l++].trim().split(' ').map(Number)\n const str = lines[l++]\n output[i] = solve(n, k, str)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nlet F\nfunction inc(idx, val) {\n for (; idx < F.length; idx |= idx + 1) {\n F[idx] += val\n }\n}\nfunction sum(idx) {\n let s = 0\n for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {\n s += F[idx]\n }\n return s\n}\n\nfunction solve(n, k, str) {\n F = Array(n + 5).fill(0)\n for (let i = 0; i < str.length; i++) {\n if (str[i] === 'B') {\n inc(i, 1)\n }\n }\n let ans = Infinity\n for (let i = 0; i + k - 1 < str.length; i++) {\n // [i, i + k - 1]\n const d = sum(i + k - 1) - (i ? sum(i - 1) : 0)\n // console.log(i, k - d)\n ans = Math.min(ans, k - d)\n }\n // console.log('-')\n return ans\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar N = nextInt();\r\n\t\tvar K = nextInt();\r\n\t\tvar list = next();\r\n\t\tvar sum = new Array(N + 1).fill(0);\r\n\t\tfor(var i = 0; i < N; i++){\r\n\t\t\tif(list[i] == \"W\"){\r\n\t\t\t\tsum[i + 1]++;\r\n\t\t\t}\r\n\t\t\tsum[i + 1] += sum[i];\r\n\t\t}\r\n\t\tvar output = 1000000000;\r\n\t\tfor(var i = 0; i < N - K + 1; i++){\r\n\t\t\toutput = Math.min(output, sum[i + K] - sum[i]);\r\n\t\t}\r\n\t\tmyout(output);\r\n\t}\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n const sum = new Array(n);\r\n for (let i = 0; i < n; i++) {\r\n var _sum;\r\n sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + (s[i] === 'B' ? 0 : 1);\r\n }\r\n let res = Infinity;\r\n for (let i = m - 1; i < n; i++) {\r\n var _sum2;\r\n res = Math.min(res, sum[i] - ((_sum2 = sum[i - m]) !== null && _sum2 !== void 0 ? _sum2 : 0));\r\n }\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [n, m] = (await read()).split(' ').map(Number);\r\n const s = await read();\r\n res.push(solve(n, m, s));\r\n }\r\n console.log(res.join('\\n'));\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', () => {\r\n inputs = str.split('\\n').values();\r\n main(read);\r\n});\r\n"}, {"source_code": "var tests = parseInt(readline());\r\n var n, k;\r\n var s;\r\n for (var t=0; t < tests; t++) {\r\n var nk = readline().split(' ').map(x=>parseInt(x));\r\n n = nk[0];\r\n k = nk[1];\r\n var s = readline();\r\n var dict = {\r\n B: 0,\r\n W: 0,\r\n }\r\n for (var i = 0; i < k; i++) {\r\n dict[s.charAt(i)]++;\r\n }\r\n var minW = dict.W;\r\n for (var i = k; i < n; i++) {\r\n dict[s.charAt(i)]++;\r\n dict[s.charAt(i-k)]--;\r\n if (dict.W < minW) {\r\n minW = dict.W;\r\n }\r\n }\r\n print(minW);\r\n }"}], "negative_code": [], "src_uid": "6e3bacbe61775883599989d0f61367d5"} {"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 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.", "output_spec": "On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — 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": "var pearlsAmount = readline();\nvar typesOfPearls = readline().split(' ');\nvar segmentsEndPoints = [];\nvar amountOfSegments = 0;\nvar object = {};\nfor (var i = 0; i < pearlsAmount; i++) {\n if (object[typesOfPearls[i]]) {\n amountOfSegments++;\n segmentsEndPoints.push(i+1);\n object = {};\n } else {\n object[typesOfPearls[i]] = 1;\n }\n}\n\nif (amountOfSegments == 0) {\n print(\"-1\");\n} else {\n segmentsEndPoints.pop();\n segmentsEndPoints.push(pearlsAmount);\n print(amountOfSegments);\n var startPoint = 1;\n for (var i = 0; i < amountOfSegments; i++) {\n print(startPoint + \" \" + segmentsEndPoints[i]);\n startPoint = segmentsEndPoints[i] + 1;\n }\n}"}, {"source_code": "var pearlsAmount = readline();\nvar typesOfPearls = readline().split(' ');\nvar segmentsEndPoints = [];\nvar amountOfSegments = 0;\nvar typesExistence = [];\nfor (var i = 0; i < pearlsAmount; i++) {\n if (typesExistence[typesOfPearls[i]]) {\n amountOfSegments++;\n segmentsEndPoints.push(i+1);\n typesExistence.length = 0;\n } else {\n typesExistence[typesOfPearls[i]] = 1;\n }\n}\n\nif (amountOfSegments == 0) {\n print(\"-1\");\n} else {\n segmentsEndPoints.pop();\n segmentsEndPoints.push(pearlsAmount);\n print(amountOfSegments);\n var startPoint = 1;\n for (var i = 0; i < amountOfSegments; i++) {\n print(startPoint + \" \" + segmentsEndPoints[i]);\n startPoint = segmentsEndPoints[i] + 1;\n }\n}"}, {"source_code": "var pearlsAmount = readline();\nvar typesOfPearls = readline().split(' ');\nvar segmentsEndPoints = [];\nvar amountOfSegments = 0;\nvar typesExistence = [];\nfor (var i = 0; i < pearlsAmount; i++) {\n if (typesExistence[typesOfPearls[i]]) {\n amountOfSegments++;\n segmentsEndPoints.push(i+1);\n typesExistence = [];\n } else {\n typesExistence[typesOfPearls[i]] = 1;\n }\n}\n\nif (amountOfSegments == 0) {\n print(\"-1\");\n} else {\n segmentsEndPoints.pop();\n segmentsEndPoints.push(pearlsAmount);\n print(amountOfSegments);\n var startPoint = 1;\n for (var i = 0; i < amountOfSegments; i++) {\n print(startPoint + \" \" + segmentsEndPoints[i]);\n startPoint = segmentsEndPoints[i] + 1;\n }\n}"}, {"source_code": "var n = readline();\nvar pearls = readline().split(' ');\n\nvar counter = [];\n\nvar result = [];\nvar rLength = 0;\n\nvar i;\nvar start_idx = 0;\n\npearls.map(function(x, idx) {\n x = parseInt(x, 10);\n if(!counter[x]) {\n counter[x] = 1;\n } else {\n result[rLength] = [start_idx + 1, idx +1];\n start_idx = idx + 1;\n rLength = rLength + 1;\n counter = [];\n }\n});\n\nif (rLength == 0) {\n print(\"-1\");\n}\nelse {\n result[rLength-1][1] = parseInt(n, 10);\n\n print(rLength);\n for (i = 0; i < rLength; i++){\n print(result[i][0]+ ' ' + result[i][1]);\n }\n}"}], "negative_code": [{"source_code": "var n = readline();\nvar pearls = readline().split(' ');\n\nvar counter = [];\n\nvar result = [];\nvar rLength = 0;\n\nvar i;\nvar start_idx = 0;\n\npearls.map(function(x, idx) {\n x = parseInt(x, 10);\n if(!counter[x]) {\n counter[x] = 1;\n } else {\n result[rLength] = [start_idx + 1, idx +1];\n start_idx = idx + 1;\n counter = [];\n }\n});\n\nif (rLength == 0) {\n print(\"-1\\r\\n\");\n}\nelse {\n result[rLength-1][1] = parseInt(n, 10);\n\n print(\"rLength\\r\\n\");\n for (i = 0; i < rLength; i++){\n print(\"result[i][0] result[i][1]\\n\");\n }\n}\n"}, {"source_code": "var n = readline();\nvar pearls = readline().split(' ');\n\nvar counter = [];\n\nvar result = [];\nvar rLength = 0;\n\nvar i;\nvar start_idx = 0;\n\npearls.map(function(x, idx) {\n x = parseInt(x, 10);\n if(!counter[x]) {\n counter[x] = 1;\n } else {\n result[rLength] = [start_idx + 1, idx +1];\n start_idx = idx + 1;\n rLength = rLength + 1;\n counter = [];\n }\n});\n\nif (rLength == 0) {\n print(\"-1\\r\\n\");\n}\nelse {\n result[rLength-1][1] = parseInt(n, 10);\n\n print(\"rLength\\r\\n\");\n for (i = 0; i < rLength; i++){\n print(\"result[i][0] result[i][1]\\n\");\n }\n}\n\n\n\n\n/*\n #include \n int main(void) {\n int i;\n int start_idx = 0;\n\n scanf(\"%d\", &n);\n\n for (i = 0; i < n; i++) {\n scanf(\"%d\", &pearls[i]);\n\n if (increase_count(pearls[i]) == 0) {\n insert_new_pearl(pearls[i]);\n }\n else { // 2개가 되는 순간임\n result[result_length][0] = start_idx + 1;\n result[result_length++][1] = i + 1;\n start_idx = i + 1;\n length = 0;\n }\n }\n\n result[result_length-1][1] = n;\n\n if (result_length == 0) {\n printf(\"-1\\n\");\n }\n else {\n printf(\"%d\\n\", result_length);\n\n for (i = 0; i < result_length; i++){\n printf(\"%d %d\\n\", result[i][0], result[i][1]);\n }\n }\n\n return 0;\n }\n */"}], "src_uid": "4cacec219e4577b255ddf6d39d308e10"} {"nl": {"description": "A matrix of size $$$n \\times m$$$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $$$(a_1, a_2, \\dots , a_k)$$$ is a palindrome, if for any integer $$$i$$$ ($$$1 \\le i \\le k$$$) the equality $$$a_i = a_{k - i + 1}$$$ holds.Sasha owns a matrix $$$a$$$ of size $$$n \\times m$$$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him!", "input_spec": "The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \\le t \\le 10$$$). The $$$t$$$ tests follow. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 100$$$) — the size of the matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i, j}$$$ ($$$0 \\le a_{i, j} \\le 10^9$$$) — the elements of the matrix.", "output_spec": "For each test output the smallest number of operations required to make the matrix nice.", "sample_inputs": ["2\n4 2\n4 2\n2 4\n4 2\n2 4\n3 4\n1 2 3 4\n5 6 7 8\n9 10 11 18"], "sample_outputs": ["8\n42"], "notes": "NoteIn the first test case we can, for example, obtain the following nice matrix in $$$8$$$ operations:2 24 44 42 2In the second test case we can, for example, obtain the following nice matrix in $$$42$$$ operations:5 6 6 56 6 6 65 6 6 5"}, "positive_code": [{"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? -1 : 1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var sr = [x, y, z, w];\n sr.sort(mp)\n add = Math.min(Math.abs(sr[0] - sr[1]) + Math.abs(sr[2] - sr[1]) + Math.abs(sr[3] - sr[1]),\n Math.abs(sr[0] - sr[2]) + Math.abs(sr[1] - sr[2]) + Math.abs(sr[3] - sr[2])\n ,Math.abs(sr[1] - sr[0]) + Math.abs(sr[2] - sr[0]) + Math.abs(sr[3] - sr[0])\n ,Math.abs(sr[0] - sr[3]) + Math.abs(sr[1] - sr[3]) + Math.abs(sr[2] - sr[3]));\n\n if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [_row, _col] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const arr = [];\n for (let i = 0; i < _row; i++) {\n const r = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n arr.push(r);\n }\n\n let count = 0;\n\n for (let row = 0; row < _row; row++) {\n for (let col = 0; col < _col / 2; col++) {\n let nums = [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]];\n nums.sort((a, b) => a - b);\n const target = nums[1];\n count += Math.abs(target - nums[0]) + Math.abs(target - nums[1]) + Math.abs(target - nums[2]);\n [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]] = [target, target, target];\n }\n }\n console.log(count);\n }\n}\n"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n let sub = [];\n a = a || 0;\n b = b || (this.length - 1);\n for (let i = a; i <= b; i++) {\n sub.push(this[i])\n if (fn(this[i], i, this)) {\n arr.push(sub);\n sub = [];\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nlet MOD = 998244353\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + MOD) % MOD;\n}\n\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let t = $()\n while (t--) {\n let [n, m] = $(2), res = 0\n let a = Arr(n, i => $(m))\n // log(a)\n For((n + 1) / 2 | 0, i => {\n For((m + 1) / 2 | 0, j => {\n let a1 = a[i][j], a2 = a[n - 1 - i][j], a3 = a[i][m - 1 - j], a4 = a[n - 1 - i][m - 1 - j];\n let s = min(\n abs(a2-a1)+abs(a3-a1)+abs(a4-a1),\n abs(a1-a2)+abs(a3-a2)+abs(a4-a2),\n abs(a1-a3)+abs(a2-a3)+abs(a4-a3),\n abs(a1-a4)+abs(a2-a4)+abs(a3-a4),\n )\n if (i == n - 1 - i) s /= 2;\n if (j == m - 1 - j) s /= 2;\n res += s;\n })\n })\n log(res)\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n B();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction B(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let [n,m] = ti(readline().split(' '));\n let mat = new Array(n);\n for(let i = 0; i < n; i++){\n mat[i] = ti(readline().split(' '));\n }\n\n let count = 0;\n for(let i = 0; i < n/2; i++){\n for(let j = 0; j < m/2; j++){\n let a = [];\n if(i !== n-i-1 && j !== m-j-1){\n a = [mat[i][j], mat[i][m-j-1], mat[n-i-1][j], mat[n-i-1][m-j-1]];;\n }else{\n a = [mat[i][j], mat[n-i-1][m-j-1]];\n }\n a.sort((a,b) => a-b);\n if(a.length === 4)\n count += Math.abs(a[0]-a[1]) + Math.abs(a[1]-a[2]) + Math.abs(a[1]-a[3]);\n else\n count += Math.abs(a[0]-a[1]);\n }\n }\n\n console.log(count);\n }\n}\n"}, {"source_code": "'use strict'\nfunction solv() {\n var ip = readline().split(' ').map(x => parseInt(x));\n var x = ip[0];\n var y = ip[1];\n var grid = new Array(x);\n for (var n = 0; n < x; n++) {\n grid[n] = readline().split(' ').map(x => parseInt(x));\n }\n var res = 0;\n for (var n = 0; n < x; n++) {\n for (var k = 0; k < y; k++) {\n var a = grid[n][k];\n var b = grid[x - 1 - n][k];\n var c = grid[n][y - 1 - k];\n var d = grid[x - 1 - n][y - 1 - k];\n var tm = [a, b, c, d];\n tm.sort((x, y) => { return x > y });\n var md = tm[3] - tm[0] + tm[2] - tm[1]\n res += md\n /**/\n }\n }\n\n print(Math.floor(res / 4))\n}\n\nvar tc = parseInt(readline())\nwhile (tc--) solv()"}, {"source_code": "'use strict'\nfunction solv() {\n var ip = readline().split(' ').map(x => parseInt(x));\n var x = ip[0];\n var y = ip[1];\n var grid = new Array(x);\n for (var n = 0; n < x; n++) {\n grid[n] = readline().split(' ').map(x => parseInt(x));\n }\n var res = 0;\n for (var n = 0; n < x; n++) {\n for (var k = 0; k < y; k++) {\n var a = grid[n][k];\n var b = grid[x - 1 - n][k];\n var c = grid[n][y - 1 - k];\n var d = grid[x - 1 - n][y - 1 - k];\n var tm = [a, b, c, d];\n tm.sort((x, y) => { return x > y });\n var md = tm[3] - tm[0] + tm[2] - tm[1]\n res += md\n /**/\n }\n }\n\n print(Math.floor(res / 4))\n}\n\nvar tc = parseInt(readline())\nwhile (tc--) solv()"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n add = Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n add = Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n add = Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n \n if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}], "negative_code": [{"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a, b = readline().split(' ').map(mp);\n var arr = [];\n for(var i = 0; i < a; a++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\nn = 1\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < a[0] / 2; i++) {\n var l = 0, r = a[1] - 1;\n while(l < r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n print(ans)\n }\n }\n print(ans); // odd rows cols not handel yet xD\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line)\n }\n \n print(arr[0]);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\nn = 1\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < a[0]; i++) {\n var l = 0, r = a[1] - 1;\n while(l < r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n print(ans)\n }\n }\n print(ans); // odd rows cols not handel yet xD\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line)\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a, b = readline().split(' ').map(mp);\n var arr = [];\n print(a, b)\n for(var i = 0; i < a; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line[0]);\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < a[0]; i++) {\n var l = 0, r = a[1] - 1;\n while(l < r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n print(ans); // odd rows cols not handel yet xD\n }\n }\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a, b = readline().split(' ').map(mp);\n var arr = [];\n print(n)\n for(var i = 0; i < a; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line[0]);\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\nn = 1\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < (a[0] + 1) / 2; i++) {\n print(i)\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < a[0]; i++) {\n var l = 0, r = a[1] - 1;\n while(l < r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n \n }print(ans); // odd rows cols not handel yet xD\n }\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? -1 : 1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var sr = [x, y, z, w];\n sr.sort(mp)\n add = Math.min(Math.abs(sr[0] - sr[1]) + Math.abs(sr[2] - sr[1]) + Math.abs(sr[3] - sr[1]),\n Math.abs(sr[0] - sr[2]) + Math.abs(sr[1] - sr[2]) + Math.abs(sr[3] - sr[2]));\n\n if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a, b = readline().split(' ').map(mp);\n var arr = [];\n for(var i = 0; i < a; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? -1 : 1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n toSort.sort(mp)\n\n add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n \n \n if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a, b = readline().split(' ').map(mp);\n var arr = [];\n for(var i = 0; i < a; a++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n print(line)\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var sr = [x, y, z, w];\n\n add = Math.min(Math.abs(sr[0] - sr[1]) + Math.abs(sr[2] - sr[1]) + Math.abs(sr[3] - sr[1]),\n Math.abs(sr[0] - sr[2]) + Math.abs(sr[1] - sr[2]) + Math.abs(sr[3] - sr[2]));\n\n if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < (a[0] + 1) / 2; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < a[0]; i++) {\n var l = 0, r = a[1] - 1;\n while(l < r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n \n }\n }\n print(ans); // odd rows cols not handel yet xD\n}"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const map = new Map();\n const [_row, _col] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const arr = [];\n for (let i = 0; i < _row; i++) {\n const r = readLine()\n .split(\" \")\n .map((n) => {\n n = parseInt(n);\n map.set(n, n);\n return n;\n });\n arr.push(r);\n }\n\n let min = Infinity;\n for (let [key, value] of map) {\n let count = 0;\n for (let row = 0; row < _row; row++) {\n for (let col = 0; col < _col; col++) {\n const diff = Math.abs(arr[row][col] - key);\n count += diff;\n }\n }\n min = Math.min(min, count);\n }\n\n console.log(min);\n }\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\nfunction permutation(arr, len, store = \"\", permutations = []) {\n if (store.length === len) {\n permutations.push(store);\n return;\n }\n for (let i = 0; i < arr.length; i++) {\n const newArr = [...arr];\n const newChar = newArr.splice(i, 1);\n permutation(newArr, len, store.concat(newChar), permutations);\n }\n return permutations;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const [_row, _col] = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n const arr = [];\n for (let i = 0; i < _row; i++) {\n const r = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n arr.push(r);\n }\n\n let count = 0;\n\n for (let row = 0; row < _row; row++) {\n for (let col = 0; col < Math.floor(_col / 2); col++) {\n let nums = [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]];\n nums.sort((a, b) => a - b);\n const target = nums[1];\n count += Math.abs(target - nums[0]) + Math.abs(target - nums[1]) + Math.abs(target - nums[2]);\n [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]] = [target, target, target];\n }\n }\n console.log(count);\n }\n}\n"}, {"source_code": "function For(a, b, fn) {\n if (!fn) return For(0, a - 1, b);\n let res;\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) != null) return res;\n }\n}\nfunction ForR(a, b, fn) {\n if (!fn) return ForR(a - 1, 0, b);\n let res;\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) != null) return res;\n }\n}\n\nfunction Arr(a, b, fn) {\n if (typeof (b) == 'function') return Arr(0, a - 1, b);\n if (b < a) return [];\n let arr = Array(b - a + 1)\n for (let i = a; i <= b; i++) arr[i] = fn(i, arr);\n return arr;\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn ? fn(v) : v).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = 1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x < min) { min = x; index = i }\n }\n return [this[index], index, min];\n}\nArray.prototype.max = function (fn) {\n let max = -1e20, index = -1, x;\n for (let i = 0; i < this.length; i++) {\n x = fn ? fn(this[i], i, this) : this[i];\n if (x > max) { max = x; index = i }\n }\n return [this[index], index, max];\n}\nArray.prototype.rev = function (first, last) {\n for (let i = first; i < (first + last) / 2; i++) {\n [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]\n }\n}\nArray.prototype.set = function (pos, arr) {\n for (let i = pos; i < pos + arr.length; i++) {\n this[i] = arr[i - pos];\n }\n}\nArray.prototype.for = function (a, b, fn) {\n let res\n for (let i = a; i <= b; i++) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.forR = function (a, b, fn) {\n let res\n for (let i = a; i >= b; i--) {\n if ((res = fn(this[i], i, this)) != null) return res;\n }\n}\nArray.prototype.bin = function (comp, a, b) {\n let mid;\n while (a < b) {\n mid = (a + b) / 2 | 0;\n if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;\n else b = mid;\n }\n return a;\n}\nArray.prototype.cut = function (fn, a, b) {\n let arr = [];\n let sub = [];\n a = a || 0;\n b = b || (this.length - 1);\n for (let i = a; i <= b; i++) {\n sub.push(this[i])\n if (fn(this[i], i, this)) {\n arr.push(sub);\n sub = [];\n }\n }\n return arr;\n}\n\nfunction gcd(a, b) {\n while (b) [a, b] = [b, a % b];\n return a;\n}\nfunction mul(a, b, m) {\n return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m\n}\nfunction pow(a, n, m) {\n let r = 1;\n while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]\n return r;\n}\nlet MOD = 998244353\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);\n return (u + MOD) % MOD;\n}\n\n// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));\n// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));\n// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });\n// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);\n\n// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1\n// for (i = pos; i; i -= i & -i) ans += fen[i];\n\n// let p = [2];\n// for (let i = 3; i < 1e5; i += 2) {\n// let j, x = Math.sqrt(i);\n// for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;\n// if (i % p[j] != 0) p.push(i);\n// }\n\n// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));\n// let dsu = (x, y) => {\n// if ((x = root(x)) == (y = root(y))) return;\n// if (par[y] < par[x]) [x, y] = [y, x];\n// par[x] += par[y];\n// par[y] = x;\n// }\n\nlet input = '';\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', main);\nfunction main() {\n let inp = input.split(/\\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],\n out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;\n let t = $()\n while (t--) {\n let [n, m] = $(2), res = 0\n let a = Arr(n, i => $(m))\n // log(a)\n For((n + 1) / 2 | 0, i => {\n For((m + 1) / 2 | 0, j => {\n let a1 = a[i][j], a2 = a[n - 1 - i][j], a3 = a[i][m - 1 - j], a4 = a[n - 1 - i][m - 1 - j];\n // log(i, j, a1, a2, a3, a4)\n let tb = Math.round((a1 + a2 + a3 + a4) / 4)\n let s = abs(a1 - tb) + abs(a2 - tb) + abs(a3 - tb) + abs(a4 - tb);\n if (i == n - 1 - i || j == m - 1 - j) s /= 2;\n res += s;\n })\n })\n log(res)\n }\n}\n"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n \n for(var i = 0; i < a[0]; i++) {\n var l = 0, r = a[1] - 1;\n while(l < r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n l++, r--;\n print(ans)\n }\n }\n print(ans); // odd rows cols not handel yet xD\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a, b = readline().split(' ').map(mp);\n var arr = [];\n for(var i = 0; i < a; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line[0]);\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n \n add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n \n \n if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n obj[x] = (obj[x] ? obj[x] + 1 : 1);\n obj[y] = (obj[y] ? obj[y] + 1 : 1);\n obj[z] = (obj[z] ? obj[z] + 1 : 1);\n obj[w] = (obj[w] ? obj[w] + 1 : 1);\n if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {\n toSort.sort(cmp);\n add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n }else {\n if(obj[x] != 1) {\n add = Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);\n }else if(obj[y] != 1) {\n add = Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);\n }else {\n add = Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);\n }\n }\n \n if(l == r || i + 1 == m) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n print(a)\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line[0]);\n }\n \n print(arr);\n}"}, {"source_code": "function i(v) {\n return parseInt(v);\n}\n\nfunction f(v) {\n return parseFloat(v);\n}\n\nfunction cmp(a, b) {\n return a - b > 0 ? 1 : -1;\n}\n\nfunction mp(v) {\n return parseInt(v); \n}\n\nvar n = i(readline());\n\nwhile(n--) {\n var a = readline().split(' ').map(mp);\n var arr = [];\n var ans = 0;\n for(var i = 0; i < a[0]; i++) {\n var line = readline().split(' ').map(mp);\n arr.push(line);\n }\n var m = parseInt((a[0] + 1) / 2)\n for(var i = 0; i < m; i++) {\n var l = 0, r = a[1] - 1;\n while(l <= r) {\n var obj = {};\n var x = arr[i][l];\n var y = arr[i][r];\n var z = arr[a[0] - i - 1][l];\n var w = arr[a[0] - i - 1][r];\n var toSort = [x, y, z, w];\n toSort.sort(mp)\n add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],\n -toSort[0] - toSort[1] + toSort[2] + toSort[3]);\n \n \n if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)\n else ans += add\n l++, r--;\n }\n }\n print(ans); \n}"}], "src_uid": "5aa709f292f266799f177b174c8bc14b"} {"nl": {"description": " One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like \"Hidden to the left of the i-th box\" (\"To the left of i\"), \"Hidden to the right of the i-th box\" (\"To the right of i\"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.", "input_spec": "The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like \"To the left of i\" and \"To the right of i\", where i is integer (1 ≤ i ≤ n). The hints may coincide.", "output_spec": "The answer should contain exactly one integer — the number of boxes that should necessarily be checked or \"-1\" if the hints are contradictory.", "sample_inputs": ["2 1\nTo the left of 2", "3 2\nTo the right of 1\nTo the right of 2", "3 1\nTo the left of 3", "3 2\nTo the left of 2\nTo the right of 1"], "sample_outputs": ["1", "1", "2", "-1"], "notes": null}, "positive_code": [{"source_code": "'use strict'\n\nlet lll = readline().split(' ').map(v => parseInt(v))\nlet N = lll[0]\nlet ls = []\nlet rs = []\nfor (let i = 0; i < lll[1]; i++) {\n let ll = readline().split(' ')\n ;(ll[2] == 'left' ? ls : rs).push(+ll[ll.length - 1])\n}\n\nlet bs = []\n\nlet n = N\nwhile(n--) {\n bs.push(true)\n}\n\nls = ls.sort((a, b) => a - b)\nrs = rs.sort((a, b) => a - b)\n\nlet ml = ls.length ? ls[0] : N + 1\nlet mr = rs.length ? rs[rs.length - 1] : 0\n\nlet r = ml - mr - 1\n\nprint(r <= 0 ? -1 : r)"}, {"source_code": "var getNums = function() {\n\treturn readline().split(' ').map(function(a) {return parseInt(a)});\n};\n\nvar input;\ninput = getNums();\nvar n1 = input[0];\nvar n2 = input[1];\nvar left = 1, right = n1;\n\nfor (var i = 0; i < n2; i++) {\n\tinput = readline();\n\tvar j;\n\tif (input.match(/To the left of/)) {\n\t\tj = parseInt(input.replace('To the left of ',''));\n\t\tright = Math.min(right, j - 1);\n\t} else {\n\t\tj = parseInt(input.replace('To the right of ',''));\n\t\tleft = Math.max(left, j + 1);\n\t}\n}\n\nif (left > right) {\n\tprint(-1);\n} else {\n\tprint(right - left + 1);\n}"}], "negative_code": [], "src_uid": "dabeb9852332f6a6e730acab7fe61a5c"} {"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$$$) — 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": "var n = +readline();\nvar arr = [];\nfor (var i = 0; i < n; i++) {\n arr[i] = 0;\n}\nfor (var i = 1; i < n; i++) {\n var point = readline().split(' ').map(item => +item - 1);\n arr[point[0]]++;\n arr[point[1]]++;\n}\nprint(arr.find(item => item === 2) ? 'NO' : 'YES');\n"}, {"source_code": "\"use strict\";\n\n// readline().split(' ').map(value => +value);\nvar n = +readline();\nvar A = new Array(Math.pow(10, 5) + 100).fill(0);\nfor (var i = 0; i < n - 1; ++i) {\n var input = readline().split(' ').map(value => +value);\n var u = input[0];\n var v = input[1];\n \n ++A[u];\n ++A[v];\n}\n\nvar result = 'YES';\nfor (var i = 1; i <= n; ++i) {\n if (A[i] === 2) {\n result = 'NO';\n break;\n }\n}\n\nwrite(result);"}], "negative_code": [], "src_uid": "ba47e6eea45d32cba660eb6d66a9adbb"} {"nl": {"description": "There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?", "input_spec": "The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\\frac{n}{2}$$$.", "output_spec": "Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.", "sample_inputs": ["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"], "sample_outputs": ["3", "9", "0"], "notes": "NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly."}, "positive_code": [{"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = new Array(n).fill(Number.MAX_SAFE_INTEGER); data.push(tmp); } return data; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\nconst solve = (n, a) => {\r\n let dp = initialize2DArrayNew(n + 1, n + 1);\r\n let x = [];\r\n let y = [];\r\n for (let i = 0; i < n; i++) a[i] == 1 ? x.push(i) : y.push(i);\r\n // pr(x);\r\n // pr(y);\r\n let xn = x.length;\r\n let yn = y.length;\r\n // pr(xn, yn);\r\n dp[0][0] = 0;\r\n for (let i = 0; i < xn + 1; i++) {\r\n for (let j = 0; j < yn + 1; j++) {\r\n dp[i][j + 1] = mi(dp[i][j + 1], dp[i][j]);\r\n // pr(dp[i][j+1])\r\n if (i < xn && j < yn) {\r\n dp[i + 1][j + 1] = mi(dp[i + 1][j + 1], dp[i][j] + abs(x[i] - y[j]));\r\n }\r\n }\r\n }\r\n pr(dp[xn][yn]);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\nconst initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = new Array(n).fill(Number.MAX_SAFE_INTEGER); data.push(tmp); } return data; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\nconst solve = (n, a) => {\r\n let dp = initialize2DArrayNew(5011, 5011);\r\n let x = [];\r\n let y = [];\r\n for (let i = 0; i < n; i++) a[i] == 1 ? x.push(i) : y.push(i);\r\n // pr(x);\r\n // pr(y);\r\n let xn = x.length;\r\n let yn = y.length;\r\n // pr(xn, yn);\r\n dp[0][0] = 0;\r\n for (let i = 0; i < xn + 1; i++) {\r\n for (let j = 0; j < yn + 1; j++) {\r\n dp[i][j + 1] = mi(dp[i][j + 1], dp[i][j]);\r\n // pr(dp[i][j+1])\r\n if (i < xn && j < yn) {\r\n dp[i + 1][j + 1] = mi(dp[i + 1][j + 1], dp[i][j] + abs(x[i] - y[j]));\r\n }\r\n }\r\n }\r\n pr(dp[xn][yn]);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}], "negative_code": [{"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\n// WA test 8 and 9 algorithm is wrong\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n } else {\r\n pr(\"1111\")\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n if (res == 42) {\r\n res = 40;\r\n } else if (res == 514) {\r\n res = 482;\r\n } else if (res == 1138) {\r\n res = 1102;\r\n } else if (res == 1182) {\r\n res = 1140;\r\n } else if (res == 1098) {\r\n res = 1090;\r\n } else if (n == 5000 && res == 1140) {\r\n res = 1138;\r\n }\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\n// WA test 8 and 9 algorithm is wrong\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n } else {\r\n pr(\"1111\")\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n if (res == 42) res = 40;\r\n if (res == 514) res = 482;\r\n if (res == 1138) res = 1102;\r\n if (res == 1182) res = 1140;\r\n if (res == 1098) res = 1090;\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\n// WA test 8 and 9 algorithm is wrong\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n } else {\r\n pr(\"1111\")\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n if (res == 42) res = 40;\r\n if (res == 514) res = 482;\r\n if (res == 1138) res = 1102;\r\n if (res == 1182) res = 1140;\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\n// WA test 8 and 9 algorithm is wrong\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n } else {\r\n pr(\"1111\")\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n if (res == 42) res = 40;\r\n if (res == 514) res = 482;\r\n if (res == 1138) res = 1102;\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\n// WA test 8 and 9 algorithm is wrong\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n } else {\r\n pr(\"1111\")\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n if (res == 42) res = 40;\r\n if (res == 514) res = 482;\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\n// WA test 8\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n } else {\r\n pr(\"1111\")\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n pr(res == 42 ? 40: res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0n;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += BigInt(diffl);\r\n } else {\r\n swap(a, ri, i);\r\n res += BigInt(diffr);\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += BigInt(abs(li - i));\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += BigInt(abs(ri - i));\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n pr(res.toString());\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl < diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n // if (a[i] == 0 || origin[i] == 0) continue;\r\n if (a[i] == 1 && origin[i] == 1) {\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n }\r\n }\r\n // pr(a);\r\n }\r\n }\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}, {"source_code": "///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////\r\nconst pr = console.log;\r\nconst mi = Math.min;\r\nconst mx = Math.max;\r\nconst abs = Math.abs;\r\nconst fl = Math.floor;\r\nconst ce = Math.ceil;\r\nconst sq = Math.sqrt;\r\nconst lge = Math.log;\r\nconst lg10 = Math.log10;\r\nconst gcd = (a, b) => b == 0 ? a : gcd(b, a % b);\r\nconst lcm = (a, b) => (a / gcd(a, b)) * b;\r\nconst amax = (a) => mx.apply(Math, a);\r\nconst amin = (a) => mi.apply(Math, a);\r\nconst sm = (a) => a.reduce(((x, y) => x + y), 0);\r\nconst aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);\r\nconst swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];\r\nconst stin = (a) => a.sort((x, y) => x - y);\r\nconst stde = (a) => a.sort((x, y) => y - x);\r\nconst counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/**\r\n * 05/15/21 night\r\n * https://codeforces.com/contest/1525/problem/D\r\n */\r\n\r\nconst solve = (n, a) => {\r\n // pr(n, a);\r\n let res = 0;\r\n let origin = [...a];\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] == 0 || origin[i] == 0) continue;\r\n let li, ri;\r\n for (let l = i - 1; ~l; l--) {\r\n if (a[l] == 0 && origin[l] == 0) {\r\n li = l;\r\n break;\r\n }\r\n }\r\n for (let r = i + 1; r < n; r++) {\r\n if (a[r] == 0 && origin[r] == 0) {\r\n ri = r;\r\n break;\r\n }\r\n }\r\n if (li != undefined) {\r\n if (ri != undefined) {\r\n let diffl = abs(li - i);\r\n let diffr = abs(ri - i);\r\n if (diffl <= diffr) {\r\n swap(a, li, i);\r\n res += diffl;\r\n } else {\r\n swap(a, ri, i);\r\n res += diffr;\r\n }\r\n } else {\r\n swap(a, li, i);\r\n res += abs(li - i);\r\n }\r\n } else {\r\n if (ri != undefined) {\r\n swap(a, ri, i);\r\n res += abs(ri - i);\r\n }\r\n }\r\n // pr(a);\r\n }\r\n pr(res);\r\n};\r\n\r\nconst main = () => {\r\n const readline = require('readline');\r\n const rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n });\r\n let input = [];\r\n rl.on('line', (line) => {\r\n input.push(line.split(\" \").map(x => Number(x)));\r\n });\r\n rl.on('close', () => {\r\n solve(input[0][0], input[1]);\r\n });\r\n};\r\n\r\nmain()"}], "src_uid": "ff5abd7dfd6234ddaf0ee7d24e02c404"} {"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$$$) — 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": "const readline = require('readline');\n\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nfunction readLines(number, cb) {\n const lines = [];\n rl.on('line', function(line) {\n lines.push(line);\n if (lines.length === number) {\n rl.close();\n cb(lines);\n }\n });\n};\n\nfunction doIt(lines) {\n const n = parseInt(lines[0]);\n const doors = lines[1].split(\" \").map(x => parseInt(x));\n const lastDoor = doors[n-1];\n for (let i = n-2; i >=0; i--) {\n if (lastDoor!==doors[i]) {\n console.log(i+1);\n return;\n }\n }\n}\n\nreadLines(2, doIt);"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n\tinput: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n\tobj = init(inLine);\n\tconsole.error('\\n↑入力 ↓出力');\n\tMain();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n\treturn {\n\t\tlist : input, index : 0, max : input.length,\n\t\thasNext : function(){return (this.index < this.max);},\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n\t};\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n\tvar N = nextInt();\n\tvar list = nextIntArray();\n\tvar one = 0;\n\tvar two = 0;\n\tfor(var i = 0; i < N; i++){\n\t\tif(list[i] == 0){\n\t\t\tone++;\n\t\t}else{\n\t\t\ttwo++;\n\t\t}\n\t}\n\tfor(var i = 0; i < N; i++){\n\t\tif(list[i] == 0){\n\t\t\tone--;\n\t\t}else{\n\t\t\ttwo--;\n\t\t}\n\t\tif(one == 0 || two == 0){\n\t\t\tmyout(i + 1);\n\t\t\treturn;\n\t\t}\n\t}\n}\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n\n let one = 0;\n let two = 0;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === 0) {\n two = i + 1;\n }\n else {\n one = i + 1;\n }\n }\n\n if (one > two) {\n one = two;\n }\n\n console.log(one);\n\n c++;\n});\n"}, {"source_code": "let input = [];\n \nconst RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n});\n\nRL.on('line', (line) => {\n input.push(line);\n});\n\n\nRL.on('close', () => {\n let {0:n, 1:m} = {...input[0].split(' ')};\n n = parseInt(n); m = parseInt(m);\n\n let lastLeft = 0, lastRight = 0;\n let countLeft = 0, countRight = 0;\n input[1].split(' ').forEach( (i, j) => {\n i = parseInt(i);\n if (i === 1){\n countRight++; lastRight = j;\n } else {\n countLeft++; lastLeft = j;\n } \n });\n\n console.log( (lastLeft > lastRight) ? lastRight+1 : lastLeft+1);\n});\n\n\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nrl.question('', ans => {\n const n = Number(ans)\n rl.question('', ans2 => {\n rl.close()\n\n const doors = ans2.split(' ').map(x => Number(x))\n\n const lDoor = doors[doors.length - 1]\n for (let i = doors.length - 2; i >= 0; i--) {\n if (doors[i] !== lDoor) {\n console.log(i + 1)\n break\n }\n }\n })\n})"}, {"source_code": "var n = readline().split(\" \");\nvar d = readline().split(\" \");\n\nvar totalL = 0;\nvar totalR = 0;\nvar countL = 0;\nvar countR = 0;\n\nfor(var i = 0 ; i < n; i++) {\n if (d[i] == 0) {\n totalL++;\n }\n}\n\ntotalR = n-totalL;\n\nfor(var i = 0 ; i < n; i++) {\n if (d[i] == 0) {\n countL++;\n } else\n countR++;\n if (countL == totalL || countR == totalR) {\n print(i+1);\n break;\n }\n}"}, {"source_code": "readline();\nvar doors = readline().split(' ').map(function(num) {\n return parseInt(num);\n})\n\n// var doors = [1,1,0]\n\nvar seq = doors[doors.length-1]\n\nfunction main() {\n for (var i = doors.length-1; i > -1; i--) {\n if (doors[i] !== seq)\n return write(i + 1 + '');\n }\n write(doors.length)\n}\n\nmain();"}, {"source_code": "var len = parseInt(readline());\nvar doorArr = readline().split(' ').map(_=>{return parseInt(_)});\n\nvar rightIndex = 1;\nvar leftIndex = 1;\nfor (var index = 0;index < doorArr.length;index ++) {\n if (doorArr[index] == 0) {\n leftIndex = index + 1;\n } else if (doorArr[index] == 1) {\n rightIndex = index + 1;\n }\n \n}\nvar result = rightIndex < leftIndex ? rightIndex : leftIndex;\nprint(parseInt(result));"}], "negative_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n\n let ans = 0;\n let idx = arr.indexOf(1);\n let idxLast = arr.lastIndexOf(1);\n\n if (idx === idxLast) {\n ans = idx + 1;\n }\n else {\n ans = idxLast - idx;\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nrl.question('', ans => {\n const n = Number(ans)\n rl.question('', ans2 => {\n rl.close()\n\n const doors = ans2.split(' ').map(x => Number(x))\n\n const max = Math.floor(n/2)\n const min = {\n l: 0,\n r: 0\n }\n\n for (let i = 0; i < doors.length; i++) {\n item = doors[i]\n if (item === 0) { min.l += 1 }\n if (item === 1) { min.r += 1 }\n\n if ((min.l === max || min.r === max) && (min.l + min.r > max)) {\n console.log(min.l + min.r)\n break\n } \n }\n })\n})"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nrl.question('', ans => {\n const n = Number(ans)\n rl.question('', ans2 => {\n rl.close()\n\n const doors = ans2.split(' ').map(x => Number(x))\n\n const max = Math.floor(n/2)\n const min = {\n l: 0,\n r: 0\n }\n\n for (let i = 0; i < doors.length; i++) {\n item = doors[i]\n if (item === 0) { min.l += 1 }\n if (item === 1) { min.r += 1 }\n // console.log(min.l, min.r, (min.l >= max || min.r >= max), ((min.l + min.r) > max))\n if ((min.l >= max || min.r >= max) && ((min.l + min.r) > max)) {\n console.log(min.l + min.r)\n break\n } \n }\n })\n})"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\n\nrl.question('', ans => {\n const n = Number(ans)\n rl.question('', ans2 => {\n rl.close()\n\n const doors = ans2.split(' ').map(x => Number(x))\n\n const max = Math.ceil(n/2)\n const min = {\n l: 0,\n r: 0\n }\n\n for (let i = 0; i < doors.length; i++) {\n item = doors[i]\n if (item === 0) min.l += 1\n if (item === 1) min.r += 1\n\n if (min.l === max || min.r === max) {\n console.log(min.l + min.r)\n break\n } \n }\n })\n})"}, {"source_code": "// readline();\n// var doors = readline().split(' ').map(function(num) {\n// return parseInt(num);\n// })\n\nvar doors = [1,1,0]\n\nvar seq = doors[doors.length-1]\n\nfunction main() {\n for (var i = doors.length-1; i > -1; i--) {\n if (doors[i] !== seq)\n return write(i + 1 + '');\n }\n write(doors.length)\n}\n\nmain();"}, {"source_code": "var len = parseInt(readline());\nvar doorArr = readline().split('').map(_=>{return parseInt(_)});\n\nvar rightIndex = 1;\nvar leftIndex = 1;\nfor (var index = 0;index < doorArr.length;index ++) {\n if (doorArr[index] == 0) {\n leftIndex = index + 1;\n } else if (doorArr[index] == 1) {\n rightIndex = index + 1;\n }\n \n}\nvar result = rightIndex < leftIndex ? rightIndex : leftIndex;\nprint(parseInt(result));"}, {"source_code": "var len = parseInt(readline());\nvar doorArr = readline().split('').map(_=>{return parseInt(_)});\n\nvar rightIndex = 1;\nvar leftIndex = 1;\nfor (var index = 0;index < len;index ++) {\n if (doorArr[index] == 0) {\n leftIndex ++;\n } else if (doorArr[index] == 1) {\n rightIndex ++;\n }\n \n}\nvar result = rightIndex > leftIndex ? rightIndex : leftIndex;\nprint(parseInt(result));"}, {"source_code": "var len = parseInt(readline());\nvar doorArr = readline().split('').map(_=>{return parseInt(_)});\n\nvar rightIndex = 1;\nvar leftIndex = 1;\nfor (var index = 0;index < len;index ++) {\n if (doorArr[index] == 0) {\n leftIndex = index + 1;\n } else if (doorArr[index] == 1) {\n rightIndex = index + 1;\n }\n \n}\nvar result = rightIndex < leftIndex ? rightIndex : leftIndex;\nprint(parseInt(result));"}, {"source_code": "\n var len = parseInt(readline());\nvar doorArr = readline().split('').map(_=>{return parseInt(_)});\n\nvar rightIndex = 1;\nvar leftIndex = 1;\nfor (var index = 0;index < len;index ++) {\n if (doorArr[index] == 0) {\n leftIndex ++;\n } else if (doorArr[index] == 1) {\n rightIndex ++;\n }\n \n}\nprint(rightIndex > leftIndex ? rightIndex : leftIndex);"}, {"source_code": "var len = parseInt(readline());\nvar doorArr = readline().split('').map(_=>{return parseInt(_)});\n\nvar rightIndex = 1;\nvar leftIndex = 1;\nfor (var index = 0;index < len;index ++) {\n if (doorArr[index] == 0) {\n leftIndex = index + 1;\n } else if (doorArr[index] == 1) {\n rightIndex = index + 1;\n }\n \n}\nvar result = rightIndex > leftIndex ? rightIndex : leftIndex;\nprint(parseInt(result));"}], "src_uid": "653455bb6762effbf7358d75660a7689"} {"nl": {"description": "You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.", "input_spec": "The first line contains two integers n and k (2 ≤ n ≤ 105, 2 ≤ k ≤ min (n, 20))  — the length of the array and the number of segments you need to split the array into. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the array.", "output_spec": "Print single integer: the minimum possible total cost of resulting subsegments.", "sample_inputs": ["7 3\n1 1 3 3 3 2 1", "10 2\n1 2 1 2 1 2 1 2 1 2", "13 3\n1 2 2 2 1 2 1 1 1 2 2 1 1"], "sample_outputs": ["1", "8", "9"], "notes": "NoteIn the first example it's optimal to split the sequence into the following three subsegments: [1], [1, 3], [3, 3, 2, 1]. The costs are 0, 0 and 1, thus the answer is 1.In the second example it's optimal to split the sequence in two equal halves. The cost for each half is 4.In the third example it's optimal to split the sequence in the following way: [1, 2, 2, 2, 1], [2, 1, 1, 1, 2], [2, 1, 1]. The costs are 4, 4, 1."}, "positive_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '',currentLine = 0,\n readline=_=>inputString[currentLine++]\nprocess.stdin.on('data', inputStdin =>inputString += inputStdin);\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n main(); \n});\n\n\n\n// Note there's no need to do it for every test case like kickstart\n// tests: $ cat input.txt | node \"c:\\....name.js\"\nfunction main() {\n\n let YAMPDC2=(A,m)=>{\n let n=A.length\n \n let dp=[...Array(m+1)].map(d=>[...Array(n+1)].map(d=>Infinity))\n dp[0][0]=0\n \n let freq=[...Array(n+2)].map(d=>0),nl=0,nr=-1,sum=0\n let fixnl=target=>{\n while(nltarget){\n nl--\n sum+=freq[A[nl]]\n freq[A[nl]]++\n }\n }\n let fixnr=target=>{\n while(nrtarget){\n freq[A[nr]]--\n sum-=freq[A[nr]]\n nr--\n }\n }\n let DC=(i,jleft,jright,kleft,kright)=>{\n if(jleft>jright)\n return\n let bestk=-1,mid=(jleft+jright)>>1\n \n fixnr(mid-1)\n for (let k = Math.max(0,kleft); k <= Math.min(mid-1,kright); k++){\n fixnl(k)\n if(dp[i-1][k]+sumNumber(d)) //reads just the n for a simple test case\n let A=readline().split(\" \").map(d=>Number(d))\n let result=YAMPDC2(A,m) //solves a simple test case\n console.log(result.toString())\n}\n\n\n\n"}], "negative_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '',currentLine = 0,\n readline=_=>inputString[currentLine++]\nprocess.stdin.on('data', inputStdin =>inputString += inputStdin);\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n main(); \n});\n\n\n\n// Note there's no need to do it for every test case like kickstart\n// tests: $ cat input.txt | node \"c:\\....name.js\"\nfunction main() {\n\n let YAMPDC2=(A,m)=>{\n let n=A.length\n \n let dp=[...Array(m+1)].map(d=>[...Array(n+1)].map(d=>1e9))\n dp[0][0]=0\n \n let freq=[...Array(n+2)].map(d=>0),nl=0,nr=-1,sum=0\n let fixnl=target=>{\n while(nltarget){\n nl--\n sum+=freq[A[nl]]\n freq[A[nl]]++\n }\n }\n let fixnr=target=>{\n while(nrtarget){\n freq[A[nr]]--\n sum-=freq[A[nr]]\n nr--\n }\n }\n let DC=(i,jleft,jright,kleft,kright)=>{\n if(jleft>jright)\n return\n let bestk=-1,mid=(jleft+jright)>>1\n \n fixnr(mid-1)\n for (let k = Math.max(0,kleft); k <= Math.min(mid-1,kright); k++){\n fixnl(k)\n if(dp[i-1][k]+sumNumber(d)) //reads just the n for a simple test case\n let A=readline().split(\" \").map(d=>Number(d))\n let result=YAMPDC2(A,m) //solves a simple test case\n console.log(result.toString())\n}\n\n\n\n"}], "src_uid": "837e3278a68c6d9ca4715c42be8517d8"} {"nl": {"description": "You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.", "input_spec": "The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.", "output_spec": "The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.", "sample_inputs": ["24\n17:30", "12\n17:30", "24\n99:99"], "sample_outputs": ["17:30", "07:30", "09:09"], "notes": null}, "positive_code": [{"source_code": "var a = readline(),\n\tb = readline(),\n\th = [b[0], b[1]]\n\tm = [b[3], b[4]]\n\t\nif (a == 12) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] >= 2) {\n\t\tif (h[1] == 0) {\n\t\t\th[0] = '1'\n\t\t}\n\t\telse {\n\t\t\th[0] = '0'\n\t\t}\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 2 && h[1] >= 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h[0] + h[1] + ':' + m[0] + m[1])"}, {"source_code": "var system,\n input,\n answer,\n hh,\n mm;\n\nsystem = parseInt( readline(), 10 );\ninput = readline();\nhh = parseInt( input.slice( 0, 2 ), 10 );\nmm = parseInt( input.slice( 3 ), 10 );\n\nif ( system == 12 ) {\n if ( hh === 0 ) {\n hh = 1; \n } else if ( hh > 12 ) {\n if ( hh % 10 !== 0 ) {\n hh = hh % 10;\n } else {\n hh = 10;\n }\n }\n} else {\n if ( hh > 23 ) {\n hh = hh % 10;\n }\n}\nif ( mm > 59 ) {\n mm = mm % 10;\n}\n\nanswer = \"\";\nif ( hh.toString().length === 1 ) {\n answer += 0;\n}\nanswer += hh + \":\";\nif ( mm.toString().length === 1 ) {\n answer += 0;\n}\nanswer += mm;\n\nprint( answer );\n"}, {"source_code": "//Input\n\n// var firstLine = \"24\" ; var secondLine = \"17:30\"; // pe: 17:30 (no changes)\n// var firstLine = \"12\" ; var secondLine = \"17:30\"; // pe: 07:30 (1 change)\n// var firstLine = \"24\" ; var secondLine = \"99:99\"; // pe: 19:19 (2 changes)\n// var firstLine = \"12\" ; var secondLine = \"00:05\"; // pe: 01:05 (1 changes)\n// var firstLine = \"12\" ; var secondLine = \"90:32\"; // pe: 10:32 (1 changes)\n// var firstLine = \"12\" ; var secondLine = \"20:00\"; // pe: 10:00 (1 changes)\n\nvar firstLine = readline(); var secondLine = readline();\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var format = firstLine;\n var hourMin = secondLine;\n\n write(correctTime(format, hourMin));\n // console.log(correctTime(format, hourMin));\n // return \"Hola\";\n};\n\nfunction correctTime(format, hourMin){\n //console.log( parseInt(hourMin.slice(3,5)) > 59 );\n if(parseInt(hourMin.slice(3,5)) > 59){\n hourMin = hourMin.slice(0, 3) + \"1\" + hourMin[4];\n };\n\n //if(format == \"24\" && parseInt(hourMin.slice(0,2)) > 23 ){\n if( parseInt(hourMin.slice(0,2)) > 23 ){\n if(hourMin[1] != \"0\"){\n hourMin = \"1\" + hourMin.slice(1, 5);\n }else{\n hourMin = \"10\" + hourMin.slice(2, 5);\n };\n };\n\n if (format == \"12\" && parseInt(hourMin.slice(0,2)) > 12){\n\n\n //hourMin = \"0\" + hourMin.slice(1, 5);\n if(hourMin[1] != \"0\"){\n hourMin = \"0\" + hourMin.slice(1, 5);\n }else{\n hourMin = \"10\" + hourMin.slice(2, 5);\n };\n\n\n };\n\n if (format == \"12\" && (hourMin.slice(0,2)) == \"00\"){\n hourMin = \"01\" + hourMin.slice(2, 5);\n };\n\n //console.log(\"hourMin: \" + hourMin);\n return hourMin;\n};\n\n"}, {"source_code": " var a = readline(),\n \tb = readline();\n\n\n//function r(a, b) {\n\n\t\t//var \n\t\th = b[0] + b[1],\n\tm = b[3] + b[4]\n\t\n\tif( a == 24) {\n\t\tif(h[0] > 2) {\n\t\t\th = 0 + h[1]\n\t\t}\n\t\tif(h[0] == 2 && h[1] > 3) {\n\t\t\th = h[0] + 0\n\t\t}\n\t\tif(m[0] > 5) {\n\t\t\tm = 0 + m[1]\n\t\t}\n\t\t\n\t}\n\tif( a == 12) {\n\t\tif(h == '00') {\n\t\t\th = '01' \n\t\t}\n\t\tif(h[0] > 1 && h[1] < 3) {\n\t\t\th = 1 + h[1]\n\t\t}\n\t\tif(h[0] > 1 && h[1] > 2) {\n\t\t\th = 0 + h[1]\n\t\t}\n\t\tif(h[0] == 1 && h[1] > 2) {\n\t\t\th = h[0] + 0\n\t\t}\n\t\tif(m[0] > 5) {\n\t\t\tm = 0 + m[1]\n\t\t}\n\t\t\n\t}\n\tvar s = h + ':' + m\n\tprint(s)\n\t//console.log(s)\n\t\n//}\n"}, {"source_code": " var a = readline(),\n \tb = readline().split('');\n\n\n//function r(a, b) {\n\n\t\t//var \n\t\th = b[0] + b[1],\n\tm = b[3] + b[4]\n\t\n\tif( a == 24) {\n\t\tif(h[0] > 2) {\n\t\t\th = '0' + h[1]\n\t\t}\n\t\tif(h[0] == 2 && h[1] > 3) {\n\t\t\th = h[0] + '0'\n\t\t}\n\t\tif(m[0] > 5) {\n\t\t\tm = '0' + m[1]\n\t\t}\n\t\t\n\t}\n\tif( a == 12) {\n\t\tif(h == '00') {\n\t\t\th = '01' \n\t\t}\n\t\tif(h[0] > 1 && h[1] < 3) {\n\t\t\th = '1' + h[1]\n\t\t}\n\t\tif(h[0] > 1 && h[1] > 2) {\n\t\t\th = '0' + h[1]\n\t\t}\n\t\tif(h[0] == 1 && h[1] > 2) {\n\t\t\th = h[0] + 0\n\t\t}\n\t\tif(m[0] > 5) {\n\t\t\tm = '0' + m[1]\n\t\t}\n\t\t\n\t}\n\tvar s = h + ':' + m\n\tprint(s)\n\t//console.log(s)\n\t\n//}\n"}, {"source_code": " var a = readline(),\n \tb = readline();\n\n\n//function r(a, b) {\n\n\t\t//var \n\t\th = b[0] + b[1],\n\tm = b[3] + b[4]\n\t\n\tif( a == 24) {\n\t\tif(h[0] > 2) {\n\t\t\th = '0' + h[1]\n\t\t}\n\t\tif(h[0] == 2 && h[1] > 3) {\n\t\t\th = h[0] + '0'\n\t\t}\n\t\tif(m[0] > 5) {\n\t\t\tm = '0' + m[1]\n\t\t}\n\t\t\n\t}\n\tif( a == 12) {\n\t\tif(h == '00') {\n\t\t\th = '01' \n\t\t}\n\t\tif(h[0] > 1 && h[1] < 3) {\n\t\t\th = '1' + h[1]\n\t\t}\n\t\tif(h[0] > 1 && h[1] > 2) {\n\t\t\th = '0' + h[1]\n\t\t}\n\t\tif(h[0] == 1 && h[1] > 2) {\n\t\t\th = h[0] + 0\n\t\t}\n\t\tif(m[0] > 5) {\n\t\t\tm = '0' + m[1]\n\t\t}\n\t\t\n\t}\n\tvar s = h + ':' + m\n\tprint(s)\n\t//console.log(s)\n\t\n//}\n"}, {"source_code": "var format = parseInt(readline()),\n times = readline().split(':'),\n hh = times[0],\n mm = times[1];\n\n// 1. correct hours\nif (format === 12) {\n if (hh === '00') hh = '01';\n else if (parseInt(hh) > 12) {\n //debugger;\n // a. Fix 1 number\n // if (hh[0] === '1') hh = hh[0] + 0;\n // else if (parseInt(hh[1]) <= 2) hh = 1 + hh[1];\n // // b. Fix 2 numbers\n // else hh = '01';\n hh = hh[1] !== '0' ? 0 + hh[1] : '10';\n }\n} else if (format === 24 && parseInt(hh) > 23) {\n // a. Fix 1 number\n hh = 0 + hh[1];\n}\n\n\n// 2. Correct minutes\nif (parseInt(mm) > 59) {\n mm = 0 + mm[1];\n}\n\nprint(hh + ':' + mm);"}, {"source_code": "//var arr = [{format: 24, value: '17:30'},{format: 12, value: '17:30'},{format: 24, value: '99:99'}];\n\nfunction solve(obj){\n\tvar ret = '';\n\tvar str = obj.value;\n\tif(obj.format == 24){\n\t\tif((Number(str.charAt(0)) > 2) || ((Number(str.charAt(0)) == 2) && (Number(str.charAt(1)) > 3)))\n\t\t\tret = '0' + str.charAt(1);\n\t\telse ret = str.substr(0, 2);\n\t}\n\telse if(obj.format == 12){\n\t\tif((Number(str.charAt(0)) == 0) && (Number(str.charAt(1)) == 0))\n\t\t\tret = '10';\n\t\telse if((Number(str.charAt(0)) > 1) || ((Number(str.charAt(0)) == 1) && (Number(str.charAt(1)) > 2))){\n\t\t\tif(Number(str.charAt(1)) < 2) ret = '1';\n\t\t\telse ret = '0';\n\t\t\tret = ret + str.charAt(1);\n\t\t}\n\t\telse ret = str.substr(0, 2);\n\t}\n\tret = ret + ':';\n\tif(Number(str.charAt(3)) > 5){\n\t\tret = ret + '0' + str.charAt(4);\n\t}\n\telse ret = ret + str.substr(3, 2);\n\t\n\treturn ret;\n}\n\nvar fmt = readline();\nvar val = readline();\nvar objetao = {format: Number(fmt), value: String(val)};\nprint(solve(objetao));"}, {"source_code": "var format = parseInt(readline());\nvar clock = readline().replace(':', '').split('').map(Number);\n\n// adjust clock\nif(format === 12) {\n \n if(clock[0] === 0 && clock[1] === 0) {\n clock[1] = 1;\n } else if(clock[0] === 1 && clock[1] > 2) {\n clock[1] = 2;\n } else if(clock[0] > 1 && clock[1] !== 0) {\n clock[0] = 0;\n } else if(clock[0] > 1 && clock[1] === 0) {\n clock[0] = 1;\n }\n}\n\nif(format === 24) {\n \n if(clock[0] === 2 && clock[1] > 3) {\n clock[1] = 3;\n } else if(clock[0] > 2) {\n clock[0] = 0;\n }\n}\n\n// adjust minutes\nif(clock[2] > 5) {\n clock[2] = 5;\n}\n\nprint(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);"}, {"source_code": "var f24 = readline() === '24';\nvar time = readline();\nvar h1 = parseInt(time[0]);\nvar h2 = parseInt(time[1]);\nvar m1 = parseInt(time[3]);\nvar m2 = parseInt(time[4]);\nif (m1 > 5)\n m1 = 0;\nif (f24) {\n if (h1 === 2) {\n if (h2 > 3)\n h2 = 0;\n }\n else if (h1 > 2)\n h1 = 0;\n}\nelse {\n if (h1 === 1) {\n if (h2 > 2)\n h2 = 0;\n }\n else if (h1 === 0) {\n if (h2 === 0)\n h2 = 1;\n }\n else {\n if (h2 === 0) {\n h1 = 1;\n }\n else {\n h1 = 0;\n }\n }\n}\nprint(h1 + '' + h2 + ':' + m1 + '' + m2);\n"}, {"source_code": "var form=readline();\nvar time=readline();\nvar left=[time[0],time[1]];\nvar right=[time[3],time[4]];\n\nif(right[0]>'5'){\n right[0]='5';\n}\n\nif(form==='24'){\n if(left[0]>'2')\n left[0]='1';\n \n if(left[0]==='2'&&left[1]>'3')\n left[1]='0';\n}\nelse{\n if(left[0]>'1'){\n if(left[1]!='0')\n left[0]='0';\n else\n left[0]='1';\n }\n if(left[0]=='1'&& left[1]>'2'){\n left[1]='1';\n }\n if(left[0]=='0' && left[1]=='0')\n left[1]='1';\n}\nprint(left[0]+left[1]+':'+right[0]+right[1]);\n\n"}], "negative_code": [{"source_code": "var a = readline(),\n\tb = readline(),\n\th = [b[0], b[1]]\n\tm = [b[3], b[4]]\n\t\nif (a == 12) {\n\tif (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 2 && h[1] > 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h[0] + h[1] + ':' + m[0] + m[1])"}, {"source_code": "var a = readline(),\n\tb = readline(),\n\th = b[0] + b[1],\n\tm = b[3] + b[4]\n\t\nif (a == 12) {\n\tif (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 2 && h[1] > 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h + ':' + m)"}, {"source_code": "var a = readline(),\n\tb = readline(),\n\th = [b[0], b[1]]\n\tm = [b[3], b[4]]\n\t\nif (a == 12) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\tif (h[1] == 0) {\n\t\t\th[0] = '1'\n\t\t}\n\t\telse {\n\t\t\th[0] = '0'\n\t\t}\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 2 && h[1] >= 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h[0] + h[1] + ':' + m[0] + m[1])"}, {"source_code": "//Input\n\n// var firstLine = \"24\" ; var secondLine = \"17:30\"; // pe: 17:30 (no changes)\n// var firstLine = \"12\" ; var secondLine = \"07:30\"; // pe: 17:30 (1 change)\n// var firstLine = \"24\" ; var secondLine = \"99:99\"; // pe: 09:09 (2 changes)\n\nvar firstLine = readline(); var secondLine = readline();\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var format = firstLine;\n var hourMin = secondLine;\n\n write(correctTime(format, hourMin));\n // console.log(correctTime(format, hourMin));\n // return \"Hola\";\n};\n\nfunction correctTime(format, hourMin){\n //console.log( parseInt(hourMin.slice(3,5)) > 59 );\n if(parseInt(hourMin.slice(3,5)) > 59){\n hourMin = hourMin.slice(0, 3) + \"1\" + hourMin[4];\n };\n //console.log(\"hourMin: \" + hourMin);\n //console.log( parseInt(hourMin.slice(0,2)) > 23 );\n\n if(format == \"24\" && parseInt(hourMin.slice(0,2)) > 23 ){\n hourMin = \"1\" + hourMin.slice(1, 5);\n } else if (format == \"12\" && parseInt(hourMin.slice(0,2)) > 12){\n hourMin = \"0\" + hourMin.slice(1, 5);\n };\n //console.log(\"hourMin: \" + hourMin);\n return hourMin;\n};\n\n"}, {"source_code": "//Input\n\n// var firstLine = \"24\" ; var secondLine = \"17:30\"; // pe: 17:30 (no changes)\n// var firstLine = \"12\" ; var secondLine = \"07:30\"; // pe: 17:30 (1 change)\n// var firstLine = \"24\" ; var secondLine = \"99:99\"; // pe: 09:09 (2 changes)\n// var firstLine = \"12\" ; var secondLine = \"00:05\"; // pe: 01:05 (1 changes)\n\nvar firstLine = readline(); var secondLine = readline();\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var format = firstLine;\n var hourMin = secondLine;\n\n write(correctTime(format, hourMin));\n // console.log(correctTime(format, hourMin));\n // return \"Hola\";\n};\n\nfunction correctTime(format, hourMin){\n //console.log( parseInt(hourMin.slice(3,5)) > 59 );\n if(parseInt(hourMin.slice(3,5)) > 59){\n hourMin = hourMin.slice(0, 3) + \"1\" + hourMin[4];\n };\n //console.log(\"hourMin: \" + hourMin);\n //console.log( parseInt(hourMin.slice(0,2)) > 23 );\n\n if(format == \"24\" && parseInt(hourMin.slice(0,2)) > 23 ){\n hourMin = \"1\" + hourMin.slice(1, 5);\n };\n if (format == \"12\" && parseInt(hourMin.slice(0,2)) > 12){\n hourMin = \"0\" + hourMin.slice(1, 5);\n };\n if (format == \"12\" && (hourMin.slice(0,2)) == \"00\"){\n hourMin = \"01\" + hourMin.slice(2, 5);\n };\n //console.log(\"hourMin: \" + hourMin);\n return hourMin;\n};\n\n"}, {"source_code": "//Input\n\n// var firstLine = \"24\" ; var secondLine = \"17:30\"; // pe: 17:30 (no changes)\n// var firstLine = \"12\" ; var secondLine = \"17:30\"; // pe: 07:30 (1 change)\n// var firstLine = \"24\" ; var secondLine = \"99:99\"; // pe: 19:19 (2 changes)\n// var firstLine = \"12\" ; var secondLine = \"00:05\"; // pe: 01:05 (1 changes)\n// var firstLine = \"12\" ; var secondLine = \"90:32\"; // pe: 10:32 (1 changes)\n// var firstLine = \"12\" ; var secondLine = \"20:00\"; // pe: 01:00 (1 changes)\n\nvar firstLine = readline(); var secondLine = readline();\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var format = firstLine;\n var hourMin = secondLine;\n\n write(correctTime(format, hourMin));\n // console.log(correctTime(format, hourMin));\n // return \"Hola\";\n};\n\nfunction correctTime(format, hourMin){\n //console.log( parseInt(hourMin.slice(3,5)) > 59 );\n if(parseInt(hourMin.slice(3,5)) > 59){\n hourMin = hourMin.slice(0, 3) + \"1\" + hourMin[4];\n };\n //console.log(\"hourMin: \" + hourMin);\n //console.log( parseInt(hourMin.slice(0,2)) > 23 );\n\n //if(format == \"24\" && parseInt(hourMin.slice(0,2)) > 23 ){\n if( parseInt(hourMin.slice(0,2)) > 23 ){\n if(hourMin[1] != \"0\"){\n hourMin = \"1\" + hourMin.slice(1, 5);\n }else{\n hourMin = \"01\" + hourMin.slice(2, 5);\n };\n };\n if (format == \"12\" && parseInt(hourMin.slice(0,2)) > 12){\n hourMin = \"0\" + hourMin.slice(1, 5);\n };\n if (format == \"12\" && (hourMin.slice(0,2)) == \"00\"){\n hourMin = \"01\" + hourMin.slice(2, 5);\n };\n //console.log(\"hourMin: \" + hourMin);\n return hourMin;\n};\n\n"}, {"source_code": "//Input\n\n// var firstLine = \"24\" ; var secondLine = \"17:30\"; // pe: 17:30 (no changes)\n// var firstLine = \"12\" ; var secondLine = \"17:30\"; // pe: 07:30 (1 change)\n// var firstLine = \"24\" ; var secondLine = \"99:99\"; // pe: 19:19 (2 changes)\n// var firstLine = \"12\" ; var secondLine = \"00:05\"; // pe: 01:05 (1 changes)\n// var firstLine = \"12\" ; var secondLine = \"90:32\"; // pe: 10:32 (1 changes)\n// var firstLine = \"12\" ; var secondLine = \"20:00\"; // pe: 01:00 (1 changes)\n\nvar firstLine = readline(); var secondLine = readline();\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var format = firstLine;\n var hourMin = secondLine;\n\n write(correctTime(format, hourMin));\n // console.log(correctTime(format, hourMin));\n // return \"Hola\";\n};\n\nfunction correctTime(format, hourMin){\n //console.log( parseInt(hourMin.slice(3,5)) > 59 );\n if(parseInt(hourMin.slice(3,5)) > 59){\n hourMin = hourMin.slice(0, 3) + \"1\" + hourMin[4];\n };\n\n //if(format == \"24\" && parseInt(hourMin.slice(0,2)) > 23 ){\n if( parseInt(hourMin.slice(0,2)) > 23 ){\n if(hourMin[1] != \"0\"){\n hourMin = \"1\" + hourMin.slice(1, 5);\n }else{\n hourMin = \"10\" + hourMin.slice(2, 5);\n };\n };\n\n if (format == \"12\" && parseInt(hourMin.slice(0,2)) > 12){\n hourMin = \"0\" + hourMin.slice(1, 5);\n };\n\n if (format == \"12\" && (hourMin.slice(0,2)) == \"00\"){\n hourMin = \"01\" + hourMin.slice(2, 5);\n };\n\n //console.log(\"hourMin: \" + hourMin);\n return hourMin;\n};\n\n"}, {"source_code": "//Input\n\n// var firstLine = \"24\" ; var secondLine = \"17:30\"; // pe: 17:30 (no changes)\n// var firstLine = \"12\" ; var secondLine = \"07:30\"; // pe: 17:30 (1 change)\n// var firstLine = \"24\" ; var secondLine = \"99:99\"; // pe: 09:09 (2 changes)\n\nvar firstLine = readline(); var secondLine = readline();\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var format = firstLine;\n var hourMin = secondLine;\n\n write(correctTime(format, hourMin));\n // console.log(correctTime(format, hourMin));\n // return \"Hola\";\n};\n\nfunction correctTime(format, hourMin){\n //console.log( parseInt(hourMin.slice(3,5)) > 59 );\n if(parseInt(hourMin.slice(3,5)) > 59){\n hourMin = hourMin.slice(0, 3) + \"1\" + hourMin[4];\n };\n //console.log(\"hourMin: \" + hourMin);\n //console.log( parseInt(hourMin.slice(0,2)) > 23 );\n\n format = \"12\";\n if(format == \"24\" && parseInt(hourMin.slice(0,2)) > 23 ){\n hourMin = \"1\" + hourMin.slice(1, 5);\n } else if (format == \"12\" && parseInt(hourMin.slice(0,2)) > 12){\n hourMin = \"0\" + hourMin.slice(1, 5);\n };\n //console.log(\"hourMin: \" + hourMin);\n\n\n return hourMin;\n};\n\n"}, {"source_code": "//Input\n\n// var firstLine = \"24\" ; var secondLine = \"17:30\"; // pe: 17:30 (no changes)\n// var firstLine = \"12\" ; var secondLine = \"07:30\"; // pe: 17:30 (1 change)\n// var firstLine = \"24\" ; var secondLine = \"99:99\"; // pe: 09:09 (2 changes)\n// var firstLine = \"12\" ; var secondLine = \"00:05\"; // pe: 01:05 (1 changes)\n// var firstLine = \"12\" ; var secondLine = \"90:32\"; // pe: 10:32 (1 changes)\n\nvar firstLine = readline(); var secondLine = readline();\n\nretorno = eval(firstLine, secondLine);\n\n//Solution\nfunction eval(firstLine, secondLine){\n var format = firstLine;\n var hourMin = secondLine;\n\n write(correctTime(format, hourMin));\n // console.log(correctTime(format, hourMin));\n // return \"Hola\";\n};\n\nfunction correctTime(format, hourMin){\n //console.log( parseInt(hourMin.slice(3,5)) > 59 );\n if(parseInt(hourMin.slice(3,5)) > 59){\n hourMin = hourMin.slice(0, 3) + \"1\" + hourMin[4];\n };\n //console.log(\"hourMin: \" + hourMin);\n //console.log( parseInt(hourMin.slice(0,2)) > 23 );\n\n //if(format == \"24\" && parseInt(hourMin.slice(0,2)) > 23 ){\n if( parseInt(hourMin.slice(0,2)) > 23 ){\n hourMin = \"1\" + hourMin.slice(1, 5);\n };\n if (format == \"12\" && parseInt(hourMin.slice(0,2)) > 12){\n hourMin = \"0\" + hourMin.slice(1, 5);\n };\n if (format == \"12\" && (hourMin.slice(0,2)) == \"00\"){\n hourMin = \"01\" + hourMin.slice(2, 5);\n };\n //console.log(\"hourMin: \" + hourMin);\n return hourMin;\n};\n\n"}, {"source_code": "var format = parseInt(readline()),\n times = readline().split(':'),\n hh = times[0],\n mm = times[1];\n\n// 1. correct hours\nif (format === 12) {\n if (hh === '00') hh = '01';\n else if (parseInt(hh) > 12) {\n //debugger;\n // a. Fix 1 number\n // if (hh[0] === '1') hh = hh[0] + 0;\n // else if (parseInt(hh[1]) <= 2) hh = 1 + hh[1];\n // // b. Fix 2 numbers\n // else hh = '01';\n hh = 0 + hh[1];\n }\n} else if (format === 24 && parseInt(hh) > 23) {\n // a. Fix 1 number\n hh = 0 + hh[1];\n}\n\n\n// 2. Correct minutes\nif (parseInt(mm) > 59) {\n mm = 0 + mm[1];\n}\n\nprint(hh + ':' + mm);"}, {"source_code": "var format = parseInt(readline()),\n times = readline().split(':'),\n hh = times[0],\n mm = times[1];\n\n// 1. correct hours\nif (format === 12) {\n if (hh === '00') hh = '01';\n else if (parseInt(hh) > 12) {\n //debugger;\n // a. Fix 1 number\n if (hh[0] === '1') hh = hh[0] + 0;\n else if (parseInt(hh[1]) <= 2) hh = 1 + hh[1];\n // b. Fix 2 numbers\n else hh = '01';\n }\n} else if (format === 24 && parseInt(hh) > 23) {\n // a. Fix 1 number\n hh = 0 + hh[1];\n}\n\n\n// 2. Correct minutes\nif (parseInt(mm) > 59) {\n mm = 0 + mm[1];\n}\n\nprint(hh + ':' + mm);"}, {"source_code": "//var arr = [{format: 24, value: '17:30'},{format: 12, value: '17:30'},{format: 24, value: '99:99'}];\n\nfunction solve(obj){\n\tvar ret = 0;\n\tvar str = obj.value;\n\tif(obj.format == 24){\n\t\tif((Number(str.charAt(0)) > 2) || ((Number(str.charAt(0)) == 2) && (Number(str.charAt(1)) > 3)))\n\t\t\tret = '0' + str.charAt(1);\n\t\telse ret = str.substr(0, 2);\n\t}\n\telse if(obj.format == 12){\n\t\tif((Number(str.charAt(0)) == 0) && (Number(str.charAt(1)) == 0))\n\t\t\tret = '10';\n\t\telse if((Number(str.charAt(0)) > 1) || ((Number(str.charAt(0)) == 1) && (Number(str.charAt(1)) > 2)))\n\t\t\tret = '0' + str.charAt(1);\n\t\telse ret = str.substr(0, 2);\n\t}\n\tret = ret + ':';\n\tif(Number(str.charAt(3)) > 5){\n\t\tret = ret + '0' + str.charAt(4);\n\t}\n\telse ret = ret + str.substr(3, 2);\n\t\n\treturn ret;\n}\n\nvar fmt = readline();\nvar val = readline();\nvar objetao = {format: Number(fmt), value: String(val)};\nprint(solve(objetao));"}, {"source_code": "//var arr = [{format: 24, value: '17:30'},{format: 12, value: '17:30'},{format: 24, value: '99:99'}];\n\nfunction solve(obj){\n\tvar ret = 0;\n\tvar str = obj.value;\n\tif(obj.format == 24){\n\t\tif((Number(str.charAt(0)) > 2) || ((Number(str.charAt(0)) == 2) && (Number(str.charAt(1)) > 3)))\n\t\t\tret = '0' + str.charAt(1);\n\t\telse ret = str.substr(0, 2);\n\t}\n\telse if(obj.format == 12){\n\t\tif((Number(str.charAt(0)) == 0) && (Number(str.charAt(1)) == 0))\n\t\t\tret = '10';\n\t\telse if((Number(str.charAt(0)) > 1) || ((Number(str.charAt(0)) == 1) && (Number(str.charAt(1)) > 2))){\n\t\t\tif(Number(str.charAt(1)) < 2) ret = ret + '1';\n\t\t\telse ret = ret + '0';\n\t\t\tret = ret + str.charAt(1);\n\t\t}\n\t\telse ret = str.substr(0, 2);\n\t}\n\tret = ret + ':';\n\tif(Number(str.charAt(3)) > 5){\n\t\tret = ret + '0' + str.charAt(4);\n\t}\n\telse ret = ret + str.substr(3, 2);\n\t\n\treturn ret;\n}\n\nvar fmt = readline();\nvar val = readline();\nvar objetao = {format: Number(fmt), value: String(val)};\nprint(solve(objetao));"}, {"source_code": "var format = parseInt(readline());\nvar clock = readline().replace(':', '').split('').map(Number);\n\n// adjust clock\nif(format === 12) {\n \n if(clock[0] === 0 && clock[1] === 0) {\n clock[1] = 1;\n } else if(clock[0] === 1 && clock[1] > 2) {\n clock[1] = 2;\n } else if(clock[0] > 1) {\n \n clock[0] = 0;\n if(clock[1] === 0)\n clock[1] = 1;\n }\n}\n\nif(format === 24) {\n \n if(clock[0] === 2 && clock[1] > 3) {\n clock[1] = 3;\n } else if(clock[0] > 2) {\n clock[0] = 0;\n }\n}\n\n// adjust minutes\nif(clock[2] > 5) {\n clock[2] = 5;\n}\n\nprint(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);"}, {"source_code": "var format = parseInt(readline());\nvar clock = readline().replace(':', '').split('').map(Number);\n\n// adjust clock\nif(format === 12) {\n \n if(clock[0] === 0 && clock[1] === 0) {\n clock[1] = 1;\n } else if(clock[0] === 1 && clock[1] > 2) {\n clock[1] = 2;\n } else if(clock[0] > 1 && clock[1] <= 2) {\n clock[1] = 0;\n } else if(clock[0] > 1 && clock[1] > 2) {\n clock[0] = 0;\n clock[1] = 1;\n }\n}\n\nif(format === 24) {\n \n if(clock[0] === 2 && clock[1] > 3) {\n clock[1] = 3;\n } else if(clock[0] > 2) {\n clock[0] = 0;\n }\n}\n\n// adjust minutes\nif(clock[2] > 5) {\n clock[2] = 5;\n}\n\nprint(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);"}, {"source_code": "var format = parseInt(readline());\nvar clock = readline().replace(':', '').split('').map(Number);\n\n// adjust clock\nif(format === 12) {\n \n if(clock[0] === 0 && clock[1] === 0) {\n clock[1] = 1;\n } else if(clock[0] === 1 && clock[1] > 2) {\n clock[1] = 2;\n } else if(clock[0] > 1 && clock[1] !== 0) {\n clock[1] = 0;\n } else if(clock[0] > 1 && clock[1] === 0) {\n clock[0] = 0;\n clock[1] = 1;\n }\n}\n\nif(format === 24) {\n \n if(clock[0] === 2 && clock[1] > 3) {\n clock[1] = 3;\n } else if(clock[0] > 2) {\n clock[0] = 0;\n }\n}\n\n// adjust minutes\nif(clock[2] > 5) {\n clock[2] = 5;\n}\n\nprint(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);"}, {"source_code": "var format = parseInt(readline());\nvar clock = readline().replace(':', '').split('').map(Number);\n\n// adjust clock\nif(format === 12) {\n \n if(clock[0] === 0 && clock[1] === 0) {\n clock[1] = 1;\n } else if(clock[0] === 1 && clock[1] > 2) {\n clock[1] = 2;\n } else if(clock[0] > 1 && clock[1] !== 0) {\n clock[0] = 0;\n } else if(clock[0] > 1 && clock[1] === 0) {\n clock[0] = 0;\n clock[1] = 1;\n }\n}\n\nif(format === 24) {\n \n if(clock[0] === 2 && clock[1] > 3) {\n clock[1] = 3;\n } else if(clock[0] > 2) {\n clock[0] = 0;\n }\n}\n\n// adjust minutes\nif(clock[2] > 5) {\n clock[2] = 5;\n}\n\nprint(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);"}, {"source_code": "var f24 = readline() === '24';\nvar time = readline();\nvar h1 = parseInt(time[0]);\nvar h2 = parseInt(time[1]);\nvar m1 = parseInt(time[3]);\nvar m2 = parseInt(time[4]);\nif (m1 > 5)\n m1 = 0;\nif (f24) {\n if (h1 === 2) {\n if (h2 > 3)\n h2 = 0;\n }\n else if (h1 > 2)\n h1 = 0;\n}\nelse {\n if (h1 === 1) {\n if (h2 > 2)\n h2 = 0;\n }\n else if (h1 === 0) {\n if (h2 === 0)\n h2 = 1;\n }\n else {\n if (h2 === 0) {\n h1 = 1;\n }\n else {\n h1 = 0;\n }\n }\n}\n"}, {"source_code": "var form=readline();\nvar time=readline();\nvar left=[time[0],time[1]];\nvar right=[time[3],time[4]];\n\nif(right[0]>'5'){\n right[0]='5';\n}\n\nif(form==='24'){\n if(left[0]>'2')\n left[0]='1';\n \n if(left[0]==='2'&&left[1]>'3')\n left[1]='0';\n}\nelse{\n if(left[0]>'1')\n left[0]='0';\n if(left[0]=='1'&& left[1]>'2'){\n left[1]='1';\n }\n}\nprint(left[0]+left[1]+':'+right[0]+right[1]);\n\n"}, {"source_code": "var a = readline(),\n\tb = readline(),\n\th = [b[0], b[1]]\n\tm = [b[3], b[4]]\n\t\nif (a == 12) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 2 && h[1] > 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h[0] + h[1] + ':' + m[0] + m[1])"}, {"source_code": "var a = readline(),\n\tb = readline(),\n\th = [b[0], b[1]]\n\tm = [b[3], b[4]]\n\t\nif (a == 12) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\tif (h[1] == 0) {\n\t\t\th[0] = '1'\n\t\t}\n\t\telse {\n\t\t\th[0] = '0'\n\t\t}\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 2 && h[1] > 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h[0] + h[1] + ':' + m[0] + m[1])"}, {"source_code": "var a = readline(),\n\tb = readline(),\n\th = [b[0], b[1]]\n\tm = [b[3], b[4]]\n\t\nif (a == 12) {\n\tif (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 2 && h[1] > 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h + ':' + m)"}, {"source_code": "var a = readline(),\n\tb = readline(),\n\th = [b[0], b[1]]\n\tm = [b[3], b[4]]\n\t\nif (a == 12) {\n\tif (h[0] == 0 && h[1] == 0) {\n\t\th[1] = '1'\n\t}\n\telse if (h[0] == 1 && h[1] > 2) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\tif (h[1] == 0) {\n\t\t\th[0] = '1'\n\t\t}\n\t\telse {\n\t\t\th[0] = '0'\n\t\t}\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nelse if (a == 24) {\n\tif (h[0] == 2 && h[1] >= 4) {\n\t\th[0] = '0'\n\t}\n\telse if (h[0] > 2) {\n\t\th[0] = '0'\n\t}\n\tif (m[0] > 5) {\n\t\tm[0] = '0'\n\t}\n}\nprint(h[0] + h[1] + ':' + m[0] + m[1])"}], "src_uid": "88d56c1e3a7ffa94354ce0c70d8e958f"} {"nl": {"description": "Naman has two binary strings $$$s$$$ and $$$t$$$ of length $$$n$$$ (a binary string is a string which only consists of the characters \"0\" and \"1\"). He wants to convert $$$s$$$ into $$$t$$$ using the following operation as few times as possible.In one operation, he can choose any subsequence of $$$s$$$ and rotate it clockwise once.For example, if $$$s = 1\\textbf{1}101\\textbf{00}$$$, he can choose a subsequence corresponding to indices ($$$1$$$-based) $$$\\{2, 6, 7 \\}$$$ and rotate them clockwise. The resulting string would then be $$$s = 1\\textbf{0}101\\textbf{10}$$$.A string $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the ordering of the remaining characters.To perform a clockwise rotation on a sequence $$$c$$$ of size $$$k$$$ is to perform an operation which sets $$$c_1:=c_k, c_2:=c_1, c_3:=c_2, \\ldots, c_k:=c_{k-1}$$$ simultaneously.Determine the minimum number of operations Naman has to perform to convert $$$s$$$ into $$$t$$$ or say that it is impossible. ", "input_spec": "The first line contains a single integer $$$n$$$ $$$(1 \\le n \\le 10^6)$$$ — the length of the strings. The second line contains the binary string $$$s$$$ of length $$$n$$$. The third line contains the binary string $$$t$$$ of length $$$n$$$.", "output_spec": "If it is impossible to convert $$$s$$$ to $$$t$$$ after any number of operations, print $$$-1$$$. Otherwise, print the minimum number of operations required.", "sample_inputs": ["6\n010000\n000001", "10\n1111100000\n0000011111", "8\n10101010\n01010101", "10\n1111100000\n1111100001"], "sample_outputs": ["1", "5", "1", "-1"], "notes": "NoteIn the first test, Naman can choose the subsequence corresponding to indices $$$\\{2, 6\\}$$$ and rotate it once to convert $$$s$$$ into $$$t$$$.In the second test, he can rotate the subsequence corresponding to all indices $$$5$$$ times. It can be proved, that it is the minimum required number of operations.In the last test, it is impossible to convert $$$s$$$ into $$$t$$$."}, "positive_code": [{"source_code": "const processData = (lines) => {\n const n = +lines[0]\n const a = lines[1].split('').map(x => +x)\n const b = lines[2].split('').map(x => +x)\n\n let cur = 0\n let min = 0\n let max = 0\n let ac = 0\n let bc = 0\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}], "negative_code": [{"source_code": "const processData = (lines) => {\n const n = +lines[0]\n const a = lines[1].split('').map(x => +x)\n const b = lines[2].split('').map(x => +x)\n\n const diff = []\n let aC = 0\n let bC = 0\n // console.log(a)\n // console.log(b)\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n const a = lines[1].split('').map(x => +x)\n const b = lines[2].split('').map(x => +x)\n\n let cur = 0\n let min = 0\n let max = 0\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n const a = lines[1].split('').map(x => +x)\n const b = lines[2].split('').map(x => +x)\n\n const diff = []\n let aC = 0\n let bC = 0\n // console.log(a)\n // console.log(b)\n for (let i=0; i x !== 0)) {\n let cur = 0\n let curPos = null\n for (let i=0; i i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}], "src_uid": "f6ad39fba01389799fddc2bd7a287138"} {"nl": {"description": "Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x > y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \\le n \\le 60$$$).", "output_spec": "For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.", "sample_inputs": ["5\n\n2\n\n4\n\n6\n\n8\n\n60"], "sample_outputs": ["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"], "notes": "NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$. "}, "positive_code": [{"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn();\r\n const c = Array.from({\r\n length: n + 1\r\n }, () => new Array(n + 1));\r\n c[0][0] = 1;\r\n for (let i = 1; i <= n; i++) {\r\n c[i][i] = c[i][0] = 1;\r\n for (let j = 1; j < i; j++) {\r\n c[i][j] = mod(c[i - 1][j] + c[i - 1][j - 1]);\r\n }\r\n }\r\n let a = c[n - 1][n / 2 - 1];\r\n for (let i = 3; i <= n / 2; i += 2) {\r\n const x = n - (i - 1) * 2,\r\n y = n / 2 - i;\r\n a = mod(a + c[x][y] + c[x - 1][y]);\r\n }\r\n const b = c[n][n / 2];\r\n return `${a} ${mod(b - a - 1)} 1`;\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 100;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\nconst MOD = 998244353;\r\nfunction mod(num) {\r\n return (num % MOD + MOD) % MOD;\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8')\r\n.split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}], "negative_code": [], "src_uid": "63fc2fb08d248f8ccdb3f5364c96dac1"} {"nl": {"description": "There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his office exactly ai times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home. Doctor plans to go home after receiving k animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out. ", "input_spec": "The first line of input data contains two space-separated integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 1014). In the second line are given space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator). ", "output_spec": "If the doctor will overall carry out less than k examinations, print a single number \"-1\" (without quotes). Otherwise, print the sequence of numbers — number of animals in the order in which they stand in the queue. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one \"End of line\"-character. Both will be accepted.", "sample_inputs": ["3 3\n1 2 1", "4 10\n3 3 2 1", "7 10\n1 3 3 1 2 3 1"], "sample_outputs": ["2", "-1", "6 2 3"], "notes": "NoteIn the first sample test: Before examination: {1, 2, 3} After the first examination: {2, 3} After the second examination: {3, 2} After the third examination: {2} In the second sample test: Before examination: {1, 2, 3, 4, 5, 6, 7} After the first examination: {2, 3, 4, 5, 6, 7} After the second examination: {3, 4, 5, 6, 7, 2} After the third examination: {4, 5, 6, 7, 2, 3} After the fourth examination: {5, 6, 7, 2, 3} After the fifth examination: {6, 7, 2, 3, 5} After the sixth examination: {7, 2, 3, 5, 6} After the seventh examination: {2, 3, 5, 6} After the eighth examination: {3, 5, 6, 2} After the ninth examination: {5, 6, 2, 3} After the tenth examination: {6, 2, 3} "}, "positive_code": [{"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n let [n, k] = ils[0].split(' ').map(v => parseInt(v))\n let A = ils[1].split(' ').map(v => parseInt(v))\n let a = A.length\n while (k > a && a > 0) {\n let m = Math.floor(k / a)\n k = k % a\n for (let i = 0; i < A.length; i++) {\n if (A[i] > m) {\n A[i] -= m\n } else if (A[i] > 0) {\n k += m - A[i]\n A[i] = 0\n a--\n }\n }\n }\n if (a > 0) {\n let r = []\n let i = 0\n for (; i < A.length && k > 0; i++) {\n if (A[i] > 0) {\n A[i]--\n k--\n }\n }\n for (let j = i; j < A.length; j++) {\n if (A[j]) r.push(j + 1)\n }\n for (let j = 0; j < i; j++) {\n if (A[j]) r.push(j + 1)\n }\n console.log(r.join(' ') || (k ? -1 : ''))\n } else if (k > 0) {\n console.log(-1)\n } else {\n console.log()\n }\n})"}], "negative_code": [{"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n let [n, k] = ils[0].split(' ').map(v => parseInt(v))\n let A = ils[1].split(' ').map(v => parseInt(v))\n let a = A.length\n while (k > a) {\n let m = Math.floor(k / a)\n k = k % a\n for (let i = 0; i < A.length; i++) {\n if (A[i] >= m) {\n A[i] -= m\n } else if (A[i] > 0) {\n k += A[i]\n A[i] = 0\n a--\n }\n }\n }\n if (a > 0) {\n let r = []\n let i = 0\n for (; i < A.length && k > 0; i++) {\n if (A[i] > 0) {\n A[i]--\n k--\n }\n }\n for (let j = i; j < A.length; j++) {\n if (A[j]) r.push(j + 1)\n }\n for (let j = 0; j < i; j++) {\n if (A[j]) r.push(j + 1)\n }\n console.log(r.join(' ') || (k ? -1 : ''))\n } else if (k > 0) {\n console.log(-1)\n } else {\n console.log()\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n let [n, k] = ils[0].split(' ').map(v => parseInt(v))\n let A = ils[1].split(' ').map(v => parseInt(v))\n let a = A.length\n while (k > a) {\n let m = Math.floor(k / a)\n k = k % a\n for (let i = 0; i < A.length; i++) {\n if (A[i] >= m) {\n A[i] -= m\n } else if (A[i] > 0) {\n k += A[i]\n A[i] = 0\n a--\n }\n }\n }\n if (a > 0) {\n let r = []\n let i = 0\n for (; i < A.length && k > 0; i++) {\n if (A[i] > 0) {\n A[i]--\n k--\n }\n }\n for (let j = i; j < A.length; j++) {\n if (A[j]) r.push(j + 1)\n }\n for (let j = 0; j < i; j++) {\n if (A[j]) r.push(j + 1)\n }\n console.log(r.join(' ') || -1)\n } else if (k > 0) {\n console.log(-1)\n } else {\n console.log()\n }\n})"}, {"source_code": "'use strict'\n\nconst {EOL} = require('os')\n\nlet ipt = ''\nprocess.stdin.on('data', s => ipt += s)\nprocess.stdin.on('end', () => {\n const ils = ipt.split(EOL).slice(0, -1)\n let [n, k] = ils[0].split(' ').map(v => parseInt(v))\n let A = ils[1].split(' ').map(v => parseInt(v))\n let a = A.length\n while (k > a) {\n let m = Math.floor(k / a)\n k = k % a\n for (let i = 0; i < A.length; i++) {\n if (A[i] >= m) {\n A[i] -= m\n } else if (A[i] > 0) {\n k += m - A[i]\n A[i] = 0\n a--\n }\n }\n }\n if (a > 0) {\n let r = []\n let i = 0\n for (; i < A.length && k > 0; i++) {\n if (A[i] > 0) {\n A[i]--\n k--\n }\n }\n for (let j = i; j < A.length; j++) {\n if (A[j]) r.push(j + 1)\n }\n for (let j = 0; j < i; j++) {\n if (A[j]) r.push(j + 1)\n }\n console.log(r.join(' ') || (k ? -1 : ''))\n } else if (k > 0) {\n console.log(-1)\n } else {\n console.log()\n }\n})"}], "src_uid": "8126f40439f2ea808683d22115421c18"} {"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$$$) — 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 — 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": "/* eslint-disable no-continue */\n/* eslint-disable no-param-reassign */\nconst readline = require('readline').createInterface({\n input: process.stdin,\n});\n\nconst lines = [];\n\nreadline.on('line', (line) => {\n if (lines.length === 0) {\n lines.push(Number(line));\n } else {\n lines.push(line);\n }\n});\n\nconst proccessLine = (len, arr) => {\n let count = 0;\n let count1 = 0;\n let count2 = 0;\n\n for (let i = 0; i < len; i += 1) {\n const v = arr[i];\n const rest = v % 3;\n if (rest === 0) {\n count += 1;\n } else if (rest === 1) {\n count1 += 1;\n } else {\n count2 += 1;\n }\n }\n\n count += Math.min(count1, count2) + Math.floor(Math.abs(count2 - count1) / 3);\n\n return count;\n};\n\nreadline.on('close', () => {\n const [_, ...vars] = lines;\n\n for (let i = 0; i < vars.length; i += 2) {\n const len = Number(vars[i]);\n const numbers = vars[i + 1].split(' ').map(Number);\n\n console.log(proccessLine(len, numbers));\n }\n});\n"}, {"source_code": "(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n };\n\n\n var t = read.number();\n\n for(var i = 0; i < t; i++) {\n var n = read.number();\n var a = read.arrNumber(' ').filter(i => i % 3);\n var res = n - a.length;\n n = a.length;\n \n var c2 = 0;\n var c1 = 0;\n for(var j = 0; j < n;j++) {\n if(a[j] % 3 === 1) {\n c1 ++;\n }\n else if(a[j] %3 === 2) {\n c2++;\n }\n }\n res+= Math.min(c1,c2);\n res += Math.floor(Math.abs(c1 - c2) / 3);\n print(res);\n }\n\n}());\n"}], "negative_code": [{"source_code": "/* eslint-disable no-continue */\n/* eslint-disable no-param-reassign */\nconst readline = require('readline').createInterface({\n input: process.stdin,\n});\n\nconst lines = [];\n\nreadline.on('line', (line) => {\n if (lines.length === 0) {\n lines.push(Number(line));\n } else {\n lines.push(line);\n }\n});\n\nconst proccessLine = (len, arr) => {\n let count = 0;\n const rests = {\n 1: 0,\n 2: 0,\n };\n\n for (let i = 0; i < len; i += 1) {\n const v = arr[i];\n const rest = v % 3;\n if (rest === 0) {\n count += 1;\n continue;\n }\n\n rests[rest] += 1;\n }\n\n const restOne = Math.floor(rests[1] / 3);\n rests[1] -= restOne;\n\n const restTwo = Math.floor(rests[2] / 3);\n rests[2] -= restTwo;\n\n return count + restOne + restTwo + Math.min(...Object.values(rests));\n};\n\nreadline.on('close', () => {\n const [_, ...vars] = lines;\n\n for (let i = 0; i < vars.length; i += 2) {\n const len = Number(vars[i]);\n const numbers = vars[i + 1].split(' ').map(Number);\n\n console.log(proccessLine(len, numbers));\n }\n});\n"}, {"source_code": "/* eslint-disable no-continue */\n/* eslint-disable no-param-reassign */\nconst readline = require('readline').createInterface({\n input: process.stdin,\n});\n\nconst lines = [];\n\nreadline.on('line', (line) => {\n if (lines.length === 0) {\n lines.push(Number(line));\n } else {\n lines.push(line);\n }\n});\n\nconst proccessLine = (len, arr) => {\n let count = 0;\n const rests = {\n 1: 0,\n 2: 0,\n };\n\n for (let i = 0; i < len; i += 1) {\n const v = arr[i];\n const rest = v % 3;\n if (rest === 0) {\n count += 1;\n continue;\n }\n\n rests[rest] += 1;\n }\n\n const restCopy = { ...rests };\n let minTogether = Math.min(...Object.values(restCopy));\n const togetherOne = Math.max(restCopy[1] - minTogether * 3, 0);\n const togetherTwo = Math.max(restCopy[2] - minTogether * 3, 0);\n\n minTogether += togetherOne + togetherTwo;\n\n const restOne = Math.floor(rests[1] / 3);\n rests[1] -= restOne * 3;\n const restTwo = Math.floor(rests[2] / 3);\n rests[2] -= restTwo * 3;\n\n const minRest = restOne + restTwo + Math.min(...Object.values(rests));\n\n return count + (minTogether > minRest ? minTogether : minRest);\n};\n\nreadline.on('close', () => {\n const [_, ...vars] = lines;\n\n for (let i = 0; i < vars.length; i += 2) {\n const len = Number(vars[i]);\n const numbers = vars[i + 1].split(' ').map(Number);\n\n console.log(proccessLine(len, numbers));\n }\n});\n"}, {"source_code": "/* eslint-disable no-continue */\n/* eslint-disable no-param-reassign */\nconst readline = require('readline').createInterface({\n input: process.stdin,\n});\n\nconst lines = [];\n\nreadline.on('line', (line) => {\n if (lines.length === 0) {\n lines.push(Number(line));\n } else {\n lines.push(line);\n }\n});\n\nconst proccessLine = (len, arr) => {\n let count = 0;\n const rests = {\n 1: 0,\n 2: 0,\n };\n\n for (let i = 0; i < len; i += 1) {\n const v = arr[i];\n const rest = v % 3;\n if (rest === 0) {\n count += 1;\n continue;\n }\n\n rests[rest] += 1;\n }\n\n const restOne = Math.floor(rests[1] / 3);\n rests[1] -= restOne * 3;\n\n const restTwo = Math.floor(rests[2] / 3);\n rests[2] -= restTwo * 3;\n\n return count + restOne + restTwo + Math.min(...Object.values(rests));\n};\n\nreadline.on('close', () => {\n const [_, ...vars] = lines;\n\n for (let i = 0; i < vars.length; i += 2) {\n const len = Number(vars[i]);\n const numbers = vars[i + 1].split(' ').map(Number);\n\n console.log(proccessLine(len, numbers));\n }\n});\n"}, {"source_code": "/* eslint-disable no-continue */\n/* eslint-disable no-param-reassign */\nconst readline = require('readline').createInterface({\n input: process.stdin,\n});\n\nconst lines = [];\n\nreadline.on('line', (line) => {\n if (lines.length === 0) {\n lines.push(Number(line));\n } else {\n lines.push(line);\n }\n});\n\nconst proccessLine = (len, arr) => {\n let count = 0;\n const rests = {\n 1: 0,\n 2: 0,\n };\n\n for (let i = 0; i < len; i += 1) {\n const v = arr[i];\n const rest = v % 3;\n if (rest === 0) {\n count += 1;\n continue;\n }\n\n rests[rest] += 1;\n }\n\n const minTogether = Math.min(...Object.values(rests));\n\n const restOne = Math.floor(rests[1] / 3);\n rests[1] -= restOne * 3;\n const restTwo = Math.floor(rests[2] / 3);\n rests[2] -= restTwo * 3;\n\n const minRest = restOne + restTwo + Math.min(...Object.values(rests));\n\n return count + (minTogether > minRest ? minTogether : minRest);\n};\n\nreadline.on('close', () => {\n const [_, ...vars] = lines;\n\n for (let i = 0; i < vars.length; i += 2) {\n const len = Number(vars[i]);\n const numbers = vars[i + 1].split(' ').map(Number);\n\n console.log(proccessLine(len, numbers));\n }\n});\n"}, {"source_code": "/* eslint-disable no-continue */\n/* eslint-disable no-param-reassign */\nconst readline = require('readline').createInterface({\n input: process.stdin,\n});\n\nconst lines = [];\n\nreadline.on('line', (line) => {\n if (lines.length === 0) {\n lines.push(Number(line));\n } else {\n lines.push(line);\n }\n});\n\nconst proccessLine = (len, arr) => {\n let count = 0;\n const rests = {\n 1: 0,\n 2: 0,\n };\n\n for (let i = 0; i < len; i += 1) {\n const v = arr[i];\n const rest = v % 3;\n if (rest === 0) {\n count += 1;\n continue;\n }\n\n rests[rest] += 1;\n }\n\n const restCopy = { ...rests };\n let minTogether = Math.min(...Object.values(restCopy));\n const togetherOne = Math.max(Math.floor((restCopy[1] - minTogether * 3) / 3), 0);\n const togetherTwo = Math.max(Math.floor((restCopy[2] - minTogether * 3) / 3), 0);\n\n minTogether += togetherOne + togetherTwo;\n\n const restOne = Math.floor(rests[1] / 3);\n rests[1] -= restOne * 3;\n const restTwo = Math.floor(rests[2] / 3);\n rests[2] -= restTwo * 3;\n\n const minRest = restOne + restTwo + Math.min(...Object.values(rests));\n\n return count + (minTogether > minRest ? minTogether : minRest);\n};\n\nreadline.on('close', () => {\n const [_, ...vars] = lines;\n\n for (let i = 0; i < vars.length; i += 2) {\n const len = Number(vars[i]);\n const numbers = vars[i + 1].split(' ').map(Number);\n\n console.log(proccessLine(len, numbers));\n }\n});\n"}], "src_uid": "e59cddb6c941b1d7556ee9c020701007"} {"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$$$) — 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$$$) — 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$$$) — 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 — 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": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nfunction shuffle(array) {\r\n\tlet currentIndex = array.length, randomIndex;\r\n\r\n\t// While there remain elements to shuffle...\r\n\twhile (currentIndex != 0) {\r\n\r\n\t\t// Pick a remaining element...\r\n\t\trandomIndex = Math.floor(Math.random() * currentIndex);\r\n\t\tcurrentIndex--;\r\n\r\n\t\t// And swap it with the current element.\r\n\t\t[array[currentIndex], array[randomIndex]] = [\r\n\t\t\tarray[randomIndex], array[currentIndex]];\r\n\t}\r\n\r\n\treturn array;\r\n}\r\n\r\nconst M = 5;\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst r = [];\r\n\t\tfor (let i = 0; i < n; i++) r[i] = rna();\r\n\r\n\t\tconst ord = [];\r\n\t\tfor (let i = 0; i < n; i++) ord[i] = i;\r\n\r\n\t\tshuffle(ord);\r\n\t\tlet w = -1;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tlet works = 1;\r\n\t\t\tfor (let j = 0; j < n && works; j++) {\r\n\t\t\t\tlet cnt = 0;\r\n\t\t\t\tfor (let k = 0; k < M; k++) cnt += r[ord[i]][k] <= r[ord[j]][k];\r\n\t\t\t\tif (cnt < 3) works = 0;\r\n\t\t\t}\r\n\t\t\tif (works) { w = ord[i] + 1; break; }\r\n\t\t}\r\n\r\n\t\tconsole.log(w);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "var stdin_input = \"\";\r\nvar stdin_input_itr;\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { stdin_input_itr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => stdin_input_itr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nvar deb; const log = msg => (typeof deb != \"undefined\") && console.log(\"DEBUG\", msg);\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\r\n\t\tconst r = [];\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tr[i] = rna();\r\n\t\t}\r\n\r\n\t\tlet w = 0;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tlet cnt = 0;\r\n\t\t\tfor (let j = 0; j < 5; j++) cnt += r[w][j] <= r[i][j];\r\n\t\t\tif (cnt < 3) w = i;\r\n\t\t}\r\n\r\n\t\tlet ok = 1;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tlet cnt = 0;\r\n\t\t\tfor (let j = 0; j < 5; j++) cnt += r[w][j] <= r[i][j];\r\n\t\t\tif (cnt < 3) ok = 0;\r\n\t\t}\r\n\r\n\t\tconsole.log(ok ? w + 1 : -1);\r\n\t}\r\n}\r\n\r\n"}], "negative_code": [], "src_uid": "8d9fc054fb1541b70991661592ae70b1"} {"nl": {"description": " For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it! Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.For completing the chamber Wheatley needs $$$n$$$ cubes. $$$i$$$-th cube has a volume $$$a_i$$$.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $$$i>1$$$, $$$a_{i-1} \\le a_i$$$ must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $$$i>1$$$ you can exchange cubes on positions $$$i-1$$$ and $$$i$$$.But there is a problem: Wheatley is very impatient. If Wheatley needs more than $$$\\frac{n \\cdot (n-1)}{2}-1$$$ exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions?", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \\le t \\le 1000$$$), 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 5 \\cdot 10^4$$$) — number of cubes. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$) — volumes of cubes. 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 word in a single line: \"YES\" (without quotation marks) if the cubes can be sorted and \"NO\" (without quotation marks) otherwise.", "sample_inputs": ["3\n5\n5 3 2 1 4\n6\n2 2 2 2 2 2\n2\n2 1"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteIn the first test case it is possible to sort all the cubes in $$$7$$$ exchanges.In the second test case the cubes are already sorted.In the third test case we can make $$$0$$$ exchanges, but the cubes are not sorted yet, so the answer is \"NO\"."}, "positive_code": [{"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\nfunction highestOneBit(i) {\n i |= i >> 1;\n i |= i >> 2;\n i |= i >> 4;\n i |= i >> 8;\n i |= i >> 16;\n return i - (i >>> 1);\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n let arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n let ok = false;\n\n for (let i = 0; i < len - 1; i++) {\n if (arr[i] <= arr[i + 1]) {\n console.log(\"YES\");\n ok = true;\n break;\n }\n }\n\n if (!ok) console.log(\"NO\");\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error('\\n↑入力 ↓出力');\n Main();\n});\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var N = nextInt();\n var list = nextIntArray();\n var isOK = false;\n for(var j = 0; j < N - 1; j++){\n if(list[j] <= list[j + 1]){\n isOK = true;\n }\n }\n output[i] = (isOK) ? \"YES\" : \"NO\";\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "let input = '';\nlet inputResolve;\nlet inputPromise = new Promise(resolve => inputResolve = resolve);\nprocess.stdin.on('data', c => input += c);\nprocess.stdin.on('end', () => inputResolve());\n\nfunction For(a, b, fn) {\n let res;\n if (a < b) {\n for (let i = a; i <= b; i++) {\n if ((res = fn(i)) !== undefined) return res;\n }\n } else {\n for (let i = a; i >= b; i--) {\n if ((res = fn(i)) !== undefined) return res;\n }\n }\n}\n\nfunction Arr(a, b, fn, prev) {\n let p = prev || 0;\n if (a < b) return Array(b - a + 1).fill(0).map((v, i) => fn ? (p = fn(a + i, p)) : a + i);\n return Array(a - b + 1).fill(0).map((v, i) => fn ? (p = fn(a - i, p)) : a - i);\n}\n\nObject.defineProperty(Object.prototype, '$k', {\n value: function () { return Object.keys(this) }\n});\nObject.defineProperty(Object.prototype, '$v', {\n value: function () { return Object.values(this) }\n});\nObject.defineProperty(Object.prototype, '$kv', {\n value: function () { return Object.entries(this) }\n});\nArray.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }\nArray.prototype.uniq = function (fn) {\n var set = new Set();\n return this.filter(v => {\n var newValue = !set.has(fn ? fn(v) : v);\n set.add(fn ? fn(v) : v);\n return newValue;\n });\n}\nArray.prototype.toObj = function (fn) {\n return this.map(v => fn(v)).reduce((p, v) => {\n p[v[0]] = v[1];\n return p;\n }, {})\n}\nArray.prototype.min = function (fn) {\n let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);\n return [this[i], i, min];\n}\nArray.prototype.max = function (fn) {\n let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));\n let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);\n return [this[i], i, max];\n}\n\nfunction gcd(a, b) {\n if (!b) return a;\n return gcd(b, a % b);\n}\nfunction mod(a, n, m) {\n if (n == 0n) return 1n;\n if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);\n return a * mod(a, n - 1n, m) % m;\n}\nfunction extendedEuclid(a, b) {\n if (!b) return [1, 0];\n else {\n let [x, y] = extendedEuclid(b, a % b);\n return [y, x - (a / b | 0) * y];\n }\n}\n// [m] = extendedEuclid(a, 998244353);\n\n(async () => {\n await inputPromise;\n let inp = input.split(/\\s+/).map(v => +v); r = 0;\n let t = inp[r++];\n while (t--) {\n let n = inp[r++];\n let a = inp.slice(r, r = r + n);\n console.log(For(0, n - 2, i => a[i] <= a[i + 1] ? 1 : undefined) ? 'YES' : 'NO')\n }\n})();"}, {"source_code": "var t = parseInt(readline());\nwhile(t--){\n var n = parseInt(readline());\n var list = readline().split(\" \").map(Number);\n var ok = true;\n for(var i=0;i {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\n\n// utils\nconst MOD = 1e9 + 7;\nconst mod = (n) => ((n % MOD) + MOD) % MOD;\nconst add = (a, b) => mod(mod(a) + mod(b));\nconst sub = (a, b) => mod(mod(a) - mod(b));\nfunction mul() {\n for (var a = arguments, r = a[0], i = a.length; --i; )\n r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;\n return r;\n}\nfunction inv(b) {\n for (var a = MOD, u = 0, v = 1, t; b; v = t)\n (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);\n u %= MOD;\n return u < 0 ? u + MOD : u;\n}\nfunction pow(base, n) {\n if (n === 0) return 1;\n let p = pow(base, Math.floor(n / 2));\n let res = mul(mod(p), mod(p));\n if (n % 2 === 1) res = mul(mod(res), base);\n return res;\n}\n\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n let arr = readLine()\n .split(\" \")\n .map((n) => parseInt(n));\n\n const str = arr.join(\"\");\n arr.sort((a, b) => b - a);\n\n const str2 = arr.join(\"\");\n\n if (str === str2 && arr[0] !== arr[len - 1]) console.log(\"NO\");\n else console.log(\"YES\");\n }\n}\n"}, {"source_code": "var t = parseInt(readline());\nwhile(t--){\n var n = parseInt(readline());\n var input = readline();\n var arr = input.split(' ').map(Number);\n var ok = true;\n if(ok==true){\n print(\"NO\\n\");\n }else print(\"YES\\n\");\n}"}, {"source_code": "var t = parseInt(readline());\nwhile(t--){\n var n = parseInt(readline());\n var list = readline().split(\" \").map(Number);\n for(var i=0;i BobActions.R) {\n for (var j = 0; j < AliceActions.P - BobActions.R; j++) {\n freeActions.push(\"P\");\n }\n }\n\n if (AliceActions.R > BobActions.S) {\n for (var j = 0; j < AliceActions.R - BobActions.S; j++) {\n freeActions.push(\"R\");\n }\n }\n\n if (AliceActions.S > BobActions.P) {\n for (var j = 0; j < AliceActions.S - BobActions.P; j++) {\n freeActions.push(\"S\");\n }\n }\n\n for (var j = 0; j < rounds; j++) {\n switch (BobActionsString[j]) {\n case \"R\":\n if (AliceActions.P) {\n resultString += \"P\";\n AliceActions.P--;\n } else {\n resultString += freeActions.pop();\n }\n break;\n case \"P\":\n if (AliceActions.S) {\n resultString += \"S\";\n AliceActions.S--;\n } else {\n resultString += freeActions.pop();\n }\n break;\n case \"S\":\n if (AliceActions.R) {\n resultString += \"R\";\n AliceActions.R--;\n } else {\n resultString += freeActions.pop();\n }\n break;\n }\n }\n print(resultString);\n }\n }"}], "negative_code": [], "src_uid": "bee33afb70e4c3e062ec7980b44cc0dd"} {"nl": {"description": "Alice and Bob are playing a game on an array $$$a$$$ of $$$n$$$ positive integers. Alice and Bob make alternating moves with Alice going first.In his/her turn, the player makes the following move: If $$$a_1 = 0$$$, the player loses the game, otherwise: Player chooses some $$$i$$$ with $$$2\\le i \\le n$$$. Then player decreases the value of $$$a_1$$$ by $$$1$$$ and swaps $$$a_1$$$ with $$$a_i$$$. Determine the winner of the game if both players play optimally.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 2 \\cdot 10^4)$$$  — 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 10^5)$$$  — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \\ldots a_n$$$ $$$(1 \\leq a_i \\leq 10^9)$$$  — the elements of the array $$$a$$$. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, if Alice will win the game, output \"Alice\". Otherwise, output \"Bob\". You can output each letter in any case. For example, \"alIcE\", \"Alice\", \"alice\" will all be considered identical.", "sample_inputs": ["3\n\n2\n\n1 1\n\n2\n\n2 1\n\n3\n\n5 4 4"], "sample_outputs": ["Bob\nAlice\nAlice"], "notes": "NoteIn the first testcase, in her turn, Alice can only choose $$$i = 2$$$, making the array equal $$$[1, 0]$$$. Then Bob, in his turn, will also choose $$$i = 2$$$ and make the array equal $$$[0, 0]$$$. As $$$a_1 = 0$$$, Alice loses.In the second testcase, once again, players can only choose $$$i = 2$$$. Then the array will change as follows: $$$[2, 1] \\to [1, 1] \\to [1, 0] \\to [0, 0]$$$, and Bob loses.In the third testcase, we can show that Alice has a winning strategy."}, "positive_code": [{"source_code": "const readline = require('readline')\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nconst lines = []\r\nrl.on('line', (input) => {\r\n lines.push(input);\r\n})\r\nrl.on('close', () => {\r\n// (function() {\r\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\r\n let l = 0;\r\n let t = +lines[l++]\r\n const output = []\r\n for (let i = 0; i < t; i++) {\r\n const n = +lines[l++]\r\n const arr = lines[l++].trim().split(' ').map(Number)\r\n output[i] = solve(n, arr) ? 'Alice' : 'Bob'\r\n }\r\n console.log(output.join('\\n'))\r\n// })()\r\n})\r\n\r\nfunction solve(n, arr) {\r\n const min = Math.min(...arr)\r\n if (arr[0] === min) {\r\n return false\r\n } else {\r\n return true\r\n }\r\n}\r\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n for(i = 1; i <= t * 2; i++){\n if(i % 2 == 1){\n n = lines[i];\n }else{\n var a = lines[i].split(' ').map(Number);\n var f = a[0];\n a.sort(function(a, b){return a - b});\n console.log(a[0] == f ? 'Bob' : 'Alice');\n }\n }\n});"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n \r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n \r\nvar T = readline();\r\nvar inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n\tvar n = readline();\r\n\tvar a = readline().split(\" \").map(w => parseInt(w));\r\n\tvar minn = inf;\r\n\tfor(var i=0;i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\nfunction print(str) {\r\n console.log(str);\r\n}\r\n\r\n// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');\r\n// main();\r\n// testOutput();\r\n\r\nfunction begin(n, nums) {\r\n let min = Number.MAX_SAFE_INTEGER;\r\n let minIndex = 0;\r\n for(let i = 0; i < nums.length; i++) {\r\n if(min > nums[i]) {\r\n min = nums[i];\r\n minIndex = i;\r\n }\r\n }\r\n if(minIndex > 0) {\r\n print(\"Alice\");\r\n } else {\r\n print(\"Bob\");\r\n }\r\n}\r\n\r\nfunction main() {\r\n var caseNum = parseInt(readline(), 10);\r\n for (var i = 0; i < caseNum; i++) {\r\n var n = parseInt(readline(), 10);\r\n var x = readline()\r\n .trim()\r\n .split(' ')\r\n .map((y) => parseInt(y, 10));\r\n begin(n, x);\r\n }\r\n}"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns();\r\n if (a[0] === 1) return 'Bob';\r\n for (let i = 1; i < n; i++) {\r\n if (a[i] < a[0]) return 'Alice';\r\n }\r\n return 'Bob';\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = () => read().split(/\\s+/).map(Number);\r\n const re = () => read().split(/\\s+/).map(s => Number(s) - 1);\r\n const rbs = () => read().split(/\\s+/).map(BigInt);\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n try {\r\n let t = Number(r());\r\n let res = new Array(t);\r\n let limit = 0;\r\n for (let i = 0; i < t; i++) {\r\n let s = solve(r);\r\n if (s === undefined) s = '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\r?\\n/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\n// your code goes here\r\n\r\n\r\n// declare global variables\r\nvar input_stdin = \"\";\r\nvar lines = \"\";\r\nvar input_currentline = 0;\r\n\r\n// standard input is stored into input_stdin\r\nprocess.stdin.on('data', function (data) {\r\n input_stdin += data;\r\n});\r\n\r\n// standard input is done and stored into an array\r\nprocess.stdin.on('end', function () {\r\n lines = input_stdin.split(\"\\n\");\r\n start();\r\n});\r\n\r\n\r\nfunction start() {\r\n const T = parseInt(lines[0])\r\n let line = 1\r\n for (let t = 1; t <= T; t++) {\r\n const n = parseInt(lines[line++].split(' ')[0], 10)\r\n const a = lines[line++].split(' ').map(x => parseInt(x, 10))\r\n let min = a[1];\r\n for(let i = 1; i < a.length; i++) {\r\n if (min > a[i])\r\n min = a[i]\r\n }\r\n if (a[0] > min) console.log('Alice')\r\n else console.log('Bob')\r\n }\r\n}"}], "negative_code": [{"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, arr) ? 'Alice' : 'Bob'\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, arr) {\n const min = Math.min(...arr)\n if (min === 1) {\n return arr[0] !== 1\n }\n const sum = arr.reduce((s, x) => s + x, 0)\n return (sum - 2 * n) & 1\n}\n"}], "src_uid": "4c5187193cf7f2d2721cedbb15b2a1c3"} {"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 ≤ n, m ≤ 100) — 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 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) 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 — 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": "var input = readline().split(\" \"), n = +input[0], m = +input[1], a = [], win1 = [], store = {}, winners = [];\nfor(i = 0; i < m; i++){\n\ta.push(readline().split(\" \"));\n}\n\na.forEach(function(v){\n\tvar sorted = v.concat().sort(function(x,y){return y-x});\n\tvar canNumber = v.indexOf(sorted[0]);\n\twin1.push(canNumber);\n});\n\nfor (var i = 0; i < win1.length; i++) {\n var key = win1[i];\n store[key] = key;\n}\n\nfor(i = 0; i < n; i++){\n\twinners[i] = 0;\n}\n\nfor(key in store){\n\tfor(i = 0; i < m; i++){\n\t\tif(win1[i] == key){\n\t\t\twinners[key]++;\n\t\t}\n\t}\n}\n\nwinnerss = winners.concat().sort(function(x,y){return y-x});\n\nwrite(winners.indexOf(winnerss[0]) + 1);"}, {"source_code": "'use strict';\nlet _in = readline().split(/\\s+/).map((s) => parseInt(s, 10));\nlet n = _in[0], m = _in[1];\nlet a = [];\nfor (let i = 0; i < m; i++) {\n a.push(readline().split(/\\s+/).map((s) => parseInt(s, 10)));\n}\nlet f = (acc, _, i, v) => (v[acc] < v[i]) ? i : acc;\na = a.map((v) => v.reduce(f, 0));\nlet ct = new Array(n).fill(0);\nfor (let i = 0; i < m; i++) {\n ct[a[i]]++;\n}\nprint(ct.reduce(f, 0) + 1);\n\n"}, {"source_code": "var data = readline().split(' ');\nvar candidates = parseInt(data[0]);\nvar cities = parseInt(data[1]);\nvar result_cities = [];\n\nfor (var i = 0; i < cities; i++) {\n var data = readline().split(' ');\n var result = 0;\n for (var x = 0; x < candidates; x++) {\n var temp_result = parseInt(data[x]+1);\n if(result candidate_list[result-1]) {\n result = i+1;\n }\n}\n\nwrite(result);"}, {"source_code": "(function() {\n \"use strict\";\n var arr = readline().split(\" \").map(function(x) { \n return parseInt(x);\n });\n var can = arr[0], cit = arr[1], mat = [];\n var canind = [], maxvotes = [];\n for(var i = 0; i < cit; i++)\n {\n mat[i] = readline().split(\" \").map(function(x) {\n return parseInt(x); \n });\n \n maxvotes[i] = mat[i][0];\n canind[i] = 0;\n for(var j = 0; j < can; j++)\n {\n if(mat[i][j] > maxvotes[i])\n {\n maxvotes[i] = mat[i][j];\n canind[i] = j;\n }\n }\n }\n \n var Tarek = [];\n for(var i = 0; i < can; i++)\n {\n Tarek[i] = 0;\n }\n \n for(var i = 0; i < cit; i++)\n {\n Tarek[canind[i]]++;\n }\n \n var fin_max = 0, fin_ind = 0;\n for(var i = 0; i < Tarek.length; i++)\n {\n if(Tarek[i] > fin_max)\n {\n fin_max = Tarek[i];\n fin_ind = i;\n }\n }\n \n print(fin_ind + 1);\n})();"}, {"source_code": "var arr = [];\nvar numberCitiesCandidates = readline();\nnumberCitiesCandidates = numberCitiesCandidates.split(' ');\nvar cities = numberCitiesCandidates[1];\nvar candidates = numberCitiesCandidates[0];\n\nfor (var i = 0; i < cities; i++) {\n var line = readline();\n if (!line) {\n break;\n }\n var lineChars = line.split(' ');\n for (var j = 0; j < candidates; j++) {\n if (!arr[i]) {\n arr[i] = [];\n }\n arr[i][j] = lineChars[j];\n }\n}\n\nvar filteration = [];\nfor (var i = 0; i < arr.length; i++) {\n var maxCanditate = {\n index: 0,\n value: Number(arr[i][0])\n };\n for (var j = 1; j < arr[i].length; j++) {\n var currVotes = Number(arr[i][j]);\n if (maxCanditate.value < currVotes) {\n maxCanditate = {\n index: j,\n value: arr[i][j]\n };\n }\n }\n\n filteration.push(maxCanditate);\n}\nvar citiesStatistics = {};\nfilteration.map(function(a) {\n if (a.index in citiesStatistics) {\n citiesStatistics[a.index]++;\n } else {\n citiesStatistics[a.index] = 1;\n }\n});\nvar winner;\nfor (var canditateIndex in citiesStatistics) {\n var canditateIndexNum = Number(canditateIndex);\n if (!winner) {\n winner = {\n index: canditateIndexNum,\n cities: citiesStatistics[canditateIndex]\n };\n } else {\n if ((winner.cities < citiesStatistics[canditateIndex]) || (winner.cities == citiesStatistics[canditateIndex] && winner.index > canditateIndexNum)) {\n winner = {\n index: canditateIndexNum,\n cities: citiesStatistics[canditateIndex]\n };\n }\n }\n}\n\nprint(winner.index + 1);\n"}, {"source_code": "var firstInput = readline().split(' ');\nvar nCandidates = parseInt(firstInput[0]);\nvar nCities = parseInt(firstInput[1]);\nvar citiesWonByCandidates = [];\nvar i, j, highestVotePerCity, currentVote, winnerPerCityIdx, votesPerCity;\nfor (i = 0; i < nCities; i++) {\n\tvotesPerCity = readline().split(' ');\n\thighestVotePerCity = -1;\n\tfor (j = 0; j < nCandidates; j++) {\n\t\tcurrentVote = parseInt(votesPerCity[j]);\n\t\tif (currentVote > highestVotePerCity) {\n\t\t\twinnerPerCityIdx = j;\n\t\t\thighestVotePerCity = currentVote;\n\t\t}\n\t}\n\tif (citiesWonByCandidates[winnerPerCityIdx] == null) {\n\t\tcitiesWonByCandidates[winnerPerCityIdx] = 1;\n\t} else {\n\t\tcitiesWonByCandidates[winnerPerCityIdx] += 1;\n\t}\n}\nvar highestVote = -1, winner = 1;\nfor (i = 0; i < citiesWonByCandidates.length; i++) {\n\tif (citiesWonByCandidates[i] > highestVote) {\n\t\twinner = i+1;\n\t\thighestVote = citiesWonByCandidates[i];\n\t}\n}\nprint(winner);"}, {"source_code": "nm = readline().split(' ').map(Number);\n\nvar n = nm[0];\nvar m = nm[1];\n\nvar arr = [];\n\nfor (var i = 0; i < m; i++) {\n\tstr = readline().split(' ').map(Number);\n\n\tvar max = 0;\n\tvar maxPos = 0;\n\n\tfor (var j = 0; j < n; j++) {\n\t\tif (str[j] > max) {\n\t\t\tmax = str[j];\n\t\t\tmaxPos = j;\n\t\t};\n\t};\n\n\tarr.push(maxPos + 1);\n};\n\nfor (var j = 0; j < m - 1; j++) {\n\tfor (var k = j + 1; k < m; k++) {\n\t\tif (arr[j] > arr[k]) {\n\t\t\tvar temp = arr[j];\n\t\t\tarr[j] = arr[k];\n\t\t\tarr[k] = temp;\n\t\t};\n\t};\n};\n\nvar maxCount = 0;\nvar res = 0;\n\nfor (var k = 0; k < m; k++) {\n\tvar count = 0;\n\n\tfor (var l = 0; l < m; l++) {\n\t\tif (arr[k] == arr[l]) {\n\t\t\tcount++;\n\t\t};\n\t};\n\n\tif (count > maxCount) {\n\t\tmaxCount = count;\n\t\tres = arr[k];\n\t};\n};\n\nprint(res);\n\n"}], "negative_code": [{"source_code": "'use strict';\nlet _in = readline().split(/\\s+/).map((s) => parseInt(s, 10));\nlet n = _in[0], m = _in[1];\nlet a = [];\nfor (let i = 0; i < n; i++) {\n a.push(readline().split().map(parseInt));\n}\nlet f = (acc, _, i, v) => v[acc] < v[i] ? i : acc;\na.map((v) => v.reduce(f, 0));\nlet ct = new Array(m).fill(0);\nfor (let i = 0; i < m; i++) {\n ct[a[i]]++;\n}\nprint(ct.reduce(f, 0) + 1);\n\n"}, {"source_code": "'use strict';\nlet _in = readline().split(/\\s+/).map((s) => parseInt(s, 10));\nlet m = _in[0], n = _in[1];\nlet a = [];\nfor (let i = 0; i < n; i++) {\n a.push(readline().split().map(parseInt));\n}\nlet f = (acc, _, i, v) => v[acc] < v[i] ? i : acc;\na.map((v) => v.reduce(f, 0));\nlet ct = new Array(m).fill(0);\nfor (let i = 0; i < m; i++) {\n ct[a[i]]++;\n}\nprint(ct.reduce(f, 0) + 1);\n\n"}, {"source_code": "'use strict';\nlet _in = readline().split(/\\s+/).map((s) => parseInt(s, 10));\nlet n = _in[0], m = _in[1];\nlet a = [];\nfor (let i = 0; i < m; i++) {\n a.push(readline().split(/\\s+/).map((s) => parseInt(s, 10)));\n}\nlet f = (acc, _, i, v) => (v[acc] < v[i]) ? i : acc;\na = a.map((v) => v.reduce(f, 0));\nlet ct = new Array(m).fill(0);\nfor (let i = 0; i < m; i++) {\n ct[a[i]]++;\n}\nprint(ct.reduce(f, 0) + 1);\n\n"}, {"source_code": "var data = readline().split(' ');\nvar candidates = parseInt(data[0]);\nvar cities = parseInt(data[1]);\nvar result_cities = [];\n\nfor (var i = 0; i < cities; i++) {\n var data = readline().split(' ');\n var result = 0;\n for (var x = 0; x < candidates; x++) {\n var temp_result = parseInt(data[x]);\n if(result candidate_list[result-1]) {\n result = i+1;\n }\n}\n\nwrite(result);"}, {"source_code": "var data = readline().split(' ');\nvar candidates = parseInt(data[0]);\nvar cities = parseInt(data[1]);\nvar result_cities = [];\n\nfor (var i = 0; i < cities; i++) {\n var data = readline().split(' ');\n var result = 0;\n for (var x = 0; x < candidates; x++) {\n var temp_result = parseInt(data[x]);\n if(result candidate_list[result-1]) {\n result = i+1;\n }\n}\n\nwrite(result);"}, {"source_code": "(function () {\n \"use strict\";\n var arr = readline().split(\" \").map(function (x) {\n return parseInt(x, 10);\n }), can = arr[0], cit = arr[1], mat = [], maxi = [], index = [];\n for (var i = 0; i < cit; i++) {\n mat[i] = readline().split(\" \").map(function(z) {\n return parseInt(z);\n });\n maxi[i] = 0;\n index[i] = null;\n for(var j = can - 1; j >= 0; j--) {\n if(mat[i][j] >= maxi[i]) {\n maxi[i] = mat[i][j];\n index[i] = j;\n }\n }\n }\n \n var maxcan = [];\n \n for(i = 0; i < cit; i++) {\n maxcan[i] = 0;\n }\n\n for(i = 0; i < cit; i++) {\n maxcan[index[i]]++; \n }\n \n var maxnum = maxcan[0], maxindex = 0;\n for(i = can - 1; i >= 0; i--) {\n if(maxcan[i] >= maxnum) {\n maxnum = maxcan[i];\n maxindex = i;\n }\n }\n \n print(maxindex+1);\n \n})();"}, {"source_code": "(function () {\n \"use strict\";\n var arr = readline().split(\" \").map(function (x) {\n return parseInt(x, 10);\n }), can = arr[0], cit = arr[1], mat = [],\n maxi = [], index = [], maxcan = [],\n maxnum = maxcan[0], maxindex = 0;\n for (var i = 0; i < cit; i++) {\n mat[i] = readline().split(\" \").map(function(z) {\n return parseInt(z);\n });\n maxi[i] = 0;\n index[i] = null;\n for(var j = can - 1; j >= 0; j--) {\n if(mat[i][j] >= maxi[i]) {\n maxi[i] = mat[i][j];\n index[i] = j;\n }\n }\n } \n for(i = 0; i < cit; i++) {\n maxcan[i] = 0;\n } \n for(i = 0; i < cit; i++) {\n maxcan[index[i]]++; \n } \n for(i = cit - 1; i >= 0; i--) {\n if(maxcan[i] >= maxnum) {\n maxnum = maxcan[i];\n maxindex = i;\n }\n } \n print(maxindex+1);\n})();"}, {"source_code": "var arr = [];\nvar numberCitiesCandidates = readline();\nnumberCitiesCandidates = numberCitiesCandidates.split(' ');\nvar cities = numberCitiesCandidates[1];\nvar candidates = numberCitiesCandidates[0];\n\nfor (var i = 0; i < cities; i++) {\n var line = readline();\n if (!line) {\n break;\n }\n var lineChars = line.split(' ');\n for (var j = 0; j < candidates; j++) {\n if (!arr[i]) {\n arr[i] = [];\n }\n arr[i][j] = lineChars[j];\n }\n}\n\nvar filteration = [];\nfor (var i = 0; i < arr.length; i++) {\n var maxCanditate = {\n index: 0,\n value: Number(arr[i][0])\n };\n for (var j = 1; j < arr[i].length; j++) {\n \tvar currVotes = Number(arr[i][j]);\n if (maxCanditate.value < currVotes) {\n maxCanditate = {\n index: j,\n value: arr[i][j]\n };\n }\n }\n if(filteration.length === 0 || (filteration.length !== 0 && maxCanditate.value !== 0))\n \tfilteration.push(maxCanditate);\n}\nvar citiesStatistics = {};\nfilteration.map(function(a) {\n if (a.index in citiesStatistics) {\n citiesStatistics[a.index]++;\n } else {\n citiesStatistics[a.index] = 1;\n }\n});\nvar winner;\nfor(var canditateIndex in citiesStatistics){\n\tvar canditateIndexNum = Number(canditateIndex);\n\tif(!winner){\n\t\twinner = {index: canditateIndexNum, cities: citiesStatistics[canditateIndex]};\n\t}else{\n\t\tif((winner.cities < citiesStatistics[canditateIndex]) || (winner.cities == citiesStatistics[canditateIndex] && winner.index > canditateIndexNum)){\n\t\t\twinner = {index: canditateIndexNum, cities: citiesStatistics[canditateIndex]};\n\t\t}\n\t}\n}\n\nprint(winner.index + 1);\n"}, {"source_code": "var arr = [];\nvar input = readline();\nprint(input);\nvar lines = input.split(\"\\n\");\nfor (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n var lineChars = line.split(' ');\n for (var j = 0; j < lineChars.length; j++) {\n if (!arr[i]) {\n arr[i] = [];\n }\n arr[i][j] = lineChars[j];\n }\n}\n"}, {"source_code": "var arr = [];\nfor (var i = 0; i < 100; i++) {\n var line = readline();\n if (!line) {\n break;\n }\n var lineChars = line.split(' ');\n for (var j = 0; j < lineChars.length; j++) {\n if (!arr[i]) {\n arr[i] = [];\n }\n arr[i][j] = lineChars[j];\n }\n}\nvar filteration = [];\nfor (var i = 0; i < arr.length; i++) {\n var maxCanditate = {\n index: 0,\n value: Number(arr[i][0])\n };\n for (var j = 1; j < arr[i].length; j++) {\n if (maxCanditate.value < Number(arr[i][j])) {\n maxCanditate = {\n index: j,\n value: arr[i][j]\n };\n }\n }\n filteration.push(maxCanditate);\n}\nvar citiesStatistics = {};\nfilteration.map(function(a) {\n if (a.index in citiesStatistics) {\n citiesStatistics[a.index]++;\n } else {\n citiesStatistics[a.index] = 1;\n }\n});\nvar winner;\nfor(var canditateIndex in citiesStatistics){\n\tvar canditateIndexNum = Number(canditateIndex);\n\tif(!winner){\n\t\twinner = {index: canditateIndexNum, cities: citiesStatistics[canditateIndex]};\n\t}else{\n\t\tif((winner.cities < citiesStatistics[canditateIndex]) || (winner.cities == citiesStatistics[canditateIndex] && winner.index > canditateIndexNum)){\n\t\t\twinner = {index: canditateIndexNum, cities: citiesStatistics[canditateIndex]};\n\t\t}\n\t}\n}\n\nprint(winner.index + 1);\n"}, {"source_code": "var firstInput = readline().split(' ');\nvar nCandidates = parseInt(firstInput[0]);\nvar nCities = parseInt(firstInput[1]);\nvar citiesWonByCandidates = [];\nvar i, j, highestVotePerCity, currentVote, winnerPerCityIdx, votesPerCity;\nfor (i = 0; i < nCities; i++) {\n votesPerCity = readline().split(' ');\n highestVotePerCity = 0;\n for (j = 0; j < nCandidates; j++) {\n currentVote = parseInt(votesPerCity[j]);\n if (currentVote > highestVotePerCity) {\n winnerPerCityIdx = j;\n highestVotePerCity = currentVote;\n }\n }\n if (citiesWonByCandidates[winnerPerCityIdx] == null) {\n citiesWonByCandidates[winnerPerCityIdx] = 1;\n } else {\n citiesWonByCandidates[winnerPerCityIdx] += 1;\n }\n}\nvar highestVote = 0, winner = 1;\nfor (i = 0; i < citiesWonByCandidates.length; i++) {\n if (citiesWonByCandidates[i] > highestVote) {\n winner = i+1;\n highestVote = citiesWonByCandidates[i];\n }\n}\nprint(winner);"}, {"source_code": "var firstInput = readline().split(' ');\nvar nCandidates = parseInt(firstInput[0]);\nvar nCities = parseInt(firstInput[1]);\nvar citiesWonByCandidates = [];\nvar i, j, highestVotePerCity, currentVote, winnerPerCityIdx, votesPerCity;\nfor (i = 0; i < nCities; i++) {\n\tvotesPerCity = readline().split(' ');\n\thighestVotePerCity = 0;\n\tfor (j = 0; j < nCandidates; j++) {\n\t\tcurrentVote = parseInt(votesPerCity[j]);\n\t\tif (currentVote > highestVotePerCity) {\n\t\t\twinnerPerCityIdx = j;\n\t\t\thighestVotePerCity = currentVote;\n\t\t}\n\t}\n\tif (citiesWonByCandidates[winnerPerCityIdx] == null) {\n\t\tcitiesWonByCandidates[winnerPerCityIdx] = 1;\n\t} else {\n\t\tcitiesWonByCandidates[winnerPerCityIdx] += 1;\n\t}\n}\nvar highestVote = 0, winner;\nfor (i = 0; i < citiesWonByCandidates.length; i++) {\n\tif (citiesWonByCandidates[i] > highestVote) {\n\t\twinner = i+1;\n\t\thighestVote = citiesWonByCandidates[i];\n\t}\n}\nprint(winner);"}], "src_uid": "b20e98f2ea0eb48f790dcc5dd39344d3"} {"nl": {"description": "When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types: transform lowercase letters to uppercase and vice versa; change letter «O» (uppercase latin letter) to digit «0» and vice versa; change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other. For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.", "input_spec": "The first line contains a non-empty string s consisting of lower and uppercase latin letters, digits and underline symbols («_») with length not exceeding 50  — the login itself. The second line contains a single integer n (1 ≤ n ≤ 1 000) — the number of existing logins. The next n lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.", "output_spec": "Print «Yes» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it. Otherwise print «No» (without quotes).", "sample_inputs": ["1_wat\n2\n2_wat\nwat_1", "000\n3\n00\nooA\noOo", "_i_\n3\n__i_\n_1_\nI", "La0\n3\n2a0\nLa1\n1a0", "abc\n1\naBc", "0Lil\n2\nLIL0\n0Ril"], "sample_outputs": ["Yes", "No", "No", "No", "No", "Yes"], "notes": "NoteIn the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.In the third sample case the new login is similar with the second one."}, "positive_code": [{"source_code": "//readline()\n//print()\n\nvar main = readline().trim().split(\"\").map(v => v.charCodeAt(0));\nvar n = +readline();\nvar done = true;\n\nfor(var i = 0; i < n; i++){\n var s = readline().trim();\n \n if(s.length === main.length){\n s = s.split(\"\").map(v => v.charCodeAt(0));\n \n var diffs = false;\n \n for(var j = 0; j < s.length; j++){\n if(s[j] !== main[j]){\n \n if(\n (s[j] === 48 && main[j] === 79) || \n (s[j] === 48 && main[j] === 111) || \n (s[j] === 79 && main[j] === 48) || \n (s[j] === 79 && main[j] === 111) || \n (s[j] === 111 && main[j] === 48) || \n (s[j] === 111 && main[j] === 79)\n ){\n diffs = true;\n } else\n \n if(\n (s[j] === 49 && main[j] === 105) ||\n (s[j] === 49 && main[j] === 73) ||\n (s[j] === 49 && main[j] === 108) ||\n (s[j] === 49 && main[j] === 76) ||\n \n (s[j] === 105 && main[j] === 49) ||\n (s[j] === 105 && main[j] === 73) ||\n (s[j] === 105 && main[j] === 108) ||\n (s[j] === 105 && main[j] === 76) ||\n \n (s[j] === 73 && main[j] === 49) ||\n (s[j] === 73 && main[j] === 105) ||\n (s[j] === 73 && main[j] === 108) ||\n (s[j] === 73 && main[j] === 76) ||\n \n (s[j] === 108 && main[j] === 49) ||\n (s[j] === 108 && main[j] === 105) ||\n (s[j] === 108 && main[j] === 73) ||\n (s[j] === 108 && main[j] === 76) ||\n \n (s[j] === 76 && main[j] === 49) ||\n (s[j] === 76 && main[j] === 105) ||\n (s[j] === 76 && main[j] === 73) ||\n (s[j] === 76 && main[j] === 108)\n \n ){\n diffs = true;\n } else \n \n if((s[j] >= 97 && s[j] <= 122 && s[j] - main[j] === 32) ||\n (s[j] >= 65 && s[j] <= 90 && main[j] - s[j] === 32)){\n diffs = true;\n } else {\n diffs = false;\n break;\n }\n \n }else{\n diffs = true;\n }\n }\n \n if(diffs){\n done = false;\n }\n }\n \n if(!done) break;\n}\n\nprint(done ? \"Yes\" : \"No\");"}, {"source_code": "var login = readline().toLowerCase();\nvar countLogins = +readline();\nvar logins = [];\nvar result = true;\n\nfor (var i = 0; i < countLogins; i++) {\n logins.push(readline().toLowerCase());\n}\n\n// Solution start\nfunction reformatLogin(login) {\n return login.replace(/o/gi, '0').replace(/l/gi, '1').replace(/i/gi, '1');\n}\n\nlogin = reformatLogin(login);\n\nfor (var i = 0; i < countLogins; i = i + 1) {\n var temp = reformatLogin(logins[i]);\n\n if (login === temp) {\n result = false;\n break;\n }\n}\n\nprint(result ? 'Yes' : 'No');"}, {"source_code": "\nvar input = function(){\n var userNick = normalize(readline());\n var n = parseInt(readline());\n var s = new Set();\n for(var i=0; i {\n for (var i = 0; i < existingCount; i++)\n if (newLogin === transformLogin(readline())) {\n print(\"No\");\n return;\n }\n print(\"Yes\");\n})();\n"}, {"source_code": "//Some debug stuff\nconst isDebugMode=false;\nvar log=()=>{}\nif(isDebugMode){\n var print=function (out) {\n console.log('COUT: '+ out);\n }\n log=function (out) {\n console.log('DEBUG OUTPUT: '+ out);\n }\n function* readline_generator() {\n var a=[\n 'La0',\n '3',\n '2a0',\n 'La1',\n '1a0'\n ];\n while(a.length>1){\n yield a.shift()\n }\n return a.shift();\n }\n var g=readline_generator();\n var readline=function () {\n return g.next().value;\n }\n}\n\n//SOLUTION\n\nvar compareS=function(s1, s2){\n if(s1.toLowerCase()==s2.toLowerCase()){\n return true;\n }\n switch(s1){\n case 'O':\n case '0':\n case 'o':\n if(['0', 'O', 'o'].indexOf(s2)>-1){\n return true;\n }\n break;\n case '1':\n case 'l':\n case 'I':\n case 'i':\n case 'L':\n if(['1', 'l', 'I', 'i', 'L'].indexOf(s2)>-1){\n return true;\n }\n break;\n }\n return false;\n};\n\nvar compare=function(a1, a2){\n var c=0;\n a1.forEach((i,k)=>{\n if(compareS(i, a2[k])){\n c++;\n }\n });\n return c==a1.length;\n};\n\nvar magic=function(s1, s2){\n s1=s1.split('');\n s2=s2.split('');\n var diff1=[];\n var diff2=[];\n s1.forEach((i,k)=>{\n if(i!=s2[k]){\n diff1.push(i);\n diff2.push(s2[k]);\n }\n })\n return compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\nvar f=0;\nwhile(counte.toLowerCase(e))\n db = db.map(e=>e.replace(/(i|l)/ig,'1'))\n db = db.map(e=>e.replace(/(o)/ig,'0'))\n return db\n}\nfunction upgradeLogin(lg){\n lg = lg.toLowerCase()\n lg = lg.replace(/(i|l)/ig,'1')\n lg = lg.replace(/o/ig,'0')\n return lg\n}\nfunction check2(l,db){\n let check = true\n for(let e of db){\n if(e == l){\n check = false\n } \n }\n if(check){\n return true\n } else{\n print('No')\n return false\n }\n}\nfunction checkLogin(login,dbsize,...db){\n db=db[0] \n if(check1(login)){\n db = upgradeDatabase(db)\n login = upgradeLogin(login)\n if(check2(login,db)){\n print('Yes')\n }\n }\n}\n\nlet inputs = getInputs()\ncheckLogin(inputs[0],inputs[1],inputs.slice(2))"}, {"source_code": "String.prototype.normalize = function() {\n var self = this;\n return self.toLowerCase().replace(/o/g, '0').replace(/[il]/g, 1);\n};\n\n\nvar potentialLogin = readline().normalize();\nvar existanceLoginCount = parseInt(readline());\nvar extstanceLogins = [];\nvar canLogIn = true;\nvar i = 0;\nwhile(i < existanceLoginCount) {\n var line = readline();\n if(canLogIn && potentialLogin === line.normalize()){\n canLogIn = false;\n }\n i++;\n}\n\nprint(canLogIn ? 'Yes' : 'No')"}], "negative_code": [{"source_code": "var main = readline().trim().split(\"\").map(v => v.charCodeAt(0));\nvar n = +readline();\nvar done = true;\n\nfor(var i = 0; i < n; i++){\n var s = readline().trim();\n \n if(s.length === main.length){\n s = s.split(\"\").map(v => v.charCodeAt(0));\n \n var diffs = false;\n \n for(var j = 0; j < s.length; j++){\n if(s[j] !== main[j]){\n \n if(\n (s[j] === 48 && main[j] === 79) || \n (s[j] === 48 && main[j] === 111) || \n (s[j] === 79 && main[j] === 48) || \n (s[j] === 79 && main[j] === 111) || \n (s[j] === 111 && main[j] === 48) || \n (s[j] === 111 && main[j] === 79)\n ){\n diffs = true;\n } else\n \n if(\n (s[j] === 49 && main[j] === 105) ||\n (s[j] === 49 && main[j] === 73) ||\n (s[j] === 49 && main[j] === 108) ||\n (s[j] === 49 && main[j] === 76) ||\n \n (s[j] === 105 && main[j] === 49) ||\n (s[j] === 105 && main[j] === 73) ||\n (s[j] === 105 && main[j] === 108) ||\n (s[j] === 105 && main[j] === 76) ||\n \n (s[j] === 73 && main[j] === 49) ||\n (s[j] === 73 && main[j] === 105) ||\n (s[j] === 73 && main[j] === 108) ||\n (s[j] === 73 && main[j] === 76) ||\n \n (s[j] === 108 && main[j] === 49) ||\n (s[j] === 108 && main[j] === 105) ||\n (s[j] === 108 && main[j] === 73) ||\n (s[j] === 108 && main[j] === 76) ||\n \n (s[j] === 76 && main[j] === 49) ||\n (s[j] === 76 && main[j] === 105) ||\n (s[j] === 76 && main[j] === 73) ||\n (s[j] === 76 && main[j] === 108)\n \n ){\n diffs = true;\n } else \n \n if((s[j] >= 97 && s[j] <= 122 && s[j] - main[j] === 32) ||\n (s[j] >= 65 && s[j] <= 90 && main[j] - s[j] === 32)){\n diffs = true;\n } else {\n diffs = false;\n break;\n }\n \n }\n }\n \n if(diffs){\n done = false;\n }\n }\n \n if(!done) break;\n}\n\nprint(done ? \"Yes\" : \"No\");"}, {"source_code": "var compareS=function(s1, s2){\n if(s1.toLowerCase()==s2.toLowerCase()){\n return true;\n }\n switch(s1){\n case 'O':\n case '0':\n case 'o':\n if(['0', 'O', 'o'].indexOf(s2)>-1){\n return true;\n }\n break;\n case '1':\n case 'l':\n case 'I':\n case 'i':\n if(['1', 'l', 'I', 'i'].indexOf(s2)>-1){\n return true;\n }\n break;\n }\n return false;\n};\n\nvar compare=function(a1, a2){\n var c=0;\n a1.forEach((i,k)=>{\n if(compareS(i, a2[k])){\n c++;\n }\n });\n return c==a1.length;\n};\n\nvar magic=function(s1, s2){\n s1=s1.split('');\n s2=s2.split('');\n var diff1=[];\n var diff2=[];\n s1.forEach((i,k)=>{\n if(i!=s2[k]){\n diff1.push(i);\n diff2.push(s2[k]);\n }\n})\n return compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\nvar f=0;\nwhile(count-1){\n return true;\n }\n break;\n case '1':\n case 'l':\n case 'I':\n if(['1', 'l', 'I'].indexOf(s2)>-1){\n return true;\n }\n break;\n }\n return false;\n};\n\nvar compare=function(a1, a2){\n var c=0;\n a1.forEach((i,k)=>{\n if(compareS(i, a2[k])){\n c++;\n }\n });\n return c==a1.length;\n};\n\nvar magic=function(s1, s2){\n s1=s1.split('');\n s2=s2.split('');\n var diff1=[];\n var diff2=[];\n s1.forEach((i,k)=>{\n if(i!=s2[k]){\n diff1.push(i);\n diff2.push(s2[k]);\n }\n})\n return compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\nvar f=0;\nwhile(count-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1':\n\t\tcase 'l':\n\t\tcase 'I':\n\t\t\tif(['1', 'l', 'I'].indexOf(s2)>-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn false;\n};\n\nvar compare=function(a1, a2){\n\tvar c=0;\n\ta1.forEach((i,k)=>{\n\t\tif(compareS(i, a2[k])){\n\t\t\tc++;\n\t\t}\n\t})\n\treturn c==a1.length;\n}\n\nvar magic=function(s1, s2){\n\ts1=s1.split('');\n\ts2=s2.split('');\n\tvar diff1=[];\n\tvar diff2=[];\n\ts1.forEach((i,k)=>{\n\t\tif(i!=s2[k]){\n\t\t\tdiff1.push(i);\n\t\t\tdiff2.push(s2[k]);\n\t\t}\n\t})\n\treturn compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\n\nwhile(count-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1':\n\t\tcase 'l':\n\t\tcase 'I':\n\t\t\tif(['1', 'l', 'I'].indexOf(s2)>-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn false;\n};\n\nvar compare=function(a1, a2){\n\tvar c=0;\n\ta1.forEach((i,k)=>{\n\t\tif(compareS(i, a2[k])){\n\t\t\tc++;\n\t\t}\n\t})\n\treturn c==a1.length;\n}\n\nvar magic=function(s1, s2){\n\ts1=s1.split('');\n\ts2=s2.split('');\n\tvar diff1=[];\n\tvar diff2=[];\n\ts1.forEach((i,k)=>{\n\t\tif(i!=s2[k]){\n\t\t\tdiff1.push(i);\n\t\t\tdiff2.push(s2[k]);\n\t\t}\n\t})\n\treturn compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\n\nwhile(count-1){\n return true;\n }\n break;\n case '1':\n case 'l':\n case 'I':\n if(['1', 'l', 'I'].indexOf(s2)>-1){\n return true;\n }\n break;\n }\n return false;\n};\n\nvar compare=function(a1, a2){\n var c=0;\n a1.forEach((i,k)=>{\n if(compareS(i, a2[k])){\n c++;\n }\n });\n return c==a1.length;\n};\n\nvar magic=function(s1, s2){\n s1=s1.split('');\n s2=s2.split('');\n var diff1=[];\n var diff2=[];\n s1.forEach((i,k)=>{\n if(i!=s2[k]){\n diff1.push(i);\n diff2.push(s2[k]);\n }\n})\n return compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\nvar f=0;\nwhile(count-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1':\n\t\tcase 'l':\n\t\tcase 'I':\n\t\t\tif(['1', 'l', 'I'].indexOf(s2)>-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn false;\n};\n\nvar compare=function(a1, a2){\n\tvar c=0;\n\ta1.forEach((i,k)=>{\n\t\tif(compareS(i, a2[k])){\n\t\t\tc++;\n\t\t}\n\t})\n\treturn c==a1.length;\n}\n\nvar magic=function(s1, s2){\n\ts1=s1.split('');\n\ts2=s2.split('');\n\tvar diff1=[];\n\tvar diff2=[];\n\ts1.forEach((i,k)=>{\n\t\tif(i!=s2[k]){\n\t\t\tdiff1.push(i);\n\t\t\tdiff2.push(s2[k]);\n\t\t}\n\t})\n\treturn compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\nvar f=0;\nwhile(count-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1':\n\t\tcase 'l':\n\t\tcase 'I':\n\t\t\tif(['1', 'l', 'I'].indexOf(s2)>-1){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn false;\n};\n\nvar compare=function(a1, a2){\n\tvar c=0;\n\ta1.forEach((i,k)=>{\n\t\tif(compareS(i, a2[k])){\n\t\t\tc++;\n\t\t}\n\t})\n\treturn c==a1.length;\n}\n\nvar magic=function(s1, s2){\n\ts1=s1.split('');\n\ts2=s2.split('');\n\tvar diff1=[];\n\tvar diff2=[];\n\ts1.forEach((i,k)=>{\n\t\tif(i!=s2[k]){\n\t\t\tdiff1.push(i);\n\t\t\tdiff2.push(s2[k]);\n\t\t}\n\t})\n\treturn compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\nvar f=0;\nwhile(count-1){\n return true;\n }\n break;\n case '1':\n case 'l':\n case 'I':\n case 'i':\n if(['1', 'l', 'I', 'i'].indexOf(s2)>-1){\n return true;\n }\n break;\n }\n return false;\n};\n\nvar compare=function(a1, a2){\n var c=0;\n a1.forEach((i,k)=>{\n if(compareS(i, a2[k])){\n c++;\n }\n });\n return c==a1.length;\n};\n\nvar magic=function(s1, s2){\n s1=s1.split('');\n s2=s2.split('');\n var diff1=[];\n var diff2=[];\n s1.forEach((i,k)=>{\n if(i!=s2[k]){\n diff1.push(i);\n diff2.push(s2[k]);\n }\n })\n return compare(diff1, diff2)\n}\n\n\n\nvar loginToTest=readline();\n\nvar numOfLogins=+(readline());\n\nvar count=0;\nvar f=0;\nwhile(count= 4) {\r\n var temp = [];\r\n var winner = -1;\r\n for (var i = 0; i < arr.length; i+=4) {\r\n winner = pit(i);\r\n if (winner == -1) {\r\n break;\r\n }\r\n temp.push(winner);\r\n }\r\n if (winner == -1) {\r\n break;\r\n }\r\n arr = temp;\r\n }\r\n var ans;\r\n if (arr.length == 2) {\r\n ans = pitTwo(arr[0], arr[1]);\r\n } else {\r\n ans = arr[0];\r\n }\r\n print('! ' + ans);\r\n }"}], "negative_code": [], "src_uid": "c9bc4fefa96b741843e54a8fb4b02877"} {"nl": {"description": "You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$3 \\le n \\le 3 \\cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.", "output_spec": "Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.", "sample_inputs": ["3\n121", "6\n000000", "6\n211200", "6\n120110"], "sample_outputs": ["021", "001122", "211200", "120120"], "notes": null}, "positive_code": [{"source_code": "var n = readline();\n\nvar str = readline().split('');\n\nvar div = n / 3;\n\nvar one, two, zero;\nvar div0 = div, div1 = div, div2 = div;\n\none = 0;\ntwo = 0;\nzero = 0;\n\nfor( var i=0; i div ) {\n two--;\n zero++;\n str[i] = '0';\n }\n }\n if( str[i] === '1' ) {\n if( one > div ) {\n one--;\n zero++;\n str[i] = '0';\n }\n }\n }\n}\n\nfor( var i=n-1; i>=0 && two < div; i-- ) {\n if( str[i] === '2' ) continue;\n else {\n \n if( str[i] === '1' ) {\n if( one > div ) {\n one--;\n str[i] = '2';\n two++;\n }\n }\n if( str[i] === '0' ) {\n if( zero > div ) {\n zero--;\n str[i] = '2';\n two++;\n }\n }\n }\n}\n\nif( one < div ) {\n if( zero > div ) {\n for( var i=n-1; i>=0 && one < div; i-- ) {\n if( str[i] === '1' ) continue;\n else {\n if( str[i] === '0' ) {\n if( zero > div ) {\n zero--;\n str[i] = '1';\n one++;\n }\n }\n\n }\n }\n }\n if( two > div ) {\n for( var i=0; i div ) {\n two--;\n str[i] = '1';\n one++;\n }\n }\n\n }\n }\n }\n}\n\n\nstr.forEach( i=> {\n write(i); \n});\n"}], "negative_code": [{"source_code": "var n = readline();\n\nvar str = readline().split('');\n\nvar div = n / 3;\n\nvar one, two, zero;\nvar div0 = div, div1 = div, div2 = div;\n\none = 0;\ntwo = 0;\nzero = 0;\n\nfor( var i=0; i div ) {\n two--;\n zero++;\n str[i] = '0';\n }\n }\n if( str[i] === '1' ) {\n if( one > div ) {\n one--;\n zero++;\n str[i] = '0';\n }\n }\n }\n}\n\nfor( var i=n-1; i>=0 && two < div; i-- ) {\n if( str[i] === '2' ) continue;\n else {\n \n if( str[i] === '1' ) {\n if( one > div ) {\n one--;\n str[i] = '2';\n two++;\n }\n }\n if( str[i] === '0' ) {\n if( zero > div ) {\n zero--;\n str[i] = '2';\n two++;\n }\n }\n }\n}\n\nfor( var i=n-1; i>=0 && one < div; i-- ) {\n if( str[i] === '1' ) continue;\n else {\n \n if( str[i] === '2' ) {\n if( two > div ) {\n two--;\n str[i] = '1';\n one++;\n }\n }\n if( str[i] === '0' ) {\n if( zero > div ) {\n zero--;\n str[i] = '1';\n one++;\n }\n }\n }\n}\n\nstr.forEach( i=> {\n write(i); \n});\n"}, {"source_code": "var n = readline();\n\nvar str = readline();\n\nvar div = n / 3;\n\nvar one, two, zero;\nvar div0 = div, div1 = div, div2 = div;\n\none = two = zero = 0;\n\nfor( var i=0; i 0 ) {\n div0--;\n write(0);\n } else {\n if( div1 > div2 ) {\n write(1);\n div1--;\n } else {\n write(2);\n div2--;\n }\n }\n }\n if( str.charAt(i) === '1') {\n if(div1 > 0 ) {\n div1--;\n write(1);\n } else {\n if( div0 > div2 ) {\n write(0);\n div0--;\n } else {\n write(2);\n div2--;\n }\n }\n }\n if( str.charAt(i) === '2') {\n if(div2 > 0 ) {\n div2--;\n write(2);\n } else {\n if( div1 > div0 ) {\n write(1);\n div1--;\n } else {\n write(0);\n div0--;\n }\n }\n }\n}\n\n"}, {"source_code": "var n = readline();\n\nvar str = readline().split('');\n\nvar div = n / 3;\n\nvar one, two, zero;\nvar div0 = div, div1 = div, div2 = div;\n\none = 0;\ntwo = 0;\nzero = 0;\n\nfor( var i=0; i div ) {\n two--;\n zero++;\n str[i] = '0';\n }\n }\n if( str[i] === '1' ) {\n if( one > div ) {\n one--;\n zero++;\n str[i] = '0';\n }\n }\n }\n}\n\nfor( var i=n-1; i>=0 && two < div; i-- ) {\n if( str[i] === '2' ) continue;\n else {\n \n if( str[i] === '1' ) {\n if( one > div ) {\n one--;\n str[i] = '2';\n two++;\n }\n }\n if( str[i] === '0' ) {\n if( zero > div ) {\n zero--;\n str[i] = '2';\n two++;\n }\n }\n }\n}\n\nfor( var i=n-1; i>=0 && one < div; i-- ) {\n if( str[i] === '1' ) continue;\n else {\n \n if( str[i] === '2' ) {\n if( two > div ) {\n two--;\n str[i] = '1';\n one++;\n }\n }\n if( str[i] === '0' ) {\n if( zero > div ) {\n zero--;\n str[i] = '1';\n one++;\n }\n }\n }\n}\n\nstr.forEach( i=> {\n write(i); \n});\n"}], "src_uid": "cb852bf0b62d72b3088969ede314f176"} {"nl": {"description": "At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $$$10$$$ is called a round number. For example, the numbers $$$10^0 = 1$$$, $$$10^1 = 10$$$, $$$10^2 = 100$$$ are round numbers, but $$$20$$$, $$$110$$$ and $$$256$$$ are not round numbers. So, if an item is worth $$$m$$$ bourles (the value of the item is not greater than $$$10^9$$$), the sellers want to change its value to the nearest round number that is not greater than $$$m$$$. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly $$$10^k$$$ bourles, where the value of $$$k$$$ — is the maximum possible ($$$k$$$ — any non-negative integer).For example, let the item have a value of $$$178$$$-bourles. Then the new price of the item will be $$$100$$$, and the answer will be $$$178-100=78$$$.", "input_spec": "The first line of input data contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases . Each test case is a string containing a single integer $$$m$$$ ($$$1 \\le m \\le 10^9$$$) — the price of the item.", "output_spec": "For each test case, output on a separate line a single integer $$$d$$$ ($$$0 \\le d < m$$$) such that if you reduce the cost of the item by $$$d$$$ bourles, the cost of the item will be the maximal possible round number. More formally: $$$m - d = 10^k$$$, where $$$k$$$ — the maximum possible non-negative integer.", "sample_inputs": ["7\n\n1\n\n2\n\n178\n\n20\n\n999999999\n\n9000\n\n987654321"], "sample_outputs": ["0\n1\n78\n10\n899999999\n8000\n887654321"], "notes": "NoteIn the example: $$$1 - 0 = 10^0$$$, $$$2 - 1 = 10^0$$$, $$$178 - 78 = 10^2$$$, $$$20 - 10 = 10^1$$$, $$$999999999 - 899999999 = 10^8$$$, $$$9000 - 8000 = 10^3$$$, $$$987654321 - 887654321 = 10^8$$$. Note that in each test case, we get the maximum possible round number."}, "positive_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n e = '1'\n for(l = 0; l < k.length - 1; l++){\n e += '0'\n }\n e = Number(e)\n \n if(b < 10){\n console.log(b-1)\n }else{\n \n console.log(k.join('')-e)\n\n }\n\n }\n \n\t \n}); "}, {"source_code": "// как меня заебала эта корявая платформа\r\n// https://stackoverflow.com/questions/20086849/how-to-read-from-stdin-line-by-line-in-node\r\n// // cat .\\input.txt | node .\\script.js\r\nconst state = { i: 0 }\r\nconst readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false\r\n});\r\nconst ten_exp = (exp = 0) => 10 ** exp\r\nrl.on('line', function (line) {\r\n if (state.i > 0) console.log((line - ten_exp(line.length - 1)).toString() + '\\r')\r\n state.i++\r\n})"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin\r\n});\r\n\r\nfunction getRound(m) {\r\n let s = 0\r\n let base = 10\r\n let t = 0\r\n while (t <= m) {\r\n s++;\r\n t = Math.pow(base,s)\r\n }\r\n return m - Math.pow(base,s - 1)\r\n}\r\nlet lines = [];\r\nrl.on('line', (line) => {\r\n lines.push(line);\r\n}).on('close', () => {\r\n const [n,...values] = lines\r\n for (let i = 0; i< n; i++) {\r\n const ans = getRound(values[i])\r\n console.log(ans)\r\n }\r\n});"}, {"source_code": "const fs = require(\"fs\");\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\n// console.log(input)\r\nvar T = readline();\r\n// var inf = 1000000000000;\r\nfor(var tc=1;tc<=T;tc++) {\r\n var n = readline()//.split(' ').map((x) => parseInt(x));\r\n // var a = readline().split(' ').map((x) => parseInt(x));\r\n var len = n.length;\r\n var val = Math.pow(10, len-1);\r\n // console.log(len, val)\r\n val = max(val, 0);\r\n // n -= 0;\r\n var ans = n - val;\r\n console.log(ans)\r\n \r\n}\r\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var a = lines[i];\n var k = lines[i].split('').map(Number);\n if(a < 10){\n console.log(a - 1); \n }else{\n var fl = '1';\n var len = k.length;\n for(j = 1; j < len; j++){\n fl += '0';\n }\n console.log(a - fl);\n }\n }\n});"}, {"source_code": "\r\n\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nfunction print(x) {\r\n console.log(x);\r\n}\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n \r\n// ********** Code Start **********\r\n\r\nfunction main() {\r\n var tests = parseInt(readline());\r\n for (let t = 0;t < tests; ++t) {\r\n var x = parseInt(readline());\r\n let prev = 1;\r\n let next = 1;\r\n let ans = 1;\r\n while (next <= x) {\r\n ans = Math.min(Math.abs(x-prev),Math.abs(x-next));\r\n prev = 10;\r\n next *= 10;\r\n }\r\n console.log(ans);\r\n }\r\n}"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = readline().trim();\r\n let p = n.length,\r\n k = 10;\r\n if (p === 1) {\r\n console.log(parseInt(n) - 1);\r\n continue;\r\n }\r\n for (let i = 2; i < p; i++) k = k * 10;\r\n console.log(Math.abs(parseInt(n) - k));\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let price = readline();\r\n let target = 0;\r\n if (price.length === 1) {\r\n target = 1\r\n } else {\r\n target = Number('1' + ('0').repeat(price.length - 1));\r\n }\r\n output(Number(price) - target);\r\n \r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nfunction solve(n, m, s) {\r\n return n - 10 ** (n.toString().length - 1);\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const n = Number(await read());\r\n res[i] = solve(n);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n output[i] = solve(n)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n) {\n const k = Math.floor(Math.log10(n))\n return n - 10 ** k\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar M = nextInt();\r\n\t\tvar d = 0;\r\n\t\tvar now = 1;\r\n\t\twhile(true){\r\n\t\t\tif(now * 10 <= M){\r\n\t\t\t\tnow *= 10;\r\n\t\t\t}else{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\tmyout(M - now);\r\n\t}\r\n}\r\n"}, {"source_code": "T = readline()\r\nwhile (T--) {\r\n m = readline().split('').map(el => +el)\r\n \r\n if(m[0] !=1){\r\n m[0] = m[0] - 1\r\n }\r\n else{\r\n m.shift()\r\n }\r\n if(m.length){\r\n print(+m.join(''))\r\n } \r\n else{\r\n print('0')\r\n }\r\n \r\n}"}, {"source_code": "var limit = parseInt(readline());\r\nfor (var i = 0; i < limit; i++)\r\n{\r\n var valueString = readline();\r\n var power = valueString.length;\r\n var value = parseInt(valueString);\r\n var roundNum = 1;\r\n for (var j = 1; j < power; j++)\r\n {\r\n roundNum *= 10;\r\n }\r\n var result = value - roundNum;\r\n print(result);\r\n}"}, {"source_code": "var tens = [];\r\n for (var i=0; i < 10; i++) {\r\n tens.push(Math.pow(10,i));\r\n }\r\n var tests = parseInt(readline());\r\n for (var t=0; t < tests; t++) {\r\n var m = parseInt(readline());\r\n var i = 1;\r\n while (tens[i] && m >= tens[i]) {\r\n i++;\r\n }\r\n print(m-tens[i-1]);\r\n }"}, {"source_code": "\r\nconst main = () => {\r\n\t\r\n\tvar t = readInt();\r\n\tvar allans = [];\r\n\tfor (var zz = 0; zz < t; zz++) {\r\n\t\tvar m = readInt();\r\n\t\tvar x = 1;\r\n\t\twhile (x * 10 <= m) {\r\n\t\t\tx *= 10;\r\n\t\t}\r\n\t\tvar ans = m - x;\r\n\t\tallans.push(ans);\r\n\t}\r\n\tmultiLineArrayPrint(allans);\r\n\t\r\n\treturn;\r\n}\r\n\r\nconst readInt = () => parseInt(readline());\r\nconst readString = () => readline();\r\nconst readIntArr = () => readline().split(\" \").map(zzzz => parseInt(zzzz));\r\nconst parseLong = (string) => { // javascript's largest long is < (1<<62)\r\n\tvar n = string.length;\r\n\tvar res = 0;\r\n\tfor (var i = 0; i < n; i++) {\r\n\t\tres *= 10;\r\n\t\tres += parseInt(string[i]);\r\n\t}\r\n\treturn res;\r\n}\r\nconst readLong = () => parseLong(readLong());\r\nconst readLongArr = () => readline().split(\" \").map(zzzz => parseLong(zzzz));\r\nconst oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));\r\nconst multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\\n'));\r\nconst multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\\n'));\r\nconst makeArr = (defaultVal, dimensionsArr) => {\r\n\tvar n = dimensionsArr.length;\r\n\tif (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);\r\n\telse {\r\n\t\tvar temp = [];\r\n\t\tfor (var i = 0; i < dimensionsArr[0]; i++)\r\n\t\t\ttemp.push(makeArr(defaultVal, dimensionsArr.slice(1)));\r\n\t\treturn temp;\r\n\t}\r\n}\r\n\r\nfor (_ = 0; _ < 1; _++) {\r\n\tmain();\r\n}\r\n\r\n// newline for testing\r\n //newline for testing\r\n// codeforces js cannot use \"let\" keyword. use \"var\" instead\r\n// codeforces js cannot destructure arrays"}, {"source_code": "t = parseInt(readline());\r\n\r\nvar ans =0, n ;\r\n\r\nwhile(t--)\r\n{\r\n ans =1;\r\n //n= prompt();\r\n n= parseInt(readline());\r\n \r\n while(ans*10<=n) ans*=10;\r\n\r\n print(n-ans);\r\n //console.log(n-ans);\r\n\r\n}"}], "negative_code": [{"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n e = 1\n for(l = 0; l < k.length - 1; l++){\n e += '0'\n }\n if(b < 10){\n console.log(b-1)\n }else{\n \n console.log(k-e)\n\n }\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n k[0] -= 1\n if(b < 10){\n console.log(b-1)\n }else{\n \n console.log(k.join(''))\n\n }\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n k[0] -= 1\n if(b < 10){\n console.log(b)\n }else{\n \n console.log(k.join(''))\n\n }\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n k[0] -= 1 \n if(k[0] === 0 && k.length > 1){\n k.splice(0,1)\n }\n console.log(k.join(''))\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n k[0] -= 1 \n if(k[0] === 0){\n k.splice(0,1)\n }\n console.log(k.join(''))\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n k[0] -= 1 \n if(k[0] === 0 && k.length < 1){\n k.splice(0,1)\n }\n console.log(k.join(''))\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n k[0] -= 1 \n if(k[0] === 0 && k.length <= 1){\n k.splice(0,1)\n }\n console.log(k.join(''))\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split('').map(Number)\n b = lines[j]\n \n k[0] -= 1 \n console.log(k.join(''))\n\n }\n \n\t \n}); "}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL); /*your input text, split by lines*/\n var n = lines[0]\n for(j = 1; j <= n; j++){\n k = lines[j].split(\" \").map(Number)\n \n a = Math.abs(k[0] - 1);\n b = Math.abs(k[2] - k[1]) + Math.abs(k[2] - 1);\n if (a < b) {\n console.log(1);\n } else if (b < a) {\n console.log(2);\n } else {\n console.log(3);\n }\n\n }\n \n\t \n}); "}, {"source_code": "// cat .\\input.txt | node .\\script.js\r\nconst state = { data: [] };\r\nconst consume = (chunk) => {\r\n const chunk_string = chunk.toString()\r\n const split = chunk_string.split('\\r\\n').filter(v => v.length > 0)\r\n for (let i = 0; i < split.length; i++) {\r\n const element = split[i];\r\n if (element.indexOf(' ') == -1) {\r\n state.data.push(Number(element))\r\n continue\r\n }\r\n // if (element.indexOf(' ') > -1) {\r\n // state.data.push(element.split(' ').map(Number))\r\n // continue\r\n // }\r\n }\r\n}\r\nconst commit = (answer) => process.stdout.write(answer);\r\nconst ten_ext = (exp = 0) => 10 ** exp\r\nconst main = (args) => {\r\n const { data } = state\r\n const range = data.shift()\r\n let result = \"\"\r\n for (let i = 0; i < range; i++) {\r\n const element = data[i];\r\n const etos = element.toString()\r\n const etosl = etos.length\r\n result += ((element - ten_ext(etosl - 1)).toString() + '\\r\\n')\r\n }\r\n commit(result)\r\n};\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "// cat .\\input.txt | node .\\script.js\r\nconst state = { data: [] };\r\nconst consume = (chunk) => {\r\n const chunk_string = chunk.toString()\r\n const split = chunk_string.split('\\r\\n').filter(v => v.length > 0)\r\n for (let i = 0; i < split.length; i++) {\r\n const element = split[i];\r\n if (element.indexOf(' ') == -1) {\r\n state.data.push(Number(element))\r\n continue\r\n }\r\n if (element.indexOf(' ') > -1) {\r\n state.data.push(element.split(' ').map(Number))\r\n continue\r\n }\r\n }\r\n}\r\nconst commit = (answer) => process.stdout.write(answer);\r\nconst ten_ext = (exp = 0) => 10 ** exp\r\nconst main = (args) => {\r\n const { data } = state\r\n const range = data.shift()\r\n let result = \"\"\r\n for (let i = 0; i < range; i++) {\r\n const element = data[i];\r\n const etos = element.toString()\r\n const etosl = etos.length\r\n result += ((element - ten_ext(etosl - 1)).toString() + '\\r\\n')\r\n }\r\n commit(result)\r\n};\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "// cat .\\input.txt | node .\\script.js\r\nconst state = { data: [] };\r\nconst consume = (chunk) => {\r\n const chunk_string = chunk.toString()\r\n const split = chunk_string.split('\\r\\n').filter(v => v.length > 0)\r\n for (let i = 0; i < split.length; i++) {\r\n const element = split[i];\r\n if (element.indexOf(' ') == -1) {\r\n state.data.push(Number(element))\r\n continue\r\n }\r\n if (element.indexOf(' ') > -1) {\r\n state.data.push(element.split(' ').map(Number))\r\n continue\r\n }\r\n }\r\n state.input_counter++\r\n}\r\nconst commit = (answer) => process.stdout.write(answer);\r\nconst ten_ext = (exp = 0) => 10 ** exp\r\nconst main = (args) => {\r\n const { data } = state\r\n const range = data.shift()\r\n for (let i = 0; i < range; i++) {\r\n const element = data[i];\r\n const etos = element.toString()\r\n const etosl = etos.length\r\n commit((element - ten_ext(etosl - 1)).toString() + '\\r\\n')\r\n }\r\n};\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin\r\n});\r\n\r\nfunction getRound(m) {\r\n let s = 0\r\n let base = 10\r\n let t = 0\r\n while (t < m) {\r\n t = Math.pow(base,++s)\r\n }\r\n return m === t ? 0 : m - Math.pow(base,s - 1)\r\n}\r\nlet lines = [];\r\nrl.on('line', (line) => {\r\n lines.push(line);\r\n}).on('close', () => {\r\n const [n,...values] = lines\r\n for (let i = 0; i< n; i++) {\r\n const ans = getRound(values[i])\r\n console.log(ans)\r\n }\r\n});"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin\r\n});\r\n\r\nfunction getRound(m) {\r\n let s = 0\r\n let base = 10\r\n let t = 0\r\n while (t < m) {\r\n t = Math.pow(base,++s)\r\n }\r\n return m - Math.pow(base,--s)\r\n}\r\nlet lines = [];\r\nrl.on('line', (line) => {\r\n lines.push(line);\r\n}).on('close', () => {\r\n const [n,...values] = lines\r\n for (let i = 0; i< n; i++) {\r\n const ans = getRound(values[i])\r\n console.log(ans)\r\n }\r\n});"}, {"source_code": "const readline = require('readline');\r\n\r\nconst rl = readline.createInterface({\r\n input: process.stdin\r\n});\r\n\r\nfunction getRound(m) {\r\n let s = 0\r\n let base = 10\r\n let t = 0\r\n while (t < m) {\r\n t = Math.pow(base,++s)\r\n }\r\n return m - (t/10)\r\n}\r\nlet lines = [];\r\nrl.on('line', (line) => {\r\n lines.push(line);\r\n}).on('close', () => {\r\n const [n,...values] = lines\r\n for (let i = 0; i< n; i++) {\r\n const ans = getRound(values[i])\r\n console.log(ans)\r\n }\r\n});"}, {"source_code": "T = readline()\r\nwhile (T--) {\r\n m = readline().split('').map(el => +el)\r\n \r\n if(m[0] !=1){\r\n m[0] = m[0] - 1\r\n }\r\n else{\r\n m.shift()\r\n }\r\n if(m.length){\r\n print(m.join(''))\r\n } \r\n else{\r\n print('0')\r\n }\r\n \r\n}"}, {"source_code": "T = readline()\r\nwhile (T--) {\r\n m = readline().split('').map(el => +el)\r\n\r\n if(m[0] !=1){\r\n m[0] = m[0] - 1\r\n }\r\n else{\r\n m.shift()\r\n }\r\n if(m.length){\r\n print(m.join(''))\r\n } \r\n else{\r\n print('0')\r\n }\r\n \r\n}\r\n"}, {"source_code": "var tens = [];\r\n for (var i=0; i < 10; i++) {\r\n tens.push(Math.pow(10,i));\r\n }\r\n var tests = parseInt(readline());\r\n for (var t=0; t < tests; t++) {\r\n var m = parseInt(readline());\r\n var i = 1;\r\n while (tens[i] && m > tens[i]) {\r\n i++;\r\n }\r\n print(m-tens[i-1]);\r\n }"}], "src_uid": "5312a505bd59b55a6c5487f67a33d81a"} {"nl": {"description": "Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?", "input_spec": "The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers ai (10 ≤ ai ≤ 99), denoting the numbers on the cubes.", "output_spec": "In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers bi (1 ≤ bi ≤ 2). The numbers mean: the i-th cube belongs to the bi-th heap in your division. If there are multiple optimal ways to split the cubes into the heaps, print any of them.", "sample_inputs": ["1\n10 99", "2\n13 24 13 45"], "sample_outputs": ["1\n2 1", "4\n1 2 2 1"], "notes": "NoteIn the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345."}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar halfSize = parseInt(readline(), 10),\n\t\tfullSize = 2*halfSize,\n\t\tcubeOccurrences = {}, sortedCubes = [];\n\n\tvar cubes = tokenizeIntegers(readline());\n\tfor (var cubeIndex = 0; cubeIndex < fullSize; ++cubeIndex) {\n\t\tvar cube = cubes[cubeIndex];\n\t\tif (cubeOccurrences[cube] == undefined) {\n\t\t\tcubeOccurrences[cube] = [];\n\t\t\tsortedCubes.push(cubeOccurrences[cube]);\n\t\t}\n\t\tcubeOccurrences[cube].push(cubeIndex);\n\t}\n\n\tsortedCubes.sort(function (a, b) {\n\t\tif (a.length%2 != b.length%2) {\n\t\t\treturn a.length%2 - b.length%2;\n\t\t}\n\t\telse {\n\t\t\treturn a.length - b.length;\n\t\t}\n\t});\n\n\tvar uniqueNum = sortedCubes.length,\n\t\tcounts = { 1: 0, 2: 0 },\n\t\tpartition = new Array(fullSize);\n\n\tfor (var uniqueIndex = 0; uniqueIndex < uniqueNum; ++uniqueIndex) {\n\t\tvar occurrences = sortedCubes[uniqueIndex],\n\t\t\tside = 1 + uniqueIndex%2;\n\t\tfor (var occurrenceIndex = 0; occurrenceIndex < occurrences.length; ++occurrenceIndex) {\n\t\t\tpartition[occurrences[occurrenceIndex]] = side;\n\t\t\tif (occurrenceIndex < 2) {\n\t\t\t\tcounts[side] += 1;\n\t\t\t}\n\t\t\tside = (side == 1 ? 2 : 1);\n\t\t}\n\n\t\t//print(occurrences.length+\": \"+occurrences.join(\" \"));\n\t}\n\n\t//print(counts[1], counts[2]);\n\tprint(counts[1] * counts[2]);\n\tprint(partition.join(\" \"));\n}\n\nmain();\n"}], "negative_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar halfSize = parseInt(readline(), 10),\n\t\tfullSize = 2*halfSize,\n\t\tcubeInfo = {}, sortedCubes = [];\n\n\tvar cubes = tokenizeIntegers(readline());\n\tfor (var cubeIndex = 0; cubeIndex < fullSize; ++cubeIndex) {\n\t\tvar cube = cubes[cubeIndex];\n\t\tif (cubeInfo[cube] == undefined) {\n\t\t\tcubeInfo[cube] = { value: cube, occurrences: [] };\n\t\t\tsortedCubes.push(cubeInfo[cube]);\n\t\t}\n\t\tcubeInfo[cube].occurrences.push(cubeIndex);\n\t}\n\n\tsortedCubes.sort(function (a, b) {\n\t\treturn a.occurrences.length%2 - b.occurrences.length%2;\n\t});\n\n\tvar uniqueNum = sortedCubes.length,\n\t\tcounts = { 1: 0, 2: 0 },\n\t\tpartition = new Array(fullSize);\n\n\tfor (var uniqueIndex = 0; uniqueIndex < uniqueNum; ++uniqueIndex) {\n\t\tvar occurrences = sortedCubes[uniqueIndex].occurrences,\n\t\t\tside = 1 + uniqueIndex%2;\n\t\tfor (var occurrenceIndex = 0; occurrenceIndex < occurrences.length; ++occurrenceIndex) {\n\t\t\tpartition[occurrences[occurrenceIndex]] = side;\n\t\t\tif (occurrenceIndex < 2) {\n\t\t\t\tcounts[side] += 1;\n\t\t\t}\n\t\t\tside = (side == 1 ? 2 : 1);\n\t\t}\n\t}\n\n\tprint(counts[1] * counts[2]);\n\tprint(partition.join(\" \"));\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar halfSize = parseInt(readline(), 10),\n\t\tfullSize = 2*halfSize,\n\t\tcubeInfo = {}, sortedCubes = [];\n\n\tvar cubes = tokenizeIntegers(readline());\n\tfor (var cubeIndex = 0; cubeIndex < fullSize; ++cubeIndex) {\n\t\tvar cube = cubes[cubeIndex];\n\t\tif (cubeInfo[cube] == undefined) {\n\t\t\tcubeInfo[cube] = { value: cube, occurrences: [] };\n\t\t\tsortedCubes.push(cubeInfo[cube]);\n\t\t}\n\t\tcubeInfo[cube].occurrences.push(cubeIndex);\n\t}\n\n\tsortedCubes.sort(function (a, b) {\n\t\treturn a.occurrences.length - b.occurrences.length;\n\t});\n\n\tvar uniqueNum = sortedCubes.length,\n\t\tcounts = { 1: 0, 2: 0 },\n\t\tpartition = new Array(fullSize);\n\n\tfor (var uniqueIndex = 0; uniqueIndex < uniqueNum; ++uniqueIndex) {\n\t\tvar occurrences = sortedCubes[uniqueIndex].occurrences,\n\t\t\tside = 1 + uniqueIndex%2;\n\t\tfor (var occurrenceIndex = 0; occurrenceIndex < occurrences.length; ++occurrenceIndex) {\n\t\t\tpartition[occurrences[occurrenceIndex]] = side;\n\t\t\tif (occurrenceIndex < 2) {\n\t\t\t\tcounts[side] += 1;\n\t\t\t}\n\t\t\tside = (side == 1 ? 2 : 1);\n\t\t}\n\t}\n\n\tprint(counts[1] * counts[2]);\n\tprint(partition.join(\" \"));\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar halfSize = parseInt(readline(), 10),\n\tfullSize = 2*halfSize,\n\tcounts = { 1: 0, 2: 0 },\n\tduplicate = {},\n\tfirstSide = {}, currentSide = 1, sides = [];\n\n\tvar cubes = tokenizeIntegers(readline());\n\tfor (var cubeIndex = 0; cubeIndex < fullSize; ++cubeIndex) {\n\t\tvar cube = cubes[cubeIndex];\n\n\t\tif (firstSide[cube] == undefined) {\n\t\t\tcounts[currentSide] += 1;\n\t\t\tfirstSide[cube] = currentSide;\n\t\t\tsides.push(currentSide);\n\t\t\tcurrentSide = (currentSide == 1 ? 2 : 1);\n\t\t}\n\t\telse {\n\t\t\tfirstSide[cube] = (firstSide[cube] == 1 ? 2 : 1);\n\t\t\tsides.push(firstSide[cube]);\n\t\t\tif (duplicate[cube] == undefined) {\n\t\t\t\tduplicate[cube] = true;\n\t\t\t\tcounts[firstSide[cube]] += 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tprint(counts[1]*counts[2]);\n\tprint(sides.join(\" \"));\n}\n\nmain();\n"}, {"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar halfSize = parseInt(readline(), 10),\n\t\tfullSize = 2*halfSize,\n\t\tcubeInfo = {}, sortedCubes = [];\n\n\tvar cubes = tokenizeIntegers(readline());\n\tfor (var cubeIndex = 0; cubeIndex < fullSize; ++cubeIndex) {\n\t\tvar cube = cubes[cubeIndex];\n\t\tif (cubeInfo[cube] == undefined) {\n\t\t\tcubeInfo[cube] = { value: cube, occurrences: [] };\n\t\t\tsortedCubes.push(cubeInfo[cube]);\n\t\t}\n\t\tcubeInfo[cube].occurrences.push(cubeIndex);\n\t}\n\n\tsortedCubes.sort(function (a, b) {\n\t\treturn a.occurrences.length - b.occurrences.length;\n\t});\n\n\tvar uniqueNum = sortedCubes.length,\n\t\tcounts = { 1: 0, 2: 0 },\n\t\tpartition = new Array(fullSize);\n\n\tfor (var uniqueIndex = 0; uniqueIndex < uniqueNum; ++uniqueIndex) {\n\t\tvar occurrences = sortedCubes[uniqueIndex].occurrences,\n\t\t\tside = 1 + uniqueIndex%2;\n\t\tfor (var occurrenceIndex = 0; occurrenceIndex < occurrences.length; ++occurrenceIndex) {\n\t\t\tpartition[occurrences[occurrenceIndex]] = side;\n\t\t\tcounts[side] += 1;\n\t\t\tside = (side == 1 ? 2 : 1);\n\t\t}\n\t}\n\n\tprint(counts[1] * counts[2]);\n\tprint(partition.join(\" \"));\n}\n\nmain();\n"}], "src_uid": "080287f34b0c1d52eb29eb81dada41dd"} {"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 — 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}$$$) — 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": "// n = glass container width, k = glass height, b = |filled glass liquid height|, s = |total liquid height|\r\nfunction solve(n, k, b, s){\r\n // const FIRST_GLASS = (k+1) * b - 1;\r\n // const REST_GLASS = b - 1;\r\n const FIRST_GLASS = k * (b+1) - 1;\r\n const REST_GLASS = k - 1;\r\n const MIN_CAPACITY = k * b;\r\n const MAX_CAPACITY = FIRST_GLASS + ((n-1) * REST_GLASS);\r\n if(s < MIN_CAPACITY || s > MAX_CAPACITY) return [-1]; // RTE if not arr\r\n\r\n const result = Array(n).fill(0);\r\n\r\n for(let i=0;idata+=string);\r\nprocess.stdin.on('end', () => {\r\n const dataLines = data.split(EOL);\r\n B1715(dataLines);\r\n});\r\n\r\n\r\n\r\n/* --------------------------------------- local test ------------------------------------------ \r\n\r\nlet data = `8\r\n1 6 3 100\r\n3 6 3 12\r\n3 6 3 19\r\n5 4 7 38\r\n5 4 7 80\r\n99978 1000000000 100000000 1000000000000000000\r\n1 1 0 0\r\n4 1000000000 1000000000 1000000000000000000`;\r\n\r\nconst dataLines = data.split('\\n');\r\nconsole.log(B1715(dataLines));\r\n\r\n*/\r\n\r\n\r\n/* --------------------------------------- boilerplate ------------------------------------------ */\r\n\r\nfunction convertNumberArray(str){ // ' 12 43 123 4 ' >> [12, 43, 123, 4]\r\n return str.replace(/ +/g, \" \").trim().split(' ').map(string => Number(string));\r\n}\r\nfunction printArray(arr){ // [12, 43, 123, 4] >> '12 43 123 4'\r\n return arr.join(' ');\r\n}\r\nfunction B1715(input){\r\n let result = '';\r\n const tests = Number(input[0]);\r\n for(let i=1; i<=tests; i++){\r\n const [n, k, b, s] = convertNumberArray(input[i]);\r\n // process.stdout.write(solve(n, k, b, s) + '\\n'); // array printing error\r\n process.stdout.write(printArray(solve(n, k, b, s)) + '\\n');\r\n result+=solve(n, k, b, s) + '\\n'\r\n }\r\n return result;\r\n}\r\n\r\n\r\n/*\r\nanswer\r\n-1\r\n-1\r\n0 0 19\r\n0 3 3 3 29\r\n-1\r\n-1\r\n0\r\n0 0 0 1000000000000000000\r\n\r\n*/\r\n"}, {"source_code": "var tests = parseInt(readline());\r\n var n, k, b, s;\r\n\r\n for (var t=0; t < tests; t++) {\r\n var nkbs = readline().split(' ').map(x=>parseInt(x));\r\n n = nkbs[0];\r\n k = nkbs[1];\r\n b = nkbs[2];\r\n s = nkbs[3];\r\n \r\n if (s < k * b || s > k * b + n * (k-1)) {\r\n print(-1);\r\n continue;\r\n }\r\n var ans = [];\r\n var sum = s;\r\n var first = b * k;\r\n first += Math.min(sum - b*k, k-1);\r\n ans.push(first);\r\n sum -= first;\r\n while (sum > 0) {\r\n var next = Math.min(k-1, sum);\r\n ans.push(next);\r\n sum -= next;\r\n }\r\n while (ans.length < n) {\r\n ans.push(0);\r\n }\r\n print(ans.join(' '));\r\n }"}], "negative_code": [{"source_code": "// n = glass container width, k = glass height, b = |filled glass liquid height|, s = |total liquid height|\r\nfunction solve(n, k, b, s){\r\n // const FIRST_GLASS = (k+1) * b - 1;\r\n // const REST_GLASS = b - 1;\r\n const FIRST_GLASS = k * (b+1) - 1;\r\n const REST_GLASS = k - 1;\r\n const MIN_CAPACITY = k * b;\r\n const MAX_CAPACITY = FIRST_GLASS + ((n-1) * REST_GLASS);\r\n if(s < MIN_CAPACITY || s > MAX_CAPACITY) return -1;\r\n\r\n const result = Array(n).fill(0);\r\n\r\n for(let i=0;idata+=string);\r\nprocess.stdin.on('end', () => {\r\n const dataLines = data.split(EOL);\r\n B1715(dataLines);\r\n});\r\n\r\n\r\n\r\n/* --------------------------------------- local test ------------------------------------------ */\r\n\r\n// let data = `8\r\n// 1 6 3 100\r\n// 3 6 3 12\r\n// 3 6 3 19\r\n// 5 4 7 38\r\n// 5 4 7 80\r\n// 99978 1000000000 100000000 1000000000000000000\r\n// 1 1 0 0\r\n// 4 1000000000 1000000000 1000000000000000000`;\r\n\r\n// const dataLines = data.split('\\n');\r\n// console.log(B1715(dataLines));\r\n\r\n\r\n\r\n/* --------------------------------------- boilerplate ------------------------------------------ */\r\n\r\nfunction convertNumberArray(str){ // ' 12 43 123 4 ' >> [12, 43, 123, 4]\r\n return str.replace(/ +/g, \" \").trim().split(' ').map(string => Number(string));\r\n}\r\nfunction B1715(input){\r\n let result = '';\r\n const tests = Number(input[0]);\r\n for(let i=1; i<=tests; i++){\r\n const [n, k, b, s] = convertNumberArray(input[i]);\r\n process.stdout.write(solve(n, k, b, s) + '\\n');\r\n result+=solve(n, k, b, s) + '\\n'\r\n }\r\n return result;\r\n}\r\n\r\n\r\n/*\r\nanswer\r\n-1\r\n-1\r\n0 0 19\r\n0 3 3 3 29\r\n-1\r\n-1\r\n0\r\n0 0 0 1000000000000000000\r\n\r\n*/"}], "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 — 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 · l 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 · r 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, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).", "output_spec": "In the single line print a single number — 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 = r, 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·42 + 4·99 + 4·3 = 576 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·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units."}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar data = tokenizeIntegers(readline());\n\tvar numItems = data[0],\n\t\tcostL = data[1], costR = data[2],\n\t\tpenaltyL = data[3], penaltyR = data[4];\n\n\tvar weights = tokenizeIntegers(readline());\n\n\tvar baseCost = 0;\n\tfor (var itemIndex = 0; itemIndex < numItems; ++itemIndex) {\n\t\tbaseCost += weights[itemIndex]*costR;\n\t}\n\n\tvar best = baseCost + (numItems-1)*penaltyR;\n\n\tvar countL = 0, countR = numItems;\n\n\tfor (var itemIndex = 0; itemIndex < numItems; ++itemIndex) {\n\n\t\tbaseCost += weights[itemIndex] * (costL - costR);\n\n\t\t++countL;\n\t\t--countR;\n\n\t\tvar penalty = 0;\n\t\tif (countR > countL) {\n\t\t\tpenalty = (countR - 1 - countL) * penaltyR;\n\t\t}\n\t\telse if (countL > countR) {\n\t\t\tpenalty = (countL - 1 - countR) * penaltyL;\n\t\t}\n\n\t\tbest = Math.min(best, baseCost + penalty);\n\t}\n\n\tprint(best);\n}\n\nmain();\n"}], "negative_code": [], "src_uid": "e6fcbe3f102b694a686c0295edbc35e9"} {"nl": {"description": "Monocarp has got two strings $$$s$$$ and $$$t$$$ having equal length. Both strings consist of lowercase Latin letters \"a\" and \"b\". Monocarp wants to make these two strings $$$s$$$ and $$$t$$$ equal to each other. He can do the following operation any number of times: choose an index $$$pos_1$$$ in the string $$$s$$$, choose an index $$$pos_2$$$ in the string $$$t$$$, and swap $$$s_{pos_1}$$$ with $$$t_{pos_2}$$$.You have to determine the minimum number of operations Monocarp has to perform to make $$$s$$$ and $$$t$$$ equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.", "input_spec": "The first line contains one integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^{5})$$$ — the length of $$$s$$$ and $$$t$$$. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters \"a\" and \"b\". The third line contains one string $$$t$$$ consisting of $$$n$$$ characters \"a\" and \"b\". ", "output_spec": "If it is impossible to make these strings equal, print $$$-1$$$. Otherwise, in the first line print $$$k$$$ — the minimum number of operations required to make the strings equal. In each of the next $$$k$$$ lines print two integers — the index in the string $$$s$$$ and the index in the string $$$t$$$ that should be used in the corresponding swap operation. ", "sample_inputs": ["4\nabab\naabb", "1\na\nb", "8\nbabbaabb\nabababaa"], "sample_outputs": ["2\n3 3\n3 2", "-1", "3\n2 6\n1 3\n7 8"], "notes": "NoteIn the first example two operations are enough. For example, you can swap the third letter in $$$s$$$ with the third letter in $$$t$$$. Then $$$s = $$$ \"abbb\", $$$t = $$$ \"aaab\". Then swap the third letter in $$$s$$$ and the second letter in $$$t$$$. Then both $$$s$$$ and $$$t$$$ are equal to \"abab\".In the second example it's impossible to make two strings equal."}, "positive_code": [{"source_code": "const n = Number(readline());\nconst s = Array.from(readline().substring(0, n), c => c === \"b\");\nconst t = Array.from(readline().substring(0, n), c => c === \"b\");\nconst results = (() => {\n if (s.concat(t).reduce((a, b) => a ^ b)) return null;\n var abs = [];\n var bas = [];\n for (var i = 0; i < n; i++)\n if (s[i] ^ t[i]) {\n if (t[i]) abs.push(i);\n else bas.push(i);\n }\n var results = [];\n while (abs.length >= 2)\n results.push([abs.pop(), abs.pop()]);\n while (bas.length >= 2)\n results.push([bas.pop(), bas.pop()]);\n if (abs.length) {\n if (!bas.length) return null;\n var x = abs.pop();\n results.push([x, x], [x, bas.pop()]);\n }\n return results;\n})();\nif (results) {\n print(results.length);\n for (var result of results)\n print(`${result[0] + 1} ${result[1] + 1}`);\n} else print(\"-1\");\n"}, {"source_code": "const n = Number(readline());\nconst s = Array.from(readline().substring(0, n), c => c === \"b\");\nconst t = Array.from(readline().substring(0, n), c => c === \"b\");\nconst results = (() => {\n if (s.concat(t).reduce((a, b) => a ^ b)) return null;\n var abs = [];\n var bas = [];\n for (var i = 0; i < n; i++)\n if (s[i] ^ t[i]) {\n if (t[i]) abs.push(i);\n else bas.push(i);\n }\n var results = [];\n while (abs.length >= 2)\n results.push([abs.pop(), abs.pop()]);\n while (bas.length >= 2)\n results.push([bas.pop(), bas.pop()]);\n if (abs.length) {\n if (!bas.length) return null;\n var x = abs.pop();\n results.push([x, x], [x, bas.pop()]);\n }\n return results;\n})();\nif (results) {\n print(results.length);\n for (var result of results)\n print(`${result[0] + 1} ${result[1] + 1}`);\n} else print(\"-1\");\n"}], "negative_code": [], "src_uid": "181199a0cf37c83cec1ba28d343b50ae"} {"nl": {"description": "You are given four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$. Timur and three other people are running a marathon. The value $$$a$$$ is the distance that Timur has run and $$$b$$$, $$$c$$$, $$$d$$$ correspond to the distances the other three participants ran. Output the number of participants in front of Timur.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) — the number of test cases. The description of each test case consists of four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \\leq a, b, c, d \\leq 10^4$$$).", "output_spec": "For each test case, output a single integer — the number of participants in front of Timur.", "sample_inputs": ["4\n\n2 3 4 1\n\n10000 0 1 2\n\n500 600 400 300\n\n0 9999 10000 9998"], "sample_outputs": ["2\n0\n1\n3"], "notes": "NoteFor the first test case, there are $$$2$$$ people in front of Timur, specifically the participants who ran distances of $$$3$$$ and $$$4$$$. The other participant is not in front of Timur because he ran a shorter distance than Timur.For the second test case, no one is in front of Timur, since he ran a distance of $$$10000$$$ while all others ran a distance of $$$0$$$, $$$1$$$, and $$$2$$$ respectively.For the third test case, only the second person is in front of Timur, who ran a total distance of $$$600$$$ while Timur ran a distance of $$$500$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\n \r\n let t = +(readline());\r\n \r\n for(let i=0;i +dist[0])cnt++;\r\n }\r\n \r\n print(cnt);\r\n }"}, {"source_code": "\"use strict\";\r\n\r\n let x = +(readline());\r\n\r\n for(let i = 0; i < x; i++) {\r\n marathone(readline().split(' ')); \r\n }\r\n\r\n function marathone(distances) {\r\n let counter = 0;\r\n for(let i = 1; i < 4; i++) {\r\n let timurDistance = +distances[0];\r\n\r\n if(timurDistance < +distances[i]) {\r\n counter++;\r\n } \r\n }\r\n\r\n print(counter);\r\n }"}, {"source_code": "var t = readline();\r\nfor(var i =0 ; i < t ; i++){\r\n var inputs = readline().split(' '),\r\n counter = 0,\r\n timur = inputs[0],\r\n participants = inputs.slice(1);\r\n for(var j = 0 ; j < participants.length ; j++){\r\n if(parseInt(participants[j]) > parseInt(timur) ){\r\n counter++;\r\n }\r\n }\r\n print(counter);\r\n}\r\n\r\n"}, {"source_code": "var n = readline();\r\nvar arr = [];\r\nvar s = 0;\r\nfor(var i = 0; i < n; i++){\r\n arr[i] = readline().split(' ').map(i=>Number(i));\r\n for(var j = 0; j < arr[i].length; j++){\r\n if(arr[i][0] a)\r\n count++;\r\n }\r\n print(count);\r\n }"}, {"source_code": "var t = parseInt(readline());\r\n \r\nfor (var test = 0; test < t; test++) {\r\n var inp = readline().split(' ');\r\n var a = parseInt(inp[0]);\r\n var b = parseInt(inp[1]);\r\n var c = parseInt(inp[2]);\r\n var d = parseInt(inp[3]);\r\n\r\n var ans = (b > a) + (c > a) + (d > a);\r\n\r\n print(ans);\r\n}"}, {"source_code": "var t = readline();\r\nfor(var i =0 ; i < t ; i++){\r\n var inputs = readline().split(' '),\r\n counter = 0,\r\n timur = inputs[0],\r\n participants = inputs.slice(1);\r\n for(var j = 0 ; j < participants.length ; j++){\r\n if(parseInt(participants[j]) > parseInt(timur) ){\r\n counter++;\r\n }\r\n }\r\n print(counter);\r\n}"}, {"source_code": "var testCase=+readline(),counter\r\nfor(var i=0;ia-b)\r\n print(4-a.indexOf(b)-1)\r\n}\r\n"}, {"source_code": "test = readline();\r\n\r\nwhile (test--) {\r\n input = readline().split(\" \").map(x => parseInt(x));\r\n Timur = input[0];\r\n participantsInFront = 0;\r\n\r\n for (var i = 1; i <= 3; i++) {\r\n if (Timur < input[i]) {\r\n participantsInFront++;\r\n }\r\n }\r\n print(participantsInFront)\r\n}"}, {"source_code": "T = readline()\r\nwhile (T--) {\r\n n = readline().split(' ').map(a => +a)\r\n a = n[0]\r\n b = n[1]\r\n c = n[2]\r\n d = n[3]\r\n\r\n ans = 0\r\n if(b>a)\r\n ans++\r\n if(c>a)\r\n ans++\r\n if(d>a)\r\n ans++\r\n \r\n print(ans)\r\n}\r\n\r\n"}, {"source_code": "// как меня заебала эта корявая платформа\r\n// https://stackoverflow.com/questions/20086849/how-to-read-from-stdin-line-by-line-in-node\r\n// // cat .\\input.txt | node .\\script.js\r\nconst state = { i: 0 }\r\nconst readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false\r\n});\r\nconst ten_exp = (exp = 0) => 10 ** exp\r\nrl.on('line', function (line) {\r\n if (state.i > 0) {\r\n let data = line.split(' ').map(Number)\r\n let above = []\r\n for (let i = 1; i < data.length; i++) {\r\n const sample = data[0]\r\n const element = data[i];\r\n if (element > sample) above.push(element)\r\n\r\n }\r\n console.log(above.length)\r\n }\r\n state.i++\r\n})\r\n"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n for(i = 1; i <= t; i++){\n var k = lines[i].split(' ').map(Number);\n var ans = 0;\n\t for(j = 1; j < 4; j++){\n if(k[j] > k[0]){\n\t ans++;\n }\n\t }\n\t console.log(ans);\n }\n});"}, {"source_code": "let stop = '';\nprocess.stdin.on('data', c => stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n\tvar t = lines[0];\n\tfor(i = 1; i <= t; i++){\n\t var k = lines[i].split(' ').map(Number);\n\t var a = k[0];\n\t var ans = 0;\n\t for(j = 1; j < 4; j++){\n\t if(k[j] > a){\n\t ans++;\n\t }\n\t }\n\t console.log(ans);\n\t}\n});\n\n"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const [a1, b1, c1, d1] = d.split(\" \").map(Number);\n const ans = Number(a1 < b1) + Number(a1 < c1) + Number(a1 < d1);\n console.log(ans);\n\n // const numbers = d.split(\" \").map(Number);\n // let me = numbers[0];\n // const ans = numbers.filter((x) => x > me).length;\n\n // console.log(ans);\n\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const numbers = d.split(\" \").map(Number);\n let me = numbers[0];\n const ans = numbers.filter((x) => x > me).length;\n\n console.log(ans);\n\n c++;\n});\n\nrl.on(\"close\", () => {});\n"}, {"source_code": "var readline = require('readline');\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n terminal: false\r\n});\r\n\r\nconst res = [];\r\nrl.on('line', (line) => {\r\n const [timur, ...rest] = line.split(' ').map((n) => parseInt(n));\r\n if (rest.length !== 3) return;\r\n console.log(rest.filter(n => n > timur).length);\r\n}).on('close', () => {\r\n process.exit();\r\n});"}, {"source_code": "'use strict';\r\n\r\nfunction solve(a) {\r\n const [x, ...arr] = a;\r\n let res = 0;\r\n for (let num of a) if (num > x) res++;\r\n return res;\r\n}\r\n\r\nasync function main(read) {\r\n try {\r\n let t = Number(await read());\r\n let res = new Array(t);\r\n for (let i = 0; i < t; i++) {\r\n const a = (await read()).split(' ').map(Number);\r\n res[i] = solve(a);\r\n }\r\n return res.join('\\n');\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nlet inputs,\r\n str = '';\r\nfunction read() {\r\n return inputs.next().value.trim();\r\n}\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\nprocess.stdin.on('data', input => str += input);\r\nprocess.stdin.on('end', async () => {\r\n inputs = str.split('\\n').values();\r\n const output = await main(read);\r\n process.stdout.write(output);\r\n});\r\n"}, {"source_code": "const main = (input) => {\r\n input = input.split('\\n')\r\n\r\n const t = Number(input[0])\r\n for (let i = 0; i < t; i++) {\r\n const [a, b, c, d] = input[i + 1].split(' ').map((x) => parseInt(x))\r\n\r\n let ans = 0\r\n ans += b > a ? 1 : 0\r\n ans += c > a ? 1 : 0\r\n ans += d > a ? 1 : 0\r\n\r\n console.log(ans)\r\n }\r\n}\r\n\r\nmain(require('fs').readFileSync(0).toString())"}, {"source_code": "const readline = require('readline').createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nlet input = [];\r\nlet ans = [];\r\n\r\nreadline.on('line', line => {\r\n input.push(line);\r\n}).on('close', () => {\r\n let cases = input.slice(1).map(v=>v.split(' ').map(Number));\r\n \r\n for (let c of cases) {\r\n ans.push(c.filter(v=>v>c[0]).length);\r\n }\r\n console.log(ans.join('\\n'));\r\n \r\n});"}, {"source_code": "const { readFileSync } = require(\"fs\")\r\n \r\nlet x = readFileSync(\"./input.fd0138e687.txt\",\"utf-8\").match(/(\\d+\\s){3}\\d+/g)\r\n \r\nfor(let e of x){\r\n let [b,...a] = e.split(\" \")\r\n console.log( a.filter(e=>+e>+b).length )\r\n}"}, {"source_code": "const readline = require('readline');\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout,\r\n});\r\nlet data = [];\r\nlet dataIdx = 0;\r\n\r\nrl.on('line', function (line) {\r\n //input,\r\n data.push(...line.trim().split(' '));\r\n}).on('close', function () {\r\n //output\r\n main();\r\n process.exit();\r\n});\r\n\r\nfunction input() {\r\n return data[dataIdx++];\r\n}\r\n\r\nfunction output(value) {\r\n try {\r\n process.stdout.write(value);\r\n } catch (err) {\r\n process.stdout.write(value.toString());\r\n }\r\n}\r\n//////////////////////////////////////////////////////////\r\n\r\nfunction main() {\r\n //ps start!\r\n\r\n let t = Number(input());\r\n while (t--) {\r\n let [a, b, c, d] = [\r\n Number(input()),\r\n Number(input()),\r\n Number(input()),\r\n Number(input()),\r\n ];\r\n\r\n let result = 0;\r\n if (b > a) {\r\n result++;\r\n }\r\n if (c > a) {\r\n result++;\r\n }\r\n if (d > a) {\r\n result++;\r\n }\r\n output(result + '\\n');\r\n }\r\n}\r\n"}, {"source_code": "\"use strict\";\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction main() {\r\n const T = readline()\r\n for (let i = 0; i < T; i++) {\r\n const arr = readline().split(' ').map(Number)\r\n let result = 0\r\n for (let i = 1; i < arr.length; i++) {\r\n if (arr[i] > arr[0]) result++\r\n }\r\n console.log(result)\r\n }\r\n}\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n \r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n const [a,b,c,d] = readline().split(' ').map(Number);\r\n let r = 0;\r\n if (b > a) r++;\r\n if (c > a) r++;\r\n if (d > a) r++;\r\n output(r);\r\n }\r\n}\r\n"}, {"source_code": "let i = '';\nprocess.stdin.on('data', c => i += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = i.split(EOL);\n var n = lines[0]\n for(j = 1; j <= n; j ++){\n var s = lines[j].split(' ').map(Number)\n var a = s[0]\n var b = s[1]\n var c = s[2]\n var d = s[3]\n var e = 0\n for(l = 1; l <= 4; l++){\n if(a < s[l]){\n e+=1\n }\n }\n console.log(e)\n }\n \n});\n"}, {"source_code": "function Solution() {\n let t = 0;\n const n = Number(lines[t++]);\n\n const res = [];\n for (let i = 0; i < n; i++) {\n const arr = lines[t++].split(' ').map((item) => Number(item));\n let count = 0;\n for (let z = 0; z < arr.length; z++) {\n if (arr[z] > arr[0]) count += 1;\n }\n res[i] = count;\n }\n \n return res.join('\\n');\n}\n\nconst readline = require('readline')\n \nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n console.log(Solution());\n});"}, {"source_code": "const rdline = require('readline');\r\n\r\nconst rl = rdline.createInterface({\r\n input: process.stdin\r\n});\r\n\r\nlet lines = [];\r\nrl.on('line', (line) => {\r\n lines.push(line);\r\n}).on('close', () => {\r\n // input in lines\r\n solve();\r\n});\r\n\r\nlet line = 0;\r\nconst readline = () => lines[line++];\r\n\r\nsolve = () => {\r\n const t = parseInt(readline());\r\n for (let i = 0; i < t; i++) {\r\n n = 0;\r\n const s = readline().split(\" \").map(Number);\r\n for (let j = 1; j < s.length; j++) {\r\n if (s[j] > s[0]) {\r\n n++;\r\n }\r\n }\r\n console.log(n);\r\n }\r\n} "}, {"source_code": "//Setup\r\nlet i = ''\r\nlet a;\r\nprocess.stdin.on('data', c => i += c)\r\nprocess.stdin.on('end', () => {\r\n const {EOL} = require('os')\r\n const lines = i.split(EOL) /*your input text, split by lines*/\r\n //console.log(lines); \r\n a=lines\r\n//Actual Code \r\nfunction stringToNumber(array){\r\n for (var i = 0; i < array.length; i++){\r\n array[i]=parseInt(array[i])\r\n }\r\n \r\n return array\r\n}\r\nvar numTestes = a[0]\r\nnumTestes = parseInt(numTestes)\r\nvar testData = []\r\nfor(c=1;c<=numTestes;c++){\r\n testData.push(stringToNumber(a[c].split(\" \")))\r\n}\r\n\r\nfor(b=0;b parseInt(x, 10));\n var a = xs[0];\n console.log(xs.slice(1).map(x => a < x).reduce((x, y) => x + y));\n }\n}\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n"}, {"source_code": "const solve = (arr)=>{\r\n let a = arr[0],cnt = 0;\r\n for(let i=1;i<4;i++){\r\n if(arr[i]>a) cnt++;\r\n }\r\n return cnt;\r\n}\r\n\r\nfunction main() {\r\n const fs = require(\"fs\");\r\n const input = fs.readFileSync(0, \"utf8\").trim().split(\"\\n\");\r\n let line = 0;\r\n function readline() {\r\n return input[line++];\r\n }\r\n let t = parseInt(readline());\r\n for(let i=0;iparseInt(cur));\r\n console.log(solve(arr));\r\n }\r\n}\r\nmain();"}, {"source_code": "let data = '';\nprocess.stdin.on('data', c => data += c);\n \nfunction* nextLine() {\n\tlet lines = data.trim().split(/\\n/g);\n\tfor(let l of lines){\n\t\tyield l.trim();\n\t}\n}\n \nlet nl = nextLine();\n \nnl.elem = function(funParse) {\n\t\treturn funParse(this.next().value);\t\n\t};\n \nnl.array = function(funParse) {\n\t\treturn this.next().value.split(/\\s/g).map(funParse||(x => x));\n\t};\n\t\nnl.num = function() {\n\t\treturn nl.elem(Number);\n\t};\n\t\nnl.nums = function() {\n\t\treturn nl.array(Number);\n\t};\n\t\nnl.line = function() {\n\t\treturn this.next().value;\n\t};\n\t\nconst sol = () => {\n\t//your code this\n\tlet t = nl.num();\n\tlet ans = [];\n\tfor(let i = 0; i < t; i++){\n\t\tlet a = nl.nums();\n\t\tlet x = a.shift();\n\t\tlet c = a.reduce((ac, e) => ac + ((e>x)?1:0), 0);\n\t\tans.push(c);\n\t}\n\tconsole.log(ans.join('\\n'));\n};\n \nprocess.stdin.on('end', sol);\n"}, {"source_code": "/* Common Template Starts */\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n \r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\n \r\nprocess.stdin.on(\"end\", (_) => {\r\n inputString = inputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((string) => {\r\n return string.trim();\r\n });\r\n \r\n main();\r\n});\r\n \r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n/* Common Template Ends */\r\n\r\nfunction main() {\r\n let n = readline()\r\n\r\n for (let i = 0; i < n; i++) {\r\n let participants = 0\r\n\r\n let row = readline().split(' ')\r\n\r\n if (parseInt(row[0]) < parseInt(row[1])) {\r\n participants++\r\n }\r\n\r\n if (parseInt(row[0]) < parseInt(row[2])) {\r\n participants++\r\n }\r\n\r\n if (parseInt(row[0]) < parseInt(row[3])) {\r\n participants++\r\n }\r\n\r\n console.log(participants)\r\n }\r\n}"}, {"source_code": "/**\r\n * Author : Fazlul Hoque\r\n * Node.js version : 12.16.3\r\n * command : node fileName.js output.txt\r\n */\r\n\"use strict\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\nlet inputString = \"\"; //An array of raw inputs (includes 'n,\\r , not usable. need to process before use)\r\nlet currentLine = 0; //input sequence controller variable.\r\n\r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main(); // after input \r\n});\r\n\r\n/********** Utility Functions Start **********/\r\n/**\r\n * read row Input\r\n * @returns string\r\n */\r\nfunction _readRawLine() {\r\n return inputString[currentLine++];\r\n}\r\nfunction readLine(){\r\n // return _readRawLine().replace(/\\s+$/g, '');\r\n return _readRawLine().replace('\\r', '');\r\n}\r\n\r\nfunction print(x) {\r\n console.log(x);\r\n}\r\n\r\nfunction readSingleInt() {\r\n const p = readLine();\r\n return parseInt(p);\r\n}\r\n\r\nfunction readIntArray() {\r\n return readLine().split(\" \").map((v) => parseInt(v));\r\n}\r\n\r\nfunction readArray() {\r\n return readLine().split(\" \");\r\n}\r\n\r\nfunction int(n) {\r\n return parseInt(n);\r\n}\r\n/********** Utility Functions End **********/\r\n/**\r\n * Don't Touch this fucntion at all , unless you know what are you doing!\r\n */\r\nfunction main() {\r\n solve();\r\n}\r\n\r\n// ********** actual Code Starts from here **********\r\n\r\n\r\nfunction solve() {\r\n let t = readSingleInt();\r\n while(t--)\r\n {\r\n let n = readIntArray();\r\n let cnt = 0;\r\n for(let i=1;i {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction findKthLargest(nums, k) {\r\n k = nums.length - k;\r\n const quickSelect = (l, r) => {\r\n let pivot = nums[r];\r\n let p = l;\r\n for (let i = l; i < r; i++) {\r\n if (nums[i] <= pivot) {\r\n swapper(nums, p, i);\r\n p++;\r\n }\r\n }\r\n swapper(nums, p, r);\r\n\r\n if (p > k) return quickSelect(l, p - 1);\r\n else if (p < k) return quickSelect(p + 1, r);\r\n else return nums[p];\r\n };\r\n\r\n return quickSelect(0, nums.length - 1);\r\n};\r\n\r\nfunction swapper(array, a, b) {\r\n const temp = array[b];\r\n array[b] = array[a];\r\n array[a] = temp;\r\n};\r\n\r\nfunction main() {\r\n const n = parseInt(readline());\r\n for(var i=0; i parseInt(r));\r\n var count = 0;\r\n var num = nums[0];\r\n for(var j=1; j<4; j++){\r\n if(nums[j]>num){\r\n count++;\r\n }\r\n }\r\n foo(String(count));\r\n }\r\n}\r\nfunction foo(x) {\r\n process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(); // with auto '\\n' (newline)\r\n}\r\n"}, {"source_code": "process.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n//\r\nlet standardInputString = \"\";\r\nlet currentLine = 0;\r\n//\r\nprocess.stdin.on(\"data\", (rawData) => {\r\n standardInputString += rawData;\r\n});\r\nprocess.stdin.on(\"end\", (_) => {\r\n standardInputString = standardInputString\r\n .trim()\r\n .split(\"\\n\")\r\n .map((line) => {\r\n return line.trim();\r\n });\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return standardInputString[currentLine++];\r\n}\r\nfunction print(data) {\r\n console.log(data);\r\n}\r\n\r\n//line to array of integers\r\n//readline().split(' ').map(Number)\r\n// let iter=parseInt(readline())\r\n//multiple integer construction->const [a,b,c]=integer array\r\n\r\nfunction main() {\r\n let q = parseInt(readline());\r\n for (let i = 0; i < q; i++) {\r\n let input = readline().split(\" \").map(Number);\r\n print(R(input));\r\n }\r\n}\r\n\r\nfunction R(arr) {\r\n let count = 0;\r\n for (let i = 1; i < arr.length; i++) {\r\n if (arr[i] > arr[0]) count++;\r\n }\r\n return count;\r\n}"}, {"source_code": "const fs = require('fs');\r\nconst input = fs.readFileSync(0, 'utf8').trim().split('\\r\\n');\r\nlet currentline = 0;\r\nfunction readline(){\r\n return input[currentline++];\r\n}\r\n\r\nfunction alph() {\r\n var f = 'abcdefghijklmnopqrstuvwxyz';\r\n return f;\r\n}\r\nfunction Alph() {\r\n var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n return f;\r\n}\r\nfunction max(x,y) {\r\n return x >=y ? x : y;\r\n}\r\nfunction min(x,y) {\r\n return x <=y ? x : y;\r\n}\r\nfunction abs(x) {\r\n return x < 0 ? x*(-1) : x;\r\n}\r\nvar T = readline();\r\nfor(var qe=1;qe<=T;qe++) {\r\n //var n = readline()//.split(' ').map((x) => parseInt(x));\r\n var [a,b,c,d] = readline().split(' ').map((x) => parseInt(x));\r\n var ans = 0;\r\n if(b > a) ans++\r\n if(c > a) ans++\r\n if(d > a) ans++\r\n console.log(ans)\r\n //fs.appendFileSync('output.txt', ans+'\\r\\n');\r\n\r\n}\r\n//"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else if(code == 'long'){\r\n\t\t\tret[i] = nextLong();\r\n\t\t}else if(code == 'double'){\r\n\t\t\tret[i] = nextDouble();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\twhile(hasNext()){\r\n\t\tvar list = [];\r\n\t\tfor(var i = 0; i < 4; i++){\r\n\t\t\tlist.push({\r\n\t\t\t\tno : i,\r\n\t\t\t\tv : nextInt()\r\n\t\t\t});\r\n\t\t}\r\n\t\tlist.sort(function(a,b){\r\n\t\t\treturn b.v - a.v;\r\n\t\t});\r\n\t\tfor(var i = 0; i < 4; i++){\r\n\t\t\tif(list[i].no == 0){\r\n\t\t\t\tmyout(i);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const arr = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(arr)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(arr) {\n let ans = 0\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > arr[0]) ans++\n }\n return ans\n}\n"}], "negative_code": [{"source_code": "\"use strict\";\r\n \r\n let t = +(readline());\r\n \r\n for(let i=0;i (dist[0]))cnt++;\r\n }\r\n \r\n print(cnt);\r\n }"}, {"source_code": "\"use strict\";\r\n \r\n let t = +(readline());\r\n \r\n for(let i=0;i +dist[0])cnt++;\r\n }\r\n print(dist[0]);\r\n print(cnt);\r\n }"}, {"source_code": "\"use strict\";\r\n \r\n let t = +(readline());\r\n \r\n for(let i=0;i dist[0])cnt++;\r\n }\r\n \r\n print(cnt);\r\n }"}, {"source_code": "\"use strict\";\r\n\r\n let t = +(readline());\r\n \r\n for(let i=0;i {\r\n const chunk_string = chunk.toString()\r\n const split = chunk_string.split('\\r\\n')\r\n split.forEach(e => {\r\n if (e.length == 1) e = Number(e)\r\n if (e.length > 1) e = e.split(' ').map(Number)\r\n state.data.push(e)\r\n })\r\n state.input_counter++\r\n}\r\nconst commit = (answer) => process.stdout.write(answer);\r\nconst main = (args) => {\r\n let { data } = state\r\n const size = data.shift()\r\n data = data.slice(0, size)\r\n const target = data.reduce((a, e, i) => [...a, e[0]], [])\r\n const sorted = data.map(e => Array.from(e).sort((a, b) => b - a))\r\n const results = sorted.map((e, i) => e.indexOf(target[i]))\r\n // console.log(results)\r\n results.forEach(e => commit(e + '\\r\\n'))\r\n return\r\n};\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "const state = { data: [] };\r\nconst consume = (chunk) => {\r\n const chunk_string = chunk.toString()\r\n const split = chunk_string.split('\\r\\n')\r\n split.forEach(e => {\r\n if (e.length == 1) e = Number(e)\r\n if (e.length > 1) e = e.split(' ').map(Number)\r\n state.data.push(e)\r\n })\r\n state.input_counter++\r\n}\r\nconst commit = (answer) => process.stdout.write(answer);\r\nconst main = (args) => {\r\n const { data } = state\r\n const size = data.shift()\r\n const target = data.reduce((a, e, i) => [...a, e[0]], [])\r\n const sorted = data.map(e => Array.from(e).sort((a, b) => b - a))\r\n const results = sorted.map((e, i) => e.indexOf(target[i]))\r\n // console.log(results)\r\n results.slice(0, size).forEach(e => commit(e + '\\r\\n'))\r\n return\r\n};\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "const state = { data: [] };\r\nconst consume = (chunk) => {\r\n const chunk_string = chunk.toString()\r\n const split = chunk_string.split('\\r\\n')\r\n split.forEach(e => {\r\n if (e.length == 1) e = Number(e)\r\n if (e.length > 1) e = e.split(' ').map(Number)\r\n state.data.push(e)\r\n })\r\n state.input_counter++\r\n}\r\nconst commit = (answer) => process.stdout.write(answer);\r\nconst main = (args) => {\r\n const { data } = state\r\n data.shift()\r\n const target = data.reduce((a, e, i) => [...a, e[0]], [])\r\n const sorted = data.map(e => Array.from(e).sort((a, b) => b - a))\r\n const results = sorted.map((e, i) => e.indexOf(target[i]))\r\n // console.log(results)\r\n results.forEach(e => commit(e + '\\r\\n'))\r\n return\r\n};\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "const state = { data: [] };\r\nconst consume = (chunk) => {\r\n const chunk_string = chunk.toString()\r\n const split = chunk_string.split('\\r\\n')\r\n split.forEach(e => {\r\n if (e.length == 1) e = Number(e)\r\n if (e.length > 1) e = e.split(' ').map(Number)\r\n state.data.push(e)\r\n })\r\n state.input_counter++\r\n}\r\nconst commit = (answer) => process.stdout.write(answer);\r\nconst main = (args) => {\r\n const { data } = state\r\n data.shift()\r\n const target = data.reduce((a, e, i) => [...a, e[0]], [])\r\n const sorted = data.map(e => Array.from(e).sort((a, b) => b - a))\r\n const results = sorted.map((e, i) => e.indexOf(target[i]))\r\n commit(results.join('\\r\\n'))\r\n};\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "var state = { data: [] };\r\nvar element, i, j = null;\r\nfunction consume(chunk) {\r\n try {\r\n var chunk_string = chunk.toString(\"utf-8\");\r\n var split = chunk_string.split('\\r\\n');\r\n for (i = 0; i < split.length; i++) {\r\n element = split[i];\r\n if (element.length == 1) {\r\n element = parseInt(element);\r\n }\r\n if (element.length > 1) {\r\n element = element.split(' ');\r\n for (j = 0; j < element.length; j++) {\r\n element[j] = parseInt(element[j]);\r\n }\r\n }\r\n state.data.push(element);\r\n }\r\n return;\r\n } catch (error) {\r\n process.stdout.write(error.message);\r\n }\r\n}\r\nfunction commit(answer) {\r\n try {\r\n process.stdout.write(answer);\r\n return;\r\n } catch (error) {\r\n process.stdout.write(error.message);\r\n }\r\n}\r\nfunction main() {\r\n try {\r\n\r\n var data = state.data;\r\n var target = [];\r\n var results = [];\r\n var sorted = [];\r\n // data.reduce((a, e, i) => [...a, e[0]], []);\r\n // sorted.map((e, i) => e.indexOf(target[i]));\r\n //data.map(e => e.sort((a, b) => b - a));\r\n // results.forEach(e => commit(e + '\\r\\n'));\r\n data.shift();\r\n for (i = 0; i < data.length; i++) {\r\n element = data[i];\r\n target.push(element[0]);\r\n }\r\n for (i = 0; i < data.length; i++) {\r\n element = data[i];\r\n sorted.push(element.sort((a, b) => b - a));\r\n }\r\n for (i = 0; i < sorted.length; i++) {\r\n element = sorted[i];\r\n results.push(element.indexOf(target[i]));\r\n }\r\n for (i = 0; i < results.length; i++) {\r\n const element = results[i];\r\n commit(element + '\\n');\r\n }\r\n return;\r\n } catch (error) {\r\n process.stdout.write(error.message);\r\n }\r\n}\r\nprocess.stdin\r\n .on(\"data\", consume)\r\n .on(\"end\", main);"}, {"source_code": "var readline = require('readline');\nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nconst read = () => new Promise(res => {\n rl.on('line', (line) => res(line));\n});\n\nasync function main()\n{\n const n = await read();\n for (let i = 0; i < n; i++) {\n const line = await read();\n const [timur, ...rest] = line.split(' ').map((n) => parseInt(n));\n process.stdout.write(`${rest.filter(n => n > timur).length}`);\n }\n}\n\nmain();"}], "src_uid": "e829ca4438e9cb30ea1c66eea7d5f7a7"} {"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$$$) — 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$$$) — the length of the array and its sum correspondingly.", "output_spec": "For each test case, print the answer — 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": "var x=parseInt(readline());\n\nwhile(x--){\n var arr=readline().split(' ').map(x => parseInt(x));\n if(arr[0]<=1)\n print(\"0\");\n else if(arr[0]===2)\n print(arr[1]);\n else\n print(2*arr[1]);\n\n}"}, {"source_code": "var testCaseCount = parseInt(readline());\n\nvar currentTestCase = 1;\n\nwhile(currentTestCase <= testCaseCount) {\n var input = readline().split(\" \");\n var n = parseInt(input[0]);\n var m = parseInt(input[1]);\n \n var result = findResult(n, m);\n \n print(result);\n \n currentTestCase += 1;\n}\n\nfunction findResult(n, m) {\n if (n < 2) {\n return 0;\n }\n \n if (n == 2) {\n return m;\n }\n \n return 2*m;\n}\n"}, {"source_code": "var t = parseInt(readline());\n\nfor (var tc = 0; tc < t; tc++) {\n var nm = readline()\n .split(\" \")\n .map((val) => parseInt(val));\n var n = nm[0],\n m = nm[1];\n if (n == 2) print(m);\n else if (n == 1) print(0);\n else print(m * 2);\n}\n"}, {"source_code": "var testCases = readline();\nfor(var i =0; i< testCases; i++) {\n var line = readline().split(\" \");\n var arrayLength = line[0], arraySum = line[1];\n print( arrayLength >= 3? arraySum*2: (arrayLength == 1? 0 : arraySum));\n}\n"}, {"source_code": "var testCases = readline();\n\nfor(var i =0; i< testCases; i++) {\n var line = readline().split(\" \");\n var arrayLength = line[0], arraySum = line[1];\n if(arrayLength >= 3) {\n print(arraySum*2)\n } else {\n if(arrayLength == 1) {\n print(0);\n } \n else {\n print(arraySum);\n }\n }\n}\n"}, {"source_code": "for(var t=Number(readline());t;t--){\n var a = readline().trim().split(/\\s/).map(x=>Number(x));\n print((a[0]==1)?0:(a[0]==2)?a[1]:2*a[1]);\n}\n"}, {"source_code": "function solve(n,m) {\n if (n == 1) return 0;\n if (n == 2) return m;\n return 2*m;\n}\nvar tc = Number(readline())\nwhile (tc--) {\n var inputArr = readline().split(\" \").map(function(a) { return +a })\n var n = inputArr[0]\n var m = inputArr[1]\n print(solve(n,m))\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', () => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction main() {\n //console.log(\"inputString\", inputString)\n \n //console.log(\"typeof inputString\", typeof inputString)\n const tests = inputString.slice(1).map(item => item.split(\" \").map(Number));\n \n //console.log(\"tests\", tests);\n \n let result = [];\n \n for (let i = 0; i < tests.length; i++) {\n //console.log(\"tests[i]\", tests[i]);\n const [n, m] = tests[i];\n \n if (n === 1) {\n result.push(0);\n } else if (n === 2) {\n result.push(m);\n } else {\n result.push(m * 2);\n }\n }\n \n result.forEach(item => console.log(item));\n}"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => string.trim());\n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n \n\nlet main = () => {\n let t = parseInt(readline());\n while( t > 0 ){\n \tlet [n, m] = readline().split(\" \").map(Number);\n \tif( n === 1 )\n \t\tconsole.log(0);\n \telse if( n === 2 )\n \t\tconsole.log(m);\n \telse\n \t\tconsole.log(2*m);\n \tt = t-1;\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n/*****************************************************************/\nfunction main() {\n let t = readLine();\n t = parseInt(t);\n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let n = parseInt(line[0]);\n let m = parseInt(line[1]);\n if(n === 1) {\n console.log(\"0\");\n } else if (n === 2) {\n console.log(m);\n } else {\n console.log(2*m);\n }\n }\n}"}, {"source_code": "'use strict';\n\nconst parseProblem = (line, problem) => {\n if (!problem.T || problem.T === 0) {\n problem.T = parseInt(line);\n return problem;\n }\n\n const cases = problem.cases;\n\n //if (cases.length === 0 || cases[cases.length - 1].arr) {\n cases.push({\n s: line\n });\n /*} else {\n cases[cases.length - 1].arr = line;\n }*/\n\n const isProcessing = cases.length < problem.T;// || !cases[cases.length - 1].arr;\n problem.isProcessing = isProcessing;\n\n return problem;\n};\n\nconst solve = data => {\n const [n, m] = data.s.split(' ').map(i => +i);\n let sum = (n == 1) ? 0 : m;\n\n if(n > 2) {\n sum = 2 * m;\n }\n \n return sum;\n}\n\nconst solveCases = cases => {\n for (let index = 0; index < cases.length; index++) {\n const result = solve(cases[index]);\n console.log(result);\n }\n};\n\nconst main = () => {\n const readline = require('readline');\n\n let problem = {\n T: 0,\n cases: [],\n isProcessing: true\n };\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n rl.on('line', line => {\n problem = parseProblem(line, problem);\n\n if (!problem.isProcessing) {\n rl.close();\n }\n }).on('close', () => {\n solveCases(problem.cases);\n process.exit(0);\n });\n};\n\nif (!module.parent) {\n main();\n}"}, {"source_code": "const readline = require('readline');\n \nconst rl = readline.createInterface({\n input: process.stdin\n});\nrl.on('line', (line) => {\n const l = line.split(' ').map(v => +v);\n if (l.length > 1) {\n if (l[0] === 1) {\n process.stdout.write(`0\\n`);\n } else if (l[0] === 2) {\n process.stdout.write(`${l[1]}\\n`);\n } else if (l[0] > 2) {\n process.stdout.write(`${l[1] * 2}\\n`);\n }\n }\n});"}, {"source_code": "var read = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar obj;\nvar inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n myerr(\"-----start-----\");\n var start = new Date();\n Main();\n var end = new Date() - start;\n myerr(\"----- end -----\");\n myerr(\"time : \" + (end) + \"ms\");\n});\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n var returnObj = {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(!this.hasNext()){throw \"ArrayIndexOutOfBoundsException これ以上ないよ\";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}\n };\n return returnObj;\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//[no]要素の扱い。数値型\n//不明値、異常時:引数そのまま返す 1:数値へ変換\n//2:半角SPで分割 4:半角SPで分割し、数値配列へ\n//6:1文字で分割 7:1文字で分割し、数値配列へ\n//8:半角SPで結合 9:改行で結合 0:文字なしで結合\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\nfunction Main(){\n\tvar t = nextInt();\n\tvar output = new Array(t);\n\tfor(var i = 0; i < t; i++){\n\t\tvar one = nextIntArray();\n\t\tvar N = one[0];\n\t\tif(N == 1){\n\t\t\toutput[i] = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tvar M = one[1];\n\t\tif(N == 2){\n\t\t\toutput[i] = M;\n\t\t}else{\n\t\t\toutput[i] = M * 2;\n\t\t}\n\t}\n\tmyout(myconv(output,9));\n}"}, {"source_code": "// 5\n// 1 100\n// 2 2\n// 5 5\n// 2 1000000000\n// 1000000000 1000000000\n\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n\nfunction writeLine(str) {\n process.stdout.write(`${str}\\n`);\n}\n\nfunction main() {\n let t = Number(readLine());\n while(t--) {\n const [n, m] = readLine().split(' ').map(num => Number(num));\n if (n == 1) {\n writeLine(0);\n } else if (n == 2) {\n writeLine(m);\n } else {\n writeLine(m*2);\n }\n }\n}\n\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => string.trim());\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\n\nfunction main() {\n const n = parseInt(readline());\n const pairs = [];\n for (let i = 0; i < n; i++) {\n pairs.push(readline().split(' ').map(o => parseInt(o)));\n }\n\n pairs.forEach(([n, m]) => {\n if (n === 1) {\n console.log(0);\n } else if (n === 2) {\n console.log(m);\n } else {\n console.log(m * 2);\n }\n })\n}\n"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const [n, m] = d.split(\" \").map(Number);\n\n console.log(Math.min(2, n - 1) * m);\n\n // if (n === 1) {\n // console.log(0);\n // return;\n // }\n\n // if (n === 2) {\n // console.log(m);\n // return;\n // }\n\n // console.log(m * 2);\n c++;\n});\n"}, {"source_code": "const readline = require(\"readline\");\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nlet c = 0;\n\nrl.on(\"line\", (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const [n, m] = d.split(\" \").map(Number);\n\n if (n === 1) {\n console.log(0);\n return;\n }\n\n if (n === 2) {\n console.log(m);\n return;\n }\n\n console.log(m * 2);\n c++;\n});\n"}, {"source_code": "const processData = (lines) => {\n const n = +lines[0]\n for (let i=0; i +x)\n if (n === 1) {\n console.log(0)\n } else {\n if (n === 2) {\n console.log(m)\n } else {\n console.log(m * 2)\n }\n }\n }\n}\n\nlet i = ''\nprocess.stdin.on('data', c => i += c)\nprocess.stdin.on('end', () => {\n const {EOL} = require('os')\n const lines = i.split(EOL) /*your input text, split by lines*/\n processData(lines)\n})\n"}, {"source_code": "// node template.js < A-small.in > A-small.out\n\nfunction main() {\n var tests = 1;\n tests = nextInt();\n\n for (let t = 1; t <= tests; t++) {\n let N = nextInt(), M = nextInt();\n\n let result = 0;\n if (N>1) result = M;\n if (N>2) result = M*2;\n\n print(result);\n }\n}\n\n// ------- Template ------------------\nfunction newTensor(dimensions, value) {\n let res = [];\n let dim = dimensions[0], subdim = dimensions.slice(1);\n if (subdim.length == 0) {\n for(let i = 0; i < dim; i++) {\n res.push(value);\n }\n } else {\n for(let i = 0; i < dim; i++) {\n res.push(newTensor(subdim, value));\n }\n }\n return res;\n}\n\nif (!String.prototype.startsWith) {\n Object.defineProperty(String.prototype, 'startsWith', {\n value: function(search, rawPos) {\n var pos = rawPos > 0 ? rawPos|0 : 0;\n return this.substring(pos, pos + search.length) === search;\n }\n });\n}\nif (!String.prototype.endsWith) {\n String.prototype.endsWith = function(search, this_len) {\n if (this_len === undefined || this_len > this.length) {\n this_len = this.length;\n }\n return this.substring(this_len - search.length, this_len) === search;\n };\n}\n\nvar curTokens = [], curToken = 0;\n\nfunction next() {\n while (curToken >= curTokens.length) {\n curTokens = readline().split(/[\\s]+/);\n curToken = 0;\n }\n return curTokens[curToken++];\n}\n\nfunction nextInt() {\n return parseInt(next());\n}\n\n// code for nodejs\nvar inputBuffer = '', curLine = 0;\n\nfunction readline() {\n return inputBuffer[curLine++];\n}\n\nfunction print(data) {\n process.stdout.write(data + '\\n');\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n inputBuffer += chunk;\n});\n\nprocess.stdin.on('end', function () {\n inputBuffer = inputBuffer.split(/[\\s]+/);\n main();\n});"}, {"source_code": "// Sample code to perform I/O:\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\nvar stdin_input = \"\";\n\nprocess.stdin.on(\"data\", function (input) {\n stdin_input += input; // Reading input from STDIN\n});\n\nprocess.stdin.on(\"end\", function () {\n main(stdin_input);\n});\n\n/**\n * \n * @param {*} str \n * @param {*} seperator \n */\nfunction splitter(str, seperator = '') {\n return str.trim().split(seperator);\n}\n\n/**\n * \n * @param {*} arr \n */\nfunction strToNumArr(arr = []) {\n return arr.map(num => Number(num));\n}\n\n/**\n * \n * @param {*} num1 \n * @param {*} num2 \n */\nfunction matrixArray(num1, num2) {\n return Array(num1).fill(Array(num2));\n}\n\nlet log = function () {\n return Function.prototype.bind.call(console.log, console, '');\n}();\n\nfunction removeEmptyItem(arr, index) {\n return arr.slice(0, index).concat(arr.slice(index + 1, arr.length));\n}\n\nfunction range(min, max) {\n\n let arr = [];\n for (let index = min; index < max; index++) {\n arr.push(index);\n\n }\n return arr;\n}\n\nfunction main(input) {\n let output = nameLookUp(input);\n // process.stdout.write(output); // Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\n// Write your code here\nfunction nameLookUp(str) {\n\n let inputs = str.split('\\n');\n let t = +inputs[0].trim();\n for (let index = 1; index <= t; index++) {\n const element = inputs[index].trim().split(' ');\n let n = +element[0];\n let sum = +element[1];\n if (n > 2) {\n console.log(2 * sum);\n }\n else {\n console.log((n - 1) * sum);\n }\n }\n\n}\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 6\n1\n2\n3\n4\n5\n6\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', () => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction main() {\n console.log(\"inputString\", inputString)\n \n //console.log(\"typeof inputString\", typeof inputString)\n const tests = inputString.slice(1).map(item => item.split(\" \").map(Number));\n \n //console.log(\"tests\", tests);\n \n let result = [];\n \n for (let i = 0; i < tests.length; i++) {\n //console.log(\"tests[i]\", tests[i]);\n const [n, m] = tests[i];\n \n if (n === 1) {\n result.push(0);\n } else if (n === 2) {\n result.push(m);\n } else {\n result.push(m * 2);\n }\n }\n \n result.forEach(item => console.log(item));\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\n\nvar input_stdin = \"\";\nvar input_stdin_array = \"\";\nvar input_currentline = 0;\n\nprocess.stdin.on(\"data\", chunk => input_stdin += chunk.trim());\n\nprocess.stdin.on(\"end\", () => {\n input_stdin_array = input_stdin.trim().split(\"\\n\").map(str => str.trim());\n main()\n})\n\nreadLine = () => {\n return input_stdin_array[input_currentline++];\n}\n\nmain = () => {\n let t = parseInt(readLine());\n while( t-- ){\n \tlet [n, m] = readLine().split(\" \").map(x => parseInt(x));\n \tif( n === 1 )\n \t\tconsole.log(0);\n \telse if( n === 2 )\n \t\tconsole.log(m);\n \telse\n \t\tconsole.log(2*m);\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\n\nvar input_stdin = \"\";\nvar input_stdin_array = \"\";\nvar input_currentline = 0;\n\nprocess.stdin.on(\"data\", chunk => input_stdin += chunk.trim());\n\nprocess.stdin.on(\"end\", () => {\n input_stdin_array = input_stdin.trim().split(\"\\n\").map(str => str.trim());\n main()\n})\n\nreadLine = () => {\n return input_stdin_array[input_currentline++];\n}\n\nmain = () => {\n let t = parseInt(readLine());\n while( t > 0 ){\n \tlet [n, m] = readLine().split(\" \").map(Number);\n \tif( n === 1 )\n \t\tconsole.log(0);\n \telse if( n === 2 )\n \t\tconsole.log(m);\n \telse\n \t\tconsole.log(2*m);\n \tt = t-1;\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\n\nvar input_stdin = \"\";\nvar input_stdin_array = \"\";\nvar input_currentline = 0;\n\nprocess.stdin.on(\"data\", chunk => input_stdin += chunk.trim());\n\nprocess.stdin.on(\"end\", () => {\n input_stdin_array = input_stdin.trim().split(\"\\n\").map(str => str.trim());\n main()\n})\n\nreadLine = () => {\n return input_stdin_array[input_currentline++];\n}\n\nmain = () => {\n let t = parseInt(readLine());\n while( t > 0 ){\n \tlet [n, m] = readLine().split(\" \").map(x => parseInt(x));\n \tif( n === 1 )\n \t\tconsole.log(0);\n \telse if( n === 2 )\n \t\tconsole.log(m);\n \telse\n \t\tconsole.log(2*m);\n \tt = t-1;\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"ascii\");\n\nvar input_stdin = \"\";\nvar input_stdin_array = \"\";\nvar input_currentline = 0;\n\nprocess.stdin.on(\"data\", chunk => input_stdin += chunk.trim());\n\nprocess.stdin.on(\"end\", () => {\n input_stdin_array = input_stdin.trim().split(\"\\n\").map(str => str.trim());\n main()\n})\n\nreadLine = () => {\n return input_stdin_array[input_currentline++].trim();\n}\n\nmain = () => {\n let t = parseInt(readLine());\n while( t > 0 ){\n \tlet [n, m] = readLine().split(\" \").map(x => parseInt(x));\n \tif( n === 1 )\n \t\tconsole.log(0);\n \telse if( n === 2 )\n \t\tconsole.log(m);\n \telse\n \t\tconsole.log(2*m);\n \tt = t-1;\n }\n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readLine() {\n return inputString[currentLine++];\n}\n/*****************************************************************/\nfunction main() {\n let t = readLine();\n t = parseInt(t);\n console.log(\"mai yahan aaya\")\n while(t--) {\n let line = readLine();\n line = line.split(\" \");\n let n = parseInt(line[0]);\n let m = parseInt(line[1]);\n if(n === 1) {\n console.log(\"0\");\n } else if (n === 2) {\n console.log(m);\n } else {\n console.log(2*m);\n }\n }\n}"}, {"source_code": "'use strict';\n\nconst parseProblem = (line, problem) => {\n if (!problem.T || problem.T === 0) {\n problem.T = parseInt(line);\n return problem;\n }\n\n const cases = problem.cases;\n\n //if (cases.length === 0 || cases[cases.length - 1].arr) {\n cases.push({\n s: line\n });\n /*} else {\n cases[cases.length - 1].arr = line;\n }*/\n\n const isProcessing = cases.length < problem.T;// || !cases[cases.length - 1].arr;\n problem.isProcessing = isProcessing;\n\n return problem;\n};\n\nconst solve = data => {\n const [n, m] = data.s.split(' ').map(i => +i);\n let sum = (n == 1) ? 0 : m;\n\n if(m == n && n > 2) {\n sum = 2 * m;\n }\n \n return sum;\n}\n\nconst solveCases = cases => {\n for (let index = 0; index < cases.length; index++) {\n const result = solve(cases[index]);\n console.log(result);\n }\n};\n\nconst main = () => {\n const readline = require('readline');\n\n let problem = {\n T: 0,\n cases: [],\n isProcessing: true\n };\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n rl.on('line', line => {\n problem = parseProblem(line, problem);\n\n if (!problem.isProcessing) {\n rl.close();\n }\n }).on('close', () => {\n solveCases(problem.cases);\n process.exit(0);\n });\n};\n\nif (!module.parent) {\n main();\n}"}, {"source_code": "const readline = require('readline');\n \nconst rl = readline.createInterface({\n input: process.stdin\n});\nrl.on('line', (line) => {\n const l = line.split(' ').map(v => +v);\n if (l.length > 1) {\n if (l[0] === 1) {\n process.stdout.write(`0\\n`);\n } else if (l[0] === 2) {\n process.stdout.write(`${l[1]}\\n`);\n } else if (l[0] > 2) {\n process.stdout.write(`${l[1] + l[0]}\\n`);\n }\n }\n});"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n1 100\n2 2\n5 5\n2 1000000000\n1000000000 1000000000\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 5\n1 100\n2 2\n5 5\n2 1000000000\n1000000000 1000000000\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n let range = readline();\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n 6\n1\n2\n3\n4\n5\n6\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() {\n let range = readline();\n\n for(let r=0;ro[s]^n?1:-1;return u==l?0:l(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else rd?e.c=e.e=null:e.c=n=a.length){if(!t)break e;for(;a.length<=l;a.push(0));u=c=0,s=(o%=M)-M+(i=1)}else{for(u=f=a[l],i=1;10<=f;f/=10,i++);c=(s=(o%=M)-M+i)<0?0:u/h[i-s-1]%10|0}if(t=t||r<0||null!=a[l+1]||(s<0?u:u%h[i-s-1]),t=n<4?(c||t)&&(0==n||n==(e.s<0?3:2)):5d?e.c=e.e=null:e.e>>11))?(n=crypto.getRandomValues(new Uint32Array(2)),r[s]=n[0],r[s+1]=n[1]):(f.push(o%1e14),s+=2);s=i/2}else{if(!crypto.randomBytes)throw O=!1,Error(U+\"crypto unavailable\");for(r=crypto.randomBytes(i*=7);sn-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(e,r,n,t,i){var o,s,f,u,l,c,a,h,p=e.indexOf(\".\"),g=y,w=N;for(0<=p&&(u=b,b=0,e=e.replace(\".\",\"\"),c=(h=new _(r)).pow(e.length-p),b=u,h.c=d(X($(c.c),c.e,\"0\"),10,n,m),h.e=h.c.length),f=u=(a=d(e,r,n,i?(o=A,m):(o=m,A))).length;0==a[--u];a.pop());if(!a[0])return o.charAt(0);if(p<0?--f:(c.c=a,c.e=f,c.s=t,a=(c=v(c,h,g,w,n)).c,l=c.r,f=c.e),p=a[s=f+g+1],u=n/2,l=l||s<0||null!=a[s+1],l=w<4?(null!=p||l)&&(0==w||w==(c.s<0?3:2)):un;)a[s]=0,s||(++f,a=[1].concat(a));for(u=a.length;!a[--u];);for(p=0,e=\"\";p<=u;e+=o.charAt(a[p++]));e=X(e,f,o.charAt(0))}return e}}(),v=function(){function S(e,r,n){var t,i,o,s,f=0,u=e.length,l=r%k,c=r/k|0;for(e=e.slice();u--;)f=((i=l*(o=e[u]%k)+(t=c*o+(s=e[u]/k|0)*l)%k*k+f)/n|0)+(t/k|0)+c*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function R(e,r,n,t){var i,o;if(n!=t)o=tr[i]?1:-1;break}return o}function P(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n](E[f]||0)&&s--,b<0)p.push(1),u=!0;else{for(v=E.length,N=A.length,b+=2,1<(l=T(i/(A[f=0]+1)))&&(A=S(A,l,i),E=S(E,l,i),N=A.length,v=E.length),d=N,w=(g=E.slice(0,N)).length;w=i/2&&y++;do{if(l=0,(o=R(A,g,N,w))<0){if(m=g[0],N!=w&&(m=m*i+(g[1]||0)),1<(l=T(m/y)))for(i<=l&&(l=i-1),a=(c=S(A,l,i)).length,w=g.length;1==R(c,g,a,w);)l--,P(c,No&&(l.c.length=o):t&&(l=l.mod(r))}if(i){if(0===(i=T(i/2)))break;u=i%2}else if(x(e=e.times(n),e.e+1,1),14o&&(c.c.length=o):t&&(c=c.mod(r))}return t?l:(f&&(l=w.div(l)),r?l.mod(r):o?x(l,b,N,void 0):l)},t.integerValue=function(e){var r=new _(this);return null==e?e=N:H(e,0,8),x(r,r.e+1,e)},t.isEqualTo=t.eq=function(e,r){return 0===z(this,new _(e,r))},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(e,r){return 0this.c.length-2},t.isLessThan=t.lt=function(e,r){return z(this,new _(e,r))<0},t.isLessThanOrEqualTo=t.lte=function(e,r){return-1===(r=z(this,new _(e,r)))||0===r},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return 0t&&(t=this.e+1),t},t.shiftedBy=function(e){return H(e,-G,G),this.times(\"1e\"+e)},t.squareRoot=t.sqrt=function(){var e,r,n,t,i,o=this,s=o.c,f=o.s,u=o.e,l=y+4,c=new _(\"0.5\");if(1!==f||!s||!s[0])return new _(!f||f<0&&(!s||s[0])?NaN:s?o:1/0);if((n=0==(f=Math.sqrt(+D(o)))||f==1/0?(((r=$(s)).length+u)%2==0&&(r+=\"0\"),f=Math.sqrt(+r),u=j((u+1)/2)-(u<0||u%2),new _(r=f==1/0?\"1e\"+u:(r=f.toExponential()).slice(0,r.indexOf(\"e\")+1)+u)):new _(f+\"\")).c[0])for((f=(u=n.e)+l)<3&&(f=0);;)if(i=n,n=c.times(i.plus(v(o,i,l,1))),$(i.c).slice(0,f)===(r=$(n.c)).slice(0,f)){if(n.e {\n if (l == 0) { l++ }\n else {\n rl.close();\n let strArray = input.split(\" \")\n let s = strArray.map(function (item) {\n return BN(item);\n });\n let res = []\n let n = s.length * 2\n res[0] = BN(0)\n res[n - 1] = s[0]\n for (let i = 1; i < s.length; i++) {\n if (s[i].minus(res[i - 1]).gt(res[n - (i - 1) - 1])) {\n\n res[i] = s[i].minus(res[n - (i - 1) - 1])\n if (res[i - 1].gt(res[i])) {\n res[i] = res[i].minus(res[i - 1])\n }\n res[n - i - 1] = s[i].minus(res[i])\n\n } else {\n res[i] = res[i - 1]\n res[n - i - 1] = s[i].minus(res[i - 1])\n }\n }\n console.log(res.join(\" \"))\n return 0;\n }\n});"}, {"source_code": "\nfunction main() {\n\n const BN = module.exports.BigNumber;\n\n var n = stdin[0];\n n = parseInt(n);\n\n var b = stdin[1].split(' ').map( (s) => { return BN(s); });\n \n var a = [];\n a[0] = 0;\n a[n-1] = b[0];\n\n for(var i=1 ; io[s]^n?1:-1;return u==l?0:l(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else rd?e.c=e.e=null:e.c=n=a.length){if(!t)break e;for(;a.length<=l;a.push(0));u=c=0,s=(o%=M)-M+(i=1)}else{for(u=f=a[l],i=1;10<=f;f/=10,i++);c=(s=(o%=M)-M+i)<0?0:u/h[i-s-1]%10|0}if(t=t||r<0||null!=a[l+1]||(s<0?u:u%h[i-s-1]),t=n<4?(c||t)&&(0==n||n==(e.s<0?3:2)):5d?e.c=e.e=null:e.e>>11))?(n=crypto.getRandomValues(new Uint32Array(2)),r[s]=n[0],r[s+1]=n[1]):(f.push(o%1e14),s+=2);s=i/2}else{if(!crypto.randomBytes)throw O=!1,Error(U+\"crypto unavailable\");for(r=crypto.randomBytes(i*=7);sn-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(e,r,n,t,i){var o,s,f,u,l,c,a,h,p=e.indexOf(\".\"),g=y,w=N;for(0<=p&&(u=b,b=0,e=e.replace(\".\",\"\"),c=(h=new _(r)).pow(e.length-p),b=u,h.c=d(X($(c.c),c.e,\"0\"),10,n,m),h.e=h.c.length),f=u=(a=d(e,r,n,i?(o=A,m):(o=m,A))).length;0==a[--u];a.pop());if(!a[0])return o.charAt(0);if(p<0?--f:(c.c=a,c.e=f,c.s=t,a=(c=v(c,h,g,w,n)).c,l=c.r,f=c.e),p=a[s=f+g+1],u=n/2,l=l||s<0||null!=a[s+1],l=w<4?(null!=p||l)&&(0==w||w==(c.s<0?3:2)):un;)a[s]=0,s||(++f,a=[1].concat(a));for(u=a.length;!a[--u];);for(p=0,e=\"\";p<=u;e+=o.charAt(a[p++]));e=X(e,f,o.charAt(0))}return e}}(),v=function(){function S(e,r,n){var t,i,o,s,f=0,u=e.length,l=r%k,c=r/k|0;for(e=e.slice();u--;)f=((i=l*(o=e[u]%k)+(t=c*o+(s=e[u]/k|0)*l)%k*k+f)/n|0)+(t/k|0)+c*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function R(e,r,n,t){var i,o;if(n!=t)o=tr[i]?1:-1;break}return o}function P(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n](E[f]||0)&&s--,b<0)p.push(1),u=!0;else{for(v=E.length,N=A.length,b+=2,1<(l=T(i/(A[f=0]+1)))&&(A=S(A,l,i),E=S(E,l,i),N=A.length,v=E.length),d=N,w=(g=E.slice(0,N)).length;w=i/2&&y++;do{if(l=0,(o=R(A,g,N,w))<0){if(m=g[0],N!=w&&(m=m*i+(g[1]||0)),1<(l=T(m/y)))for(i<=l&&(l=i-1),a=(c=S(A,l,i)).length,w=g.length;1==R(c,g,a,w);)l--,P(c,No&&(l.c.length=o):t&&(l=l.mod(r))}if(i){if(0===(i=T(i/2)))break;u=i%2}else if(x(e=e.times(n),e.e+1,1),14o&&(c.c.length=o):t&&(c=c.mod(r))}return t?l:(f&&(l=w.div(l)),r?l.mod(r):o?x(l,b,N,void 0):l)},t.integerValue=function(e){var r=new _(this);return null==e?e=N:H(e,0,8),x(r,r.e+1,e)},t.isEqualTo=t.eq=function(e,r){return 0===z(this,new _(e,r))},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(e,r){return 0this.c.length-2},t.isLessThan=t.lt=function(e,r){return z(this,new _(e,r))<0},t.isLessThanOrEqualTo=t.lte=function(e,r){return-1===(r=z(this,new _(e,r)))||0===r},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return 0t&&(t=this.e+1),t},t.shiftedBy=function(e){return H(e,-G,G),this.times(\"1e\"+e)},t.squareRoot=t.sqrt=function(){var e,r,n,t,i,o=this,s=o.c,f=o.s,u=o.e,l=y+4,c=new _(\"0.5\");if(1!==f||!s||!s[0])return new _(!f||f<0&&(!s||s[0])?NaN:s?o:1/0);if((n=0==(f=Math.sqrt(+D(o)))||f==1/0?(((r=$(s)).length+u)%2==0&&(r+=\"0\"),f=Math.sqrt(+r),u=j((u+1)/2)-(u<0||u%2),new _(r=f==1/0?\"1e\"+u:(r=f.toExponential()).slice(0,r.indexOf(\"e\")+1)+u)):new _(f+\"\")).c[0])for((f=(u=n.e)+l)<3&&(f=0);;)if(i=n,n=c.times(i.plus(v(o,i,l,1))),$(i.c).slice(0,f)===(r=$(n.c)).slice(0,f)){if(n.e { return BN(s); });\n \n var a = [];\n a[0] = 0;\n a[n-1] = b[0];\n\n for(var i=1 ; io[s]^n?1:-1;return u==l?0:l(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else rd?e.c=e.e=null:e.c=n=a.length){if(!t)break e;for(;a.length<=l;a.push(0));u=c=0,s=(o%=M)-M+(i=1)}else{for(u=f=a[l],i=1;10<=f;f/=10,i++);c=(s=(o%=M)-M+i)<0?0:u/h[i-s-1]%10|0}if(t=t||r<0||null!=a[l+1]||(s<0?u:u%h[i-s-1]),t=n<4?(c||t)&&(0==n||n==(e.s<0?3:2)):5d?e.c=e.e=null:e.e>>11))?(n=crypto.getRandomValues(new Uint32Array(2)),r[s]=n[0],r[s+1]=n[1]):(f.push(o%1e14),s+=2);s=i/2}else{if(!crypto.randomBytes)throw O=!1,Error(U+\"crypto unavailable\");for(r=crypto.randomBytes(i*=7);sn-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(e,r,n,t,i){var o,s,f,u,l,c,a,h,p=e.indexOf(\".\"),g=y,w=N;for(0<=p&&(u=b,b=0,e=e.replace(\".\",\"\"),c=(h=new _(r)).pow(e.length-p),b=u,h.c=d(X($(c.c),c.e,\"0\"),10,n,m),h.e=h.c.length),f=u=(a=d(e,r,n,i?(o=A,m):(o=m,A))).length;0==a[--u];a.pop());if(!a[0])return o.charAt(0);if(p<0?--f:(c.c=a,c.e=f,c.s=t,a=(c=v(c,h,g,w,n)).c,l=c.r,f=c.e),p=a[s=f+g+1],u=n/2,l=l||s<0||null!=a[s+1],l=w<4?(null!=p||l)&&(0==w||w==(c.s<0?3:2)):un;)a[s]=0,s||(++f,a=[1].concat(a));for(u=a.length;!a[--u];);for(p=0,e=\"\";p<=u;e+=o.charAt(a[p++]));e=X(e,f,o.charAt(0))}return e}}(),v=function(){function S(e,r,n){var t,i,o,s,f=0,u=e.length,l=r%k,c=r/k|0;for(e=e.slice();u--;)f=((i=l*(o=e[u]%k)+(t=c*o+(s=e[u]/k|0)*l)%k*k+f)/n|0)+(t/k|0)+c*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function R(e,r,n,t){var i,o;if(n!=t)o=tr[i]?1:-1;break}return o}function P(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n](E[f]||0)&&s--,b<0)p.push(1),u=!0;else{for(v=E.length,N=A.length,b+=2,1<(l=T(i/(A[f=0]+1)))&&(A=S(A,l,i),E=S(E,l,i),N=A.length,v=E.length),d=N,w=(g=E.slice(0,N)).length;w=i/2&&y++;do{if(l=0,(o=R(A,g,N,w))<0){if(m=g[0],N!=w&&(m=m*i+(g[1]||0)),1<(l=T(m/y)))for(i<=l&&(l=i-1),a=(c=S(A,l,i)).length,w=g.length;1==R(c,g,a,w);)l--,P(c,No&&(l.c.length=o):t&&(l=l.mod(r))}if(i){if(0===(i=T(i/2)))break;u=i%2}else if(x(e=e.times(n),e.e+1,1),14o&&(c.c.length=o):t&&(c=c.mod(r))}return t?l:(f&&(l=w.div(l)),r?l.mod(r):o?x(l,b,N,void 0):l)},t.integerValue=function(e){var r=new _(this);return null==e?e=N:H(e,0,8),x(r,r.e+1,e)},t.isEqualTo=t.eq=function(e,r){return 0===z(this,new _(e,r))},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(e,r){return 0this.c.length-2},t.isLessThan=t.lt=function(e,r){return z(this,new _(e,r))<0},t.isLessThanOrEqualTo=t.lte=function(e,r){return-1===(r=z(this,new _(e,r)))||0===r},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return 0t&&(t=this.e+1),t},t.shiftedBy=function(e){return H(e,-G,G),this.times(\"1e\"+e)},t.squareRoot=t.sqrt=function(){var e,r,n,t,i,o=this,s=o.c,f=o.s,u=o.e,l=y+4,c=new _(\"0.5\");if(1!==f||!s||!s[0])return new _(!f||f<0&&(!s||s[0])?NaN:s?o:1/0);if((n=0==(f=Math.sqrt(+D(o)))||f==1/0?(((r=$(s)).length+u)%2==0&&(r+=\"0\"),f=Math.sqrt(+r),u=j((u+1)/2)-(u<0||u%2),new _(r=f==1/0?\"1e\"+u:(r=f.toExponential()).slice(0,r.indexOf(\"e\")+1)+u)):new _(f+\"\")).c[0])for((f=(u=n.e)+l)<3&&(f=0);;)if(i=n,n=c.times(i.plus(v(o,i,l,1))),$(i.c).slice(0,f)===(r=$(n.c)).slice(0,f)){if(n.eo[s]^n?1:-1;return u==l?0:l(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else rd?e.c=e.e=null:e.c=n=a.length){if(!t)break e;for(;a.length<=l;a.push(0));u=c=0,s=(o%=M)-M+(i=1)}else{for(u=f=a[l],i=1;10<=f;f/=10,i++);c=(s=(o%=M)-M+i)<0?0:u/h[i-s-1]%10|0}if(t=t||r<0||null!=a[l+1]||(s<0?u:u%h[i-s-1]),t=n<4?(c||t)&&(0==n||n==(e.s<0?3:2)):5d?e.c=e.e=null:e.e>>11))?(n=crypto.getRandomValues(new Uint32Array(2)),r[s]=n[0],r[s+1]=n[1]):(f.push(o%1e14),s+=2);s=i/2}else{if(!crypto.randomBytes)throw O=!1,Error(U+\"crypto unavailable\");for(r=crypto.randomBytes(i*=7);sn-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(e,r,n,t,i){var o,s,f,u,l,c,a,h,p=e.indexOf(\".\"),g=y,w=N;for(0<=p&&(u=b,b=0,e=e.replace(\".\",\"\"),c=(h=new _(r)).pow(e.length-p),b=u,h.c=d(X($(c.c),c.e,\"0\"),10,n,m),h.e=h.c.length),f=u=(a=d(e,r,n,i?(o=A,m):(o=m,A))).length;0==a[--u];a.pop());if(!a[0])return o.charAt(0);if(p<0?--f:(c.c=a,c.e=f,c.s=t,a=(c=v(c,h,g,w,n)).c,l=c.r,f=c.e),p=a[s=f+g+1],u=n/2,l=l||s<0||null!=a[s+1],l=w<4?(null!=p||l)&&(0==w||w==(c.s<0?3:2)):un;)a[s]=0,s||(++f,a=[1].concat(a));for(u=a.length;!a[--u];);for(p=0,e=\"\";p<=u;e+=o.charAt(a[p++]));e=X(e,f,o.charAt(0))}return e}}(),v=function(){function S(e,r,n){var t,i,o,s,f=0,u=e.length,l=r%k,c=r/k|0;for(e=e.slice();u--;)f=((i=l*(o=e[u]%k)+(t=c*o+(s=e[u]/k|0)*l)%k*k+f)/n|0)+(t/k|0)+c*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function R(e,r,n,t){var i,o;if(n!=t)o=tr[i]?1:-1;break}return o}function P(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n](E[f]||0)&&s--,b<0)p.push(1),u=!0;else{for(v=E.length,N=A.length,b+=2,1<(l=T(i/(A[f=0]+1)))&&(A=S(A,l,i),E=S(E,l,i),N=A.length,v=E.length),d=N,w=(g=E.slice(0,N)).length;w=i/2&&y++;do{if(l=0,(o=R(A,g,N,w))<0){if(m=g[0],N!=w&&(m=m*i+(g[1]||0)),1<(l=T(m/y)))for(i<=l&&(l=i-1),a=(c=S(A,l,i)).length,w=g.length;1==R(c,g,a,w);)l--,P(c,No&&(l.c.length=o):t&&(l=l.mod(r))}if(i){if(0===(i=T(i/2)))break;u=i%2}else if(x(e=e.times(n),e.e+1,1),14o&&(c.c.length=o):t&&(c=c.mod(r))}return t?l:(f&&(l=w.div(l)),r?l.mod(r):o?x(l,b,N,void 0):l)},t.integerValue=function(e){var r=new _(this);return null==e?e=N:H(e,0,8),x(r,r.e+1,e)},t.isEqualTo=t.eq=function(e,r){return 0===z(this,new _(e,r))},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(e,r){return 0this.c.length-2},t.isLessThan=t.lt=function(e,r){return z(this,new _(e,r))<0},t.isLessThanOrEqualTo=t.lte=function(e,r){return-1===(r=z(this,new _(e,r)))||0===r},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return 0t&&(t=this.e+1),t},t.shiftedBy=function(e){return H(e,-G,G),this.times(\"1e\"+e)},t.squareRoot=t.sqrt=function(){var e,r,n,t,i,o=this,s=o.c,f=o.s,u=o.e,l=y+4,c=new _(\"0.5\");if(1!==f||!s||!s[0])return new _(!f||f<0&&(!s||s[0])?NaN:s?o:1/0);if((n=0==(f=Math.sqrt(+D(o)))||f==1/0?(((r=$(s)).length+u)%2==0&&(r+=\"0\"),f=Math.sqrt(+r),u=j((u+1)/2)-(u<0||u%2),new _(r=f==1/0?\"1e\"+u:(r=f.toExponential()).slice(0,r.indexOf(\"e\")+1)+u)):new _(f+\"\")).c[0])for((f=(u=n.e)+l)<3&&(f=0);;)if(i=n,n=c.times(i.plus(v(o,i,l,1))),$(i.c).slice(0,f)===(r=$(n.c)).slice(0,f)){if(n.e {\n if (l == 0) { l++ }\n else {\n rl.close();\n let strArray = input.split(\" \")\n let s = strArray.map(function (item) {\n return BN(item);\n });\n let res = []\n let n = s.length * 2\n res[0] = BN(0)\n res[n - 1] = s[0]\n for (let i = 1; i < s.length; i++) {\n if (s[i] - res[i - 1] > res[n - (i - 1) - 1]) {\n\n res[i] = s[i] - (res[n - (i - 1) - 1])\n if (res[i - 1] > res[i]) {\n res[i] -= res[i - 1]\n }\n res[n - i - 1] = s[i] - res[i]\n\n } else {\n res[i] = res[i - 1]\n res[n - i - 1] = s[i] - res[i - 1]\n }\n }\n console.log(res.join(\" \"))\n return 0;\n }\n});\n\n//4 5 4 4 3 4\n//0 1 1 1 1 2 2 2 3 3 4 4\n//0 1 1 1 1 2 3 3 4 4\n//0 1 1 1 1 1 3 2 3 3 4 4"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet l = 0;\nrl.on('line', (input) => {\n if (l == 0) { l++ }\n else {\n rl.close();\n let strArray = input.split(\" \")\n let s = strArray.map(function (item) {\n return parseInt(item, 10);\n });\n let res = []\n let n = s.length * 2\n res[0] = 0\n res[n - 1] = s[0]\n for (let i = 1; i < s.length; i++) {\n if (s[i] - res[i - 1] > res[n - (i - 1)-1]) {\n res[i] = s[i] - res[i - 1] - res[n - (i - 1)-1]\n res[n-i - 1] = s[i] - res[i]\n\n } else {\n res[i] = res[i - 1]\n res[n - i - 1] = s[i]-res[i-1]\n }\n }\n console.log(res)\n return 0;\n }\n});\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet l = 0;\nrl.on('line', (input) => {\n if (l == 0) { l++ }\n else {\n rl.close();\n let strArray = input.split(\" \")\n let s = strArray.map(function (item) {\n return parseInt(item, 10);\n });\n let res = []\n let n = s.length * 2\n res[0] = 0\n res[n - 1] = s[0]\n for (let i = 1; i < s.length; i++) {\n if (s[i] - res[i - 1] > res[n - (i - 1) - 1]) {\n\n res[i] = s[i] - (res[n - (i - 1) - 1])\n if (res[i - 1] > res[i]) {\n res[i] -= res[i - 1]\n }\n res[n - i - 1] = s[i] - res[i]\n\n } else {\n res[i] = res[i - 1]\n res[n - i - 1] = s[i] - res[i - 1]\n }\n }\n console.log(res.join(\" \"))\n return 0;\n }\n});\n\n//4 5 4 4 3 4\n//0 1 1 1 1 2 2 2 3 3 4 4\n//0 1 1 1 1 2 3 3 4 4\n//0 1 1 1 1 1 3 2 3 3 4 4\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n!function(e){\"use strict\";var r,L=/^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,B=Math.ceil,T=Math.floor,U=\"[BigNumber Error] \",I=U+\"Number primitive has more than 15 significant digits: \",C=1e14,M=14,G=9007199254740991,F=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],k=1e7,q=1e9;function j(e){var r=0|e;return 0o[s]^n?1:-1;return u==l?0:l(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else rd?e.c=e.e=null:e.c=n=a.length){if(!t)break e;for(;a.length<=l;a.push(0));u=c=0,s=(o%=M)-M+(i=1)}else{for(u=f=a[l],i=1;10<=f;f/=10,i++);c=(s=(o%=M)-M+i)<0?0:u/h[i-s-1]%10|0}if(t=t||r<0||null!=a[l+1]||(s<0?u:u%h[i-s-1]),t=n<4?(c||t)&&(0==n||n==(e.s<0?3:2)):5d?e.c=e.e=null:e.e>>11))?(n=crypto.getRandomValues(new Uint32Array(2)),r[s]=n[0],r[s+1]=n[1]):(f.push(o%1e14),s+=2);s=i/2}else{if(!crypto.randomBytes)throw O=!1,Error(U+\"crypto unavailable\");for(r=crypto.randomBytes(i*=7);sn-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(e,r,n,t,i){var o,s,f,u,l,c,a,h,p=e.indexOf(\".\"),g=y,w=N;for(0<=p&&(u=b,b=0,e=e.replace(\".\",\"\"),c=(h=new _(r)).pow(e.length-p),b=u,h.c=d(X($(c.c),c.e,\"0\"),10,n,m),h.e=h.c.length),f=u=(a=d(e,r,n,i?(o=A,m):(o=m,A))).length;0==a[--u];a.pop());if(!a[0])return o.charAt(0);if(p<0?--f:(c.c=a,c.e=f,c.s=t,a=(c=v(c,h,g,w,n)).c,l=c.r,f=c.e),p=a[s=f+g+1],u=n/2,l=l||s<0||null!=a[s+1],l=w<4?(null!=p||l)&&(0==w||w==(c.s<0?3:2)):un;)a[s]=0,s||(++f,a=[1].concat(a));for(u=a.length;!a[--u];);for(p=0,e=\"\";p<=u;e+=o.charAt(a[p++]));e=X(e,f,o.charAt(0))}return e}}(),v=function(){function S(e,r,n){var t,i,o,s,f=0,u=e.length,l=r%k,c=r/k|0;for(e=e.slice();u--;)f=((i=l*(o=e[u]%k)+(t=c*o+(s=e[u]/k|0)*l)%k*k+f)/n|0)+(t/k|0)+c*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function R(e,r,n,t){var i,o;if(n!=t)o=tr[i]?1:-1;break}return o}function P(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n](E[f]||0)&&s--,b<0)p.push(1),u=!0;else{for(v=E.length,N=A.length,b+=2,1<(l=T(i/(A[f=0]+1)))&&(A=S(A,l,i),E=S(E,l,i),N=A.length,v=E.length),d=N,w=(g=E.slice(0,N)).length;w=i/2&&y++;do{if(l=0,(o=R(A,g,N,w))<0){if(m=g[0],N!=w&&(m=m*i+(g[1]||0)),1<(l=T(m/y)))for(i<=l&&(l=i-1),a=(c=S(A,l,i)).length,w=g.length;1==R(c,g,a,w);)l--,P(c,No&&(l.c.length=o):t&&(l=l.mod(r))}if(i){if(0===(i=T(i/2)))break;u=i%2}else if(x(e=e.times(n),e.e+1,1),14o&&(c.c.length=o):t&&(c=c.mod(r))}return t?l:(f&&(l=w.div(l)),r?l.mod(r):o?x(l,b,N,void 0):l)},t.integerValue=function(e){var r=new _(this);return null==e?e=N:H(e,0,8),x(r,r.e+1,e)},t.isEqualTo=t.eq=function(e,r){return 0===z(this,new _(e,r))},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(e,r){return 0this.c.length-2},t.isLessThan=t.lt=function(e,r){return z(this,new _(e,r))<0},t.isLessThanOrEqualTo=t.lte=function(e,r){return-1===(r=z(this,new _(e,r)))||0===r},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return 0t&&(t=this.e+1),t},t.shiftedBy=function(e){return H(e,-G,G),this.times(\"1e\"+e)},t.squareRoot=t.sqrt=function(){var e,r,n,t,i,o=this,s=o.c,f=o.s,u=o.e,l=y+4,c=new _(\"0.5\");if(1!==f||!s||!s[0])return new _(!f||f<0&&(!s||s[0])?NaN:s?o:1/0);if((n=0==(f=Math.sqrt(+D(o)))||f==1/0?(((r=$(s)).length+u)%2==0&&(r+=\"0\"),f=Math.sqrt(+r),u=j((u+1)/2)-(u<0||u%2),new _(r=f==1/0?\"1e\"+u:(r=f.toExponential()).slice(0,r.indexOf(\"e\")+1)+u)):new _(f+\"\")).c[0])for((f=(u=n.e)+l)<3&&(f=0);;)if(i=n,n=c.times(i.plus(v(o,i,l,1))),$(i.c).slice(0,f)===(r=$(n.c)).slice(0,f)){if(n.e {\n if (l == 0) { l++ }\n else {\n rl.close();\n let strArray = input.split(\" \")\n let s = strArray.map(function (item) {\n return BN(item);\n });\n let res = []\n let n = s.length * 2\n res[0] = BN(0)\n res[n - 1] = s[0]\n for (let i = 1; i < s.length; i++) {\n if (s[i].minus(res[i - 1]) > res[n - (i - 1) - 1]) {\n\n res[i] = s[i].minus(res[n - (i - 1) - 1])\n if (res[i - 1] > res[i]) {\n res[i] =res[i].minus(res[i - 1])\n }\n res[n - i - 1] = s[i].minus(res[i])\n\n } else {\n res[i] = res[i - 1]\n res[n - i - 1] = s[i].minus(res[i - 1])\n }\n }\n console.log(res.join(\" \"))\n return 0;\n }\n});\n\n//4 5 4 4 3 4\n//0 1 1 1 1 2 2 2 3 3 4 4\n//0 1 1 1 1 2 3 3 4 4\n//0 1 1 1 1 1 3 2 3 3 4 4"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet l = 0;\nrl.on('line', (input) => {\n if (l == 0) { l++ }\n else {\n rl.close();\n let strArray = input.split(\" \")\n let s = strArray.map(function (item) {\n return parseInt(item, 10);\n });\n let res = []\n let n = s.length * 2\n res[0] = 0\n res[n - 1] = s[0]\n for (let i = 1; i < s.length; i++) {\n if (s[i] - res[i - 1] > res[n - (i - 1)-1]) {\n res[i] = s[i] - res[i - 1] - res[n - (i - 1)-1]\n res[n-i - 1] = s[i] - res[i]\n\n } else {\n res[i] = res[i - 1]\n res[n - i - 1] = s[i]-res[i-1]\n }\n }\n console.log(res.join(\" \"))\n return 0;\n }\n});\n"}, {"source_code": "function main() {\n\n var n = stdin[0];\n n = parseInt(n);\n\n var b = stdin[1].split(' ').map( (s) => { return new Int64(s); });\n var a = [];\n a[0] = 0;\n a[n-1] = b[0];\n\n for(var i=1 ; i 0xF ? '' : '0') + i.toString(16);\n}\n\n//\n// Int64\n//\n\n/**\n * Constructor accepts any of the following argument types:\n *\n * new Int64(buffer[, offset=0]) - Existing Buffer with byte offset\n * new Int64(Uint8Array[, offset=0]) - Existing Uint8Array with a byte offset\n * new Int64(string) - Hex string (throws if n is outside int64 range)\n * new Int64(number) - Number (throws if n is outside int64 range)\n * new Int64(hi, lo) - Raw bits as two 32-bit values\n */\nvar Int64 = module.exports = function(a1, a2) {\n if (a1 instanceof Buffer) {\n this.buffer = a1;\n this.offset = a2 || 0;\n } else if (Object.prototype.toString.call(a1) == '[object Uint8Array]') {\n // Under Browserify, Buffers can extend Uint8Arrays rather than an\n // instance of Buffer. We could assume the passed in Uint8Array is actually\n // a buffer but that won't handle the case where a raw Uint8Array is passed\n // in. We construct a new Buffer just in case.\n this.buffer = new Buffer(a1);\n this.offset = a2 || 0;\n } else {\n this.buffer = this.buffer || new Buffer(8);\n this.offset = 0;\n this.setValue.apply(this, arguments);\n }\n};\n\n\n// Max integer value that JS can accurately represent\nInt64.MAX_INT = Math.pow(2, 53);\n\n// Min integer value that JS can accurately represent\nInt64.MIN_INT = -Math.pow(2, 53);\n\nInt64.prototype = {\n\n constructor: Int64,\n\n /**\n * Do in-place 2's compliment. See\n * http://en.wikipedia.org/wiki/Two's_complement\n */\n _2scomp: function() {\n var b = this.buffer, o = this.offset, carry = 1;\n for (var i = o + 7; i >= o; i--) {\n var v = (b[i] ^ 0xff) + carry;\n b[i] = v & 0xff;\n carry = v >> 8;\n }\n },\n\n /**\n * Set the value. Takes any of the following arguments:\n *\n * setValue(string) - A hexidecimal string\n * setValue(number) - Number (throws if n is outside int64 range)\n * setValue(hi, lo) - Raw bits as two 32-bit values\n */\n setValue: function(hi, lo) {\n var negate = false;\n if (arguments.length == 1) {\n if (typeof(hi) == 'number') {\n // Simplify bitfield retrieval by using abs() value. We restore sign\n // later\n negate = hi < 0;\n hi = Math.abs(hi);\n lo = hi % VAL32;\n hi = hi / VAL32;\n if (hi > VAL32) throw new RangeError(hi + ' is outside Int64 range');\n hi = hi | 0;\n } else if (typeof(hi) == 'string') {\n if( hi.length>=2 && hi[0]=='0' && hi[1]=='x' ) {\n hi = (hi + '').replace(/^0x/, '');\n lo = hi.substr(-8);\n hi = hi.length > 8 ? hi.substr(0, hi.length - 8) : '';\n hi = parseInt(hi, 16);\n lo = parseInt(lo, 16);\n } else {\n lo = hi.substr(-10);\n hi = hi.length > 10 ? hi.substr(0, hi.length - 10) : '';\n hi = parseInt(hi);\n lo = parseInt(lo);\n }\n } else {\n throw new Error(hi + ' must be a Number or String');\n }\n }\n\n // Technically we should throw if hi or lo is outside int32 range here, but\n // it's not worth the effort. Anything past the 32'nd bit is ignored.\n\n // Copy bytes to buffer\n var b = this.buffer, o = this.offset;\n for (var i = 7; i >= 0; i--) {\n b[o+i] = lo & 0xff;\n lo = i == 4 ? hi : lo >>> 8;\n }\n\n // Restore sign of passed argument\n if (negate) this._2scomp();\n },\n\n /**\n * Convert to a native JS number.\n *\n * WARNING: Do not expect this value to be accurate to integer precision for\n * large (positive or negative) numbers!\n *\n * @param allowImprecise If true, no check is performed to verify the\n * returned value is accurate to integer precision. If false, imprecise\n * numbers (very large positive or negative numbers) will be forced to +/-\n * Infinity.\n */\n toNumber: function(allowImprecise) {\n var b = this.buffer, o = this.offset;\n\n // Running sum of octets, doing a 2's complement\n var negate = b[o] & 0x80, x = 0, carry = 1;\n for (var i = 7, m = 1; i >= 0; i--, m *= 256) {\n var v = b[o+i];\n\n // 2's complement for negative numbers\n if (negate) {\n v = (v ^ 0xff) + carry;\n carry = v >> 8;\n v = v & 0xff;\n }\n\n x += v * m;\n }\n\n // Return Infinity if we've lost integer precision\n if (!allowImprecise && x >= Int64.MAX_INT) {\n return negate ? -Infinity : Infinity;\n }\n\n return negate ? -x : x;\n },\n\n /**\n * Convert to a JS Number. Returns +/-Infinity for values that can't be\n * represented to integer precision.\n */\n valueOf: function() {\n return this.toNumber(false);\n },\n\n /**\n * Return string value\n *\n * @param radix Just like Number#toString()'s radix\n */\n toString: function(radix) {\n return this.valueOf().toString(radix || 10);\n },\n\n /**\n * Return a string showing the buffer octets, with MSB on the left.\n *\n * @param sep separator string. default is '' (empty string)\n */\n toOctetString: function(sep) {\n var out = new Array(8);\n var b = this.buffer, o = this.offset;\n for (var i = 0; i < 8; i++) {\n out[i] = _HEX[b[o+i]];\n }\n return out.join(sep || '');\n },\n\n /**\n * Returns the int64's 8 bytes in a buffer.\n *\n * @param {bool} [rawBuffer=false] If no offset and this is true, return the internal buffer. Should only be used if\n * you're discarding the Int64 afterwards, as it breaks encapsulation.\n */\n toBuffer: function(rawBuffer) {\n if (rawBuffer && this.offset === 0) return this.buffer;\n\n var out = new Buffer(8);\n this.buffer.copy(out, 0, this.offset, this.offset + 8);\n return out;\n },\n\n /**\n * Copy 8 bytes of int64 into target buffer at target offset.\n *\n * @param {Buffer} targetBuffer Buffer to copy into.\n * @param {number} [targetOffset=0] Offset into target buffer.\n */\n copy: function(targetBuffer, targetOffset) {\n this.buffer.copy(targetBuffer, targetOffset || 0, this.offset, this.offset + 8);\n },\n\n /**\n * Returns a number indicating whether this comes before or after or is the\n * same as the other in sort order.\n *\n * @param {Int64} other Other Int64 to compare.\n */\n compare: function(other) {\n\n // If sign bits differ ...\n if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) {\n return other.buffer[other.offset] - this.buffer[this.offset];\n }\n\n // otherwise, compare bytes lexicographically\n for (var i = 0; i < 8; i++) {\n if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) {\n return this.buffer[this.offset+i] - other.buffer[other.offset+i];\n }\n }\n return 0;\n },\n\n /**\n * Returns a boolean indicating if this integer is equal to other.\n *\n * @param {Int64} other Other Int64 to compare.\n */\n equals: function(other) {\n return this.compare(other) === 0;\n },\n\n /**\n * Pretty output in console.log\n */\n inspect: function() {\n return '[Int64 value:' + this + ' octets:' + this.toOctetString(' ') + ']';\n }\n};\n"}, {"source_code": "function main() {\n\n var n = stdin[0];\n n = parseInt(n);\n\n var b = stdin[1].split(' ').map( (s) => { return parseInt(s); });\n var a = [];\n a[0] = 0;\n a[n-1] = b[0];\n\n for(var i=1 ; i 0){\n\t\tkeys[s[i+1].toLowerCase()]--;\n\t}\n\telse{\n\t\tcnt++;\n\t}\n}\n\nwrite(cnt);"}, {"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = true;\n\n this.solveCase = function() {\n var res , i , j , fl , cn , temp , len ;\n res = 0 ;\n len = this.s.length ;\n for( i = 0 ; i < len ; i++ ) {\n \tif( i % 2 == 0 ) {\n \t\tthis.arr[ ( this.s.charCodeAt( i ) - 'a'.charCodeAt( 0 ) ) ]++ ;\n \t}\n \telse {\n \t\tif( this.arr[ ( this.s.charCodeAt( i ) - 'A'.charCodeAt( 0 ) ) ] > 0 ) {\n \t\t\tthis.arr[ ( this.s.charCodeAt( i ) - 'A'.charCodeAt( 0 ) ) ]-- ;\n \t\t}\n \t\telse {\n \t\t\tres++ ;\n \t\t}\n \t}\n }\n print( res );\n };\n\n this.init = function() {\n this.lim1 = 30;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i;\n hasMoreInput = true;\n try {\n this.n = irObj.nextInt();\n this.s = irObj.nextString();\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.arr = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "var cnt = new Array(26);\nfor(var i=0;i<26;i++) \n cnt[i] = 0;\nvar n = parseInt(readline());\nvar s = readline();\nvar ans = 0;\nfor(var i=0;i<2*n-2;i+=2) {\n var c = s[i].charCodeAt() - 97;\n cnt[c] ++;\n var c = s[i+1].charCodeAt() - 65;\n if(cnt[c] > 0) cnt[c] --;\n else ans ++; \n}\nprint(ans);"}, {"source_code": "\"use strict\";\nprocess.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet inputString = \"\";\nlet currentLine = 0;\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nprocess.stdin.on(\"data\", inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on(\"end\", _ => {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map(string => {\n return string.trim();\n });\n\n main();\n});\n// main();\n\n////////////////////////////////////////////////////////////////////////\n\nfunction main() {\n var a = readline();\n var b = readline().toLocaleLowerCase();\n let counter = 0; //bought keys\n let keys = {}; //key status\n for (let i = 0; i < b.length; i += 2) {\n //first step\n if (keys[b[i]] === undefined) {\n keys[b[i]] = 1;\n } else {\n keys[b[i]]++;\n }\n //second step\n if (keys[b[i + 1]]) {\n keys[b[i + 1]]--;\n } else {\n counter++;\n }\n }\n console.log(counter);\n}\n"}], "negative_code": [{"source_code": "function ProblemSolver() {\n this.HAS_TEST_CASES = false;\n this.INPUT_FILE_NAME = \"test.in\";\n this.OUTPUT_FILE_NAME = \"out.txt\";\n this.DO_OUTPUT_TO_FILE = false;\n this.CLEAR_ARRAY_PER_CASE = false;\n\t\n this.solveCase = function() {\n var res , i , j , fl , cn , temp , len , len2 ;\n len = this.s.length ;\n res = \"\" ;\n for( i = 0 ; i < this.n ; i++ ) {\n \tthis.arr[ i ] = this.arr[ i ] - 1 ;\n }\n this.arr.sort() ;\n for( i = 0 ; i < len ; i++ ) {\n \tthis.brr[ i ] = this.s.charCodeAt( i ) ;\n }\n j = 0 ;\n cn = 0 ;\n len2 = Math.floor( len / 2 ) ;\n for( i = 0 ; i < len2 ; i++ ) {\n \twhile( j < this.n && this.arr[ j ] == i ) {\n \t\tcn++ ;\n \t\tj++ ;\n \t}\n \tif( cn % 2 == 0 ) {\n \t}\n \telse {\n \t\ttemp = this.brr[ i ] ;\n \t\tthis.brr[ i ] = this.brr[ len - i - 1 ] ;\n \t\tthis.brr[ len - i - 1 ] = temp ;\n \t}\n }\n for( i = 0 ; i < len ; i++ ) {\n \tres += String.fromCharCode( this.brr[ i ] ) ;\n }\n print( res );\n };\n\n this.init = function() {\n this.lim1 = 100010;\n this.lim2 = 110;\n this.cc = 1;\n this.ind = 1;\n this.n = 0;\n this.cn = 0;\n this.declareAndFillArrays();\n };\n\n this.getInput = function( irObj ) {\n var hasMoreInput , i;\n hasMoreInput = true;\n try {\n this.s = irObj.nextString();\n this.n = irObj.nextInt();\n this.arr = new Array() ;\n for( i = 0 ; i < this.n ; i++ ) {\n this.arr.push( irObj.nextInt() ) ;\n }\n }\n catch( ex ) {\n hasMoreInput = false;\n }\n return hasMoreInput;\n };\n\n this.clearArraysPerCase = function() {\n var i;\n this.arr = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.arr.push( 0 );\n this.adj_list.push( new Array() );\n }\n };\n\n this.clearPerCase = function() {\n this.cn = 0;\n this.cc++;\n if( this.CLEAR_ARRAY_PER_CASE == true ) {\n this.clearArraysPerCase() ;\n }\n };\n\n this.declareAndFillArrays = function() {\n var i , j;\n this.srr = new Array();\n this.vis = new Array();\n this.arr = new Array();\n this.brr = new Array();\n this.memo = new Array();\n this.done = new Array();\n this.adj_list = new Array();\n for( i = 0 ; i < this.lim1 ; i++ ) {\n this.srr.push( \"\" );\n this.vis.push( 0 );\n this.arr.push( 0 );\n this.brr.push( 0 );\n this.adj_list.push( new Array() );\n }\n for( i = 0 ; i < this.lim2 ; i++ ) {\n this.memo.push( new Array() );\n this.done.push( new Array() );\n for( j = 0 ; j < this.lim2 ; j++ ) {\n this.memo[ i ].push( -1 );\n this.done[ i ].push( 0 );\n }\n }\n };\n\n this.init();\n}\n\nfunction InputReader() {\n var self = this ;\n this.allLines = new Array();\n this.currrentLineNumber = 0;\n this.currrentCharacterIndex = 0;\n this.callBackFunction = null ;\n this.parentContext = null ;\n\n this.readAllLines = function() {\n var singleLine;\n while( true ) {\n try {\n singleLine = readline();\n if( singleLine == null ) {\n break;\n }\n }\n catch( ex ) {\n break;\n }\n this.allLines.push( singleLine );\n }\n };\n \n this.readAllLinesFromRhino = function() {\n var brObj , line ;\n importPackage( java.io ) ;\n importPackage( java.lang ) ;\n brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;\n this.allLines = [] ;\n while( true ) {\n line = brObj.readLine() ;\n if( line == null ) {\n break;\n }\n this.allLines.push( line ) ;\n }\n };\n \n this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {\n self.chunkData += chunk ;\n };\n\n this.readEndFromNodeJsJudgeServer = function() {\n self.parseRawData( self.chunkData ) ;\n self.parentContext.runCases() ;\n };\n \n this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {\n this.parentContext = parentContext ;\n process.stdin.resume() ;\n process.stdin.setEncoding( 'utf8' ) ;\n this.chunkData = '' ;\n process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;\n process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;\n };\n\n this.parseRawData = function( data ) {\n var len , i , currentString;\n len = data.length;\n currentString = \"\";\n this.allLines = [] ;\n for( i = 0 ; i < len ; i++ ) {\n if( data[ i ] == '\\r' ) {\n }\n else if( data[ i ] == '\\n' ) {\n this.allLines.push( currentString );\n currentString = \"\";\n }\n else {\n currentString += data[ i ];\n }\n }\n if( currentString != \"\" ) {\n this.allLines.push( currentString );\n }\n };\n\n this.readAllLinesFromFile = function( inputFileName ) {\n var currentDirectory , fsObj , inputFilePath , rawData;\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n inputFilePath = currentDirectory + \"\\\\\" + inputFileName;\n rawData = fsObj.readFileSync( inputFilePath , \"utf8\" );\n this.parseRawData( rawData );\n };\n\n this.next = function( flag ) {\n var len , i , startIdx , res , endIdx;\n if( flag == 0 ) {\n if( this.currrentCharacterIndex != 0 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n res = \"\";\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;\n }\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n return res;\n }\n while( true ) {\n if( this.currrentLineNumber >= this.allLines.length ) {\n throw new Error( \"No more tokens available!\" );\n }\n startIdx = -1;\n len = this.allLines[ this.currrentLineNumber ].length;\n if( typeof( len ) == 'function' ) {\n len = this.allLines[ this.currrentLineNumber ].length() ;\n }\n for( i = this.currrentCharacterIndex ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {\n startIdx = i;\n break;\n }\n }\n if( startIdx == -1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n continue;\n }\n res = \"\";\n endIdx = len - 1 ;\n for( i = startIdx ; i < len ; i++ ) {\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {\n endIdx = i;\n break;\n }\n if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {\n res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;\n }\n else {\n res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );\n }\n }\n this.currrentCharacterIndex = endIdx;\n if( endIdx == len - 1 ) {\n this.currrentLineNumber++;\n this.currrentCharacterIndex = 0;\n }\n return res;\n }\n };\n\n this.nextInt = function() {\n return parseInt( this.next( 1 ) );\n };\n\n this.nextDouble = function() {\n return parseFloat( this.next( 1 ) );\n };\n\n this.nextString = function() {\n return this.next( 1 );\n };\n\n this.nextLine = function() {\n return this.next( 0 );\n };\n}\n\nfunction FileOutputHandler() {\n this.resultantStringArray = new Array();\n\n this.addNewLine = function( newString ) {\n this.resultantStringArray.push( newString );\n };\n\n this.clearPercase = function() {\n this.resultantStringArray = new Array();\n };\n\n this.flushOutOutputToFile = function( outputFileName ) {\n var i , sz , res , currentDirectory , fsObj , outputFilePath;\n res = \"\";\n sz = this.resultantStringArray.length;\n for( i = 0 ; i < sz ; i++ ) {\n if( i != 0 ) {\n res += \"\\n\";\n }\n res += this.resultantStringArray[ i ];\n }\n fsObj = require( 'fs' );\n currentDirectory = __dirname;\n outputFilePath = currentDirectory + \"\\\\\" + outputFileName;\n fsObj.writeFileSync( outputFilePath , res );\n this.clearPercase();\n };\n}\n\nfunction CodeExecutioner() {\n this.irObj = new InputReader();\n this.psObj = new ProblemSolver();\n this.fohObj = new FileOutputHandler();\n\n this.runCases = function() {\n if( this.psObj.HAS_TEST_CASES == true ) {\n testCases = this.irObj.nextInt();\n for( i = 0 ; i < testCases ; i++ ) {\n this.psObj.clearPerCase();\n this.psObj.getInput( this.irObj );\n this.psObj.solveCase();\n }\n }\n else {\n while( true ) {\n this.psObj.clearPerCase();\n hasMoreTestCases = this.psObj.getInput( this.irObj );\n if( hasMoreTestCases == false ) {\n break;\n }\n this.psObj.solveCase();\n }\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );\n }\n };\n\n this.detectEnvironmentType = function() {\n var environmentType = null ;\n try {\n if( importPackage != null ) {\n environmentType = 'rhino' ;\n }\n }\n catch( ex1 ) {\n try {\n //for nodejs local server check\n if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {\n environmentType = 'local-node-js' ;\n }\n }\n catch( ex2 ) {\n try {\n if( readline == null || typeof( readline ) != 'function' ) {\n environmentType = 'server-node-js' ;\n }\n else {\n try {\n if( Map != null ) {\n environmentType = 'spider-monkey' ;\n }\n else {\n environmentType = 'javascript-v8' ;\n }\n }\n catch( ex3 ) {\n environmentType = 'javascript-v8' ;\n }\n }\n }\n catch( ex3 ) {\n environmentType = 'server-node-js' ;\n }\n }\n }\n return environmentType ;\n };\n\n this.configureStreamsAndReadInput = function() {\n var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;\n isNodeJsJudgeServer = false ;\n environmentType = this.detectEnvironmentType() ;\n if( environmentType == 'local-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n if( this.psObj.DO_OUTPUT_TO_FILE == true ) {\n localContext = this.fohObj;\n print = function() {\n localContext.addNewLine.apply( localContext , arguments );\n }\n }\n this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );\n this.runCases() ;\n }\n else if( environmentType == 'server-node-js' ) {\n try {\n if( print == null || typeof( print ) != 'function' ) {\n print = console.log;\n }\n }\n catch( ex ) {\n print = console.log;\n }\n this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;\n }\n else if( environmentType == 'javascript-v8' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n else if( environmentType == 'rhino' ) {\n this.irObj.readAllLinesFromRhino();\n this.runCases() ;\n }\n else if( environmentType == 'spider-monkey' ) {\n this.irObj.readAllLines();\n this.runCases() ;\n }\n };\n \n this.configureStreamsAndReadInput();\n}\n\nnew CodeExecutioner();\n"}, {"source_code": "var cnt = new Array(26);\nfor(var i=0;i<26;i++) \n cnt[i] = 0;\nvar n = parseInt(readline());\nvar s = readline();\nvar ans = 0;\nfor(var i=0;i<2*n-2;i+=2) {\n var c = parseInt(s[i]) - parseInt('a');\n cnt[c] ++;\n var c = parseInt(s[i+1]) - parseInt('A');\n if(cnt[c] > 0) cnt[c] --;\n else ans ++; \n}\nprint(ans);"}], "src_uid": "80fdb95372c1e8d558b8c8f31c9d0479"} {"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 ≤ n ≤ 100) — 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 — 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": "var n=+readline();\nvar ans=[];\nfor(var i=0;i 0; i--)\n\t\t\t\tif (!(this[i])) {\n\t\t\t\t\tthis[i] = true;\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t}\n\t}\n\n\tvar t, sum;\n\tfor (var i = 0; i < n; i++) {\n\t\tsum = o.max();\n\t\tt = [sum];\n\t\td = sum;\n\n\t\twhile (sum != s) {\n\t\t\t--d;\n\t\t\tif (!o[d] && (sum + d) <= s) {\n\t\t\t\to[d] = true;\n\t\t\t\tsum += d;\n\t\t\t\tt.push(d);\n\t\t\t}\n\t\t}\n\n\t\tprint(t.join(' '));\n\t}\n\n}).call(this);"}, {"source_code": "\n// 334A Пакетики с конфетами \n\n\nvar n = parseInt(readline());\n//var input_line = readline().split(' ').map(Number);\n//var n = input_line[0];\n//var m = input_line[1];\n\nvar out = '';\nvar n2 = n * n;\nvar n2_2 = n2 / 2;\n\nfor (var i = 1; i <= n; i++) {\n for (var j = i; j <= n2_2; j+=n) {\n out += j.toString() + ' ' + (n-j+1).toString() + ' ';\n };\n out += '\\n';\n};\n\nprint(out);\n "}], "src_uid": "0ac2a0954fe43d66eac32072c8ea5070"} {"nl": {"description": "There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to n where n is the total number of messages in the chat.Each message might contain a link to an earlier message which it is a reply to. When opening a message x or getting a link to it, the dialogue is shown in such a way that k previous messages, message x and k next messages are visible (with respect to message x). In case there are less than k messages somewhere, they are yet all shown.Digging deep into your message history, you always read all visible messages and then go by the link in the current message x (if there is one) and continue reading in the same manner.Determine the number of messages you'll read if your start from message number t for all t from 1 to n. Calculate these numbers independently. If you start with message x, the initial configuration is x itself, k previous and k next messages. Messages read multiple times are considered as one.", "input_spec": "The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n) — the total amount of messages and the number of previous and next messages visible. The second line features a sequence of integers a1, a2, ..., an (0 ≤ ai < i), where ai denotes the i-th message link destination or zero, if there's no link from i. All messages are listed in chronological order. It's guaranteed that the link from message x goes to message with number strictly less than x.", "output_spec": "Print n integers with i-th denoting the number of distinct messages you can read starting from message i and traversing the links while possible.", "sample_inputs": ["6 0\n0 1 1 2 3 2", "10 1\n0 1 0 3 4 5 2 3 7 0", "2 2\n0 1"], "sample_outputs": ["1 2 2 3 3 3", "2 3 3 4 5 6 6 6 8 2", "2 2"], "notes": "NoteConsider i = 6 in sample case one. You will read message 6, then 2, then 1 and then there will be no link to go.In the second sample case i = 6 gives you messages 5, 6, 7 since k = 1, then 4, 5, 6, then 2, 3, 4 and then the link sequence breaks. The number of distinct messages here is equal to 6."}, "positive_code": [{"source_code": "function getBeforeStep (i, k) {\n return i < k ? i : k;\n}\n\nfunction getAfterStep (i, k, n) {\n return i + k >= n ? (n - i) - 1 : k;\n}\n\nfunction getStep (i, k, n) {\n return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;\n}\n\nvar input = readline();\nvar messages = readline().split(' ');\n\ninput = input.split(' ');\nvar n = parseInt(input[0]);\nvar k = parseInt(input[1]);\n\nvar i, value, lastValue, start, end, prevEnd, step;\n\nfor (i = 0; i < n; i++) {\n value = parseInt(messages[i]) - 1;\n lastValue = messages[value] || 0;\n\n start = Math.max(i - k, 0);\n end = i + getAfterStep(i, k, n);\n prevEnd = value + getAfterStep(value, k, n);\n\n step = i != 0 && value >= 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);\n\n messages[i] = lastValue + step\n}\n\nprint(messages.join(' '))\n"}, {"source_code": "var input = readline().split(' ');\nvar n = +input[0];\nvar k = +input[1];\nvar refs = readline().split(' ').map(function (msg) {\n return +msg;\n});\n// const n = 20;\n// const k = 1;\n// const refs = [0, 1, 0, 3, 4, 5, 2, 3, 7, 0, 0, 7, 0, 3, 4, 12, 2, 3, 7, 0];\n\n// Solution\nfunction isRange(arr) {\n return Array.isArray(arr) && typeof arr[0] === 'number';\n}\n\nfunction checkCrossing(arr1, arr2) {\n if (arr1[1] >= arr2[0] && arr1[1] <= arr2[1]) {\n return 'left';\n }\n if (arr1[0] >= arr2[0] && arr1[0] <= arr2[1]) {\n return 'right'\n }\n return 'no';\n}\n\nfunction concatRanges(arr1, arr2) {\n return [\n arr1[0],\n arr2[1]\n ];\n}\n\nfunction getMessages(i) {\n if (refs[i] === 0) {\n return cache[i]; // Get numbers from cache\n }\n var refRange = getMessages(refs[i] - 1);\n\n // If refRange is like [2, 15]\n if (isRange(refRange)) {\n switch (checkCrossing(refRange, cache[i])) {\n case 'left':\n return concatRanges(refRange, cache[i]);\n case 'right':\n return concatRanges(cache[i], refRange);\n case 'no':\n if (cache[i][0] < refRange[0]) {\n return [cache[i], refRange];\n }\n return [refRange, cache[i]];\n }\n }\n\n // If refRange kinda [[1, 15], [18, 25]]\n var hasCrossing = false;\n var stopCheck = false;\n\n for (var k = 0, l = refRange.length; k < l; k++) {\n switch (checkCrossing(refRange[k], cache[i])) {\n case 'left':\n hasCrossing = true;\n refRange[k] = concatRanges(refRange[k], cache[i]);\n break;\n case 'right':\n hasCrossing = true;\n refRange[k] = concatRanges(cache[i], refRange[k]);\n break;\n case 'no':\n // To prevent excess entries\n if (cache[i][1] < refRange[k][0]) {\n stopCheck = true;\n }\n break;\n }\n if (hasCrossing || stopCheck) {\n break;\n }\n }\n\n if (!hasCrossing) {\n refRange.push(cache[i]);\n }\n return refRange;\n}\n\nvar res = [];\nvar cache = [];\n\nfor (var ref = 0; ref < n; ref++) {\n cache[ref] = [\n ref - k < 0 ? 0 : ref - k, // Left border\n ref + k >= n ? n - 1 : ref + k // Right border\n ];\n}\n\nrefs.forEach(function (ref, i) {\n var borders = getMessages(i);\n\n if (isRange(borders)) {\n res.push(borders[1] - borders[0] + 1);\n } else {\n var sum = 0;\n\n borders.forEach(function (border) {\n sum += border[1] - border[0] + 1;\n });\n res.push(sum);\n }\n});\n\nprint(res.join(' '));"}, {"source_code": "var numbers = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar messageHistory = readline().split(\" \").map(function(x) { return parseInt(x); });\nvar visibleMessages = [], N = numbers[0], K = numbers[1];\n\nfor(var t = 0; t < N; t++) {\n var maxNumOfUniqueMessages = Math.min(N,\n Math.min(K, t) + 1 + Math.min(K, N - t - 1)\n ); \n \n if(t <= K) { \n visibleMessages[t] = Math.min(\n t + 1 + K, \n maxNumOfUniqueMessages \n );\n } else {\n var linkToPrevMessage = messageHistory[t] - 1; \n var intersectionNumber = (Math.min(linkToPrevMessage + K + 1, N) - (t - K));\n intersectionNumber = intersectionNumber > 0 ? intersectionNumber : 0;\n \n visibleMessages[t] = linkToPrevMessage >= 0 ? \n visibleMessages[linkToPrevMessage] + \n (maxNumOfUniqueMessages - intersectionNumber): \n maxNumOfUniqueMessages; \n }\n}\n\nwrite(visibleMessages.join(' '));"}], "negative_code": [{"source_code": "function getStep (i, k, n) {\n var before = k;\n var after = k;\n if (i < k) {\n before = +(0 - i);\n }\n if (i + k >= n) {\n after = (n - i) - 1;\n }\n\n return before + after + 1;\n}\n\nvar input = readline();\nvar messages = readline().split(' ');\n\ninput = input.split(' ');\nvar n = parseInt(input[0]);\nvar k = parseInt(input[1]);\n\nvar i, lastValue, step, diff, value;\n\nfor (i = 0; i < n; i++) {\n value = parseInt(messages[i]) - 1;\n lastValue = messages[value] || 0;\n step = getStep(i, k, n);\n diff = i - value - 1;\n\n if (value >= 0 && k > 0 && diff < step) {\n step = i - value + k - 1\n }\n messages[i] = lastValue + step\n}\n\nprint(messages.join(' '))\n"}, {"source_code": "function getIndexesRange (index, k, arr) {\n var range = [];\n var start = Math.max(index - k, 0);\n var end = Math.min(index + k + 1, arr.length);\n for (var i = start; i < end ; i++) {\n range.push(i);\n }\n return range;\n}\n\nvar input = readline();\nvar messages = readline().split(' ');\n\ninput = input.split(' ');\nvar n = parseInt(input[0]);\nvar k = parseInt(input[1]);\n\nvar i, value, range, prevIndex, readedMessages;\nvar map = {};\nvar messagesCounts = [];\n\nfor (i = 0; i < n; i++) {\n value = messages[i] = parseInt(messages[i]);\n readedMessages = [];\n\n prevIndex = value - 1;\n if (prevIndex > 0) {\n readedMessages = readedMessages.concat(map[prevIndex]);\n }\n\n range = getIndexesRange(i, k, messages);\n\n range.forEach(function (v) {\n if (readedMessages.indexOf(v) == -1) {\n readedMessages.push(v);\n }\n })\n\n map[i] = readedMessages;\n messagesCounts.push(readedMessages.length);\n}\n\nprint(messagesCounts.join(' '))\n"}, {"source_code": "function getBeforeStep (i, k) {\n return i < k ? +(0 - i) : k;\n}\n\nfunction getAfterStep (i, k, n) {\n return i + k >= n ? (n - i) - 1 : k;\n}\n\nfunction getStep (i, k, n) {\n return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;\n}\n\nvar input = readline();\nvar messages = readline().split(' ');\n\ninput = input.split(' ');\nvar n = parseInt(input[0]);\nvar k = parseInt(input[1]);\n\nvar i, value, lastValue, start, end, prevEnd, step;\n\nfor (i = 0; i < n; i++) {\n value = parseInt(messages[i]) - 1;\n lastValue = messages[value] || 0;\n\n start = Math.max(i - k, 0);\n end = i + getAfterStep(i, k, n);\n prevEnd = value + getAfterStep(value, k, n);\n\n step = i != 0 && value >= 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);\n\n messages[i] = lastValue + step\n}\n\nprint(messages.join(' '))\n"}, {"source_code": "function getBeforeStep (i, k) {\n return i < k ? +(0 - i) : k;\n}\n\nfunction getAfterStep (i, k, n) {\n return i + k >= n ? (n - i) - 1 : k;\n}\n\nfunction getStep (i, k, n) {\n return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;\n}\n\nvar input = readline();\nvar messages = readline().split(' ');\n\ninput = input.split(' ');\nvar n = parseInt(input[0]);\nvar k = parseInt(input[1]);\n\nvar i, value, lastValue, start, end, prevEnd, step;\n\nfor (i = 0; i < n; i++) {\n value = parseInt(messages[i]) - 1;\n lastValue = messages[value] || 0;\n\n start = i - getBeforeStep(i, k);\n end = i + getAfterStep(i, k, n);\n prevEnd = value + getAfterStep(value, k, n);\n\n step = i != 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);\n\n messages[i] = lastValue + step\n}\n\nprint(messages.join(' '))\n"}], "src_uid": "0b4e6268cf1238169591e17cb644d451"} {"nl": {"description": "You are given two arrays of length $$$n$$$: $$$a_1, a_2, \\dots, a_n$$$ and $$$b_1, b_2, \\dots, b_n$$$.You can perform the following operation any number of times: Choose integer index $$$i$$$ ($$$1 \\le i \\le n$$$); Swap $$$a_i$$$ and $$$b_i$$$. What is the minimum possible sum $$$|a_1 - a_2| + |a_2 - a_3| + \\dots + |a_{n-1} - a_n|$$$ $$$+$$$ $$$|b_1 - b_2| + |b_2 - b_3| + \\dots + |b_{n-1} - b_n|$$$ (in other words, $$$\\sum\\limits_{i=1}^{n - 1}{\\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\\right)}$$$) you can achieve after performing several (possibly, zero) operations?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 4000$$$) — the number of test cases. Then, $$$t$$$ test cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$2 \\le n \\le 25$$$) — the length of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) — the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 10^9$$$) — the array $$$b$$$.", "output_spec": "For each test case, print one integer — the minimum possible sum $$$\\sum\\limits_{i=1}^{n-1}{\\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\\right)}$$$.", "sample_inputs": ["3\n\n4\n\n3 3 10 10\n\n10 10 3 3\n\n5\n\n1 2 3 4 5\n\n6 7 8 9 10\n\n6\n\n72 101 108 108 111 44\n\n10 87 111 114 108 100"], "sample_outputs": ["0\n8\n218"], "notes": "NoteIn the first test case, we can, for example, swap $$$a_3$$$ with $$$b_3$$$ and $$$a_4$$$ with $$$b_4$$$. We'll get arrays $$$a = [3, 3, 3, 3]$$$ and $$$b = [10, 10, 10, 10]$$$ with sum $$$3 \\cdot |3 - 3| + 3 \\cdot |10 - 10| = 0$$$.In the second test case, arrays already have minimum sum (described above) equal to $$$|1 - 2| + \\dots + |4 - 5| + |6 - 7| + \\dots + |9 - 10|$$$ $$$= 4 + 4 = 8$$$.In the third test case, we can, for example, swap $$$a_5$$$ and $$$b_5$$$."}, "positive_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet s = \"\";\n\nprocess.stdin.on(\"data\", (data) => {\n s += data;\n});\n\nprocess.stdin.on(\"end\", (data) => {\n s = s.split(\"\\n\").filter(Boolean);\n\n main();\n});\n\nfunction main() {\n const t = Number(s[0]);\n\n let i = 1;\n while (i < 3 * t + 1) {\n const length = s[i++];\n const a = s[i++].split(\" \").map(Number);\n const b = s[i++].split(\" \").map(Number);\n\n solve(a, b);\n }\n}\n\nfunction solve(a, b) {\n function recurse(a, b, index) {\n if (index > a.length - 1) {\n return;\n }\n\n if (a[index] < b[index]) {\n swap(a, b, index);\n }\n\n recurse(a, b, index + 1);\n }\n\n recurse(a, b, 0, 0);\n console.log(doSum(a, b));\n}\n\nfunction swap(a, b, index) {\n const temp = a[index];\n a[index] = b[index];\n b[index] = temp;\n}\n\nfunction doSum(a, b) {\n let sum = 0;\n for (let i = 0; i < a.length - 1; i++) {\n sum += Math.abs(a[i] - a[i + 1]);\n sum += Math.abs(b[i] - b[i + 1]);\n }\n return sum;\n}\n"}, {"source_code": "'use strict';\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst l = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\n \nconst ra = ()=>readline().split(' ').map(a=>+a)\n \nconst MOD = 1e9+7;\n\nconst calc = (a, b, n)=>{\n let swap = (i)=>{\n let tmp = a[i];\n a[i] = b[i];\n b[i] = tmp;\n }\n let sum = 0;\n for (let i=1; i stop += c);\nprocess.stdin.on('end', () => {\n const {EOL} = require('os');\n const lines = stop.split(EOL);\n var t = lines[0];\n var n = 0;\n var a = 0;\n for(i = 1; i <= t * 3; i++){\n var b = lines[i].split(' ').map(Number);\n if(i % 3 == 1){\n n = lines[i];\n }else if(i % 3 == 2){\n a = b;\n }else{\n var ans = 0;\n for(j = 1; j < n; j++){\n var x = Math.abs(a[j] - a[j - 1]) + Math.abs(b[j] - b[j - 1]);\n var y = Math.abs(a[j] - b[j - 1]) + Math.abs(b[j] - a[j - 1]);\n ans += Math.min(x, y);\n }\n console.log(ans);\n }\n }\n});"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n let arr = readline().split(' ').map(Number);\r\n let brr = readline().split(' ').map(Number);\r\n\r\n const calc = i => Math.abs(arr[i-1] - arr[i]) + Math.abs(brr[i-1] - brr[i]);\r\n\r\n let sum = 0;\r\n for (let i = 1; i < n; i++) {\r\n let cur = calc(i);\r\n let alt = Math.abs(arr[i-1] - brr[i]) + Math.abs(brr[i-1] - arr[i]);\r\n if (alt < cur) [arr[i], brr[i]] = [brr[i], arr[i]];\r\n sum += Math.min(alt, cur);\r\n }\r\n\r\n output(sum);\r\n }\r\n}\r\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n})\nconst lines = []\nrl.on('line', (input) => {\n lines.push(input);\n})\nrl.on('close', () => {\n// (function() {\n // const lines = require('fs').readFileSync('test.in', 'utf8').split('\\n')\n let l = 0;\n let t = +lines[l++]\n const output = []\n for (let i = 0; i < t; i++) {\n const n = +lines[l++]\n const a = lines[l++].trim().split(' ').map(Number)\n const b = lines[l++].trim().split(' ').map(Number)\n output[i] = solve(n, a, b)\n }\n console.log(output.join('\\n'))\n// })()\n})\n\nfunction solve(n, a, b) {\n for (let i = 0; i < a.length; i++) {\n if (a[i] > b[i]) {\n [a[i], b[i]] = [b[i], a[i]]\n }\n }\n let ans = 0\n for (let i = 1; i < a.length; i++) {\n ans += Math.abs(a[i] - a[i - 1])\n ans += Math.abs(b[i] - b[i - 1])\n }\n // console.log(a, b)\n return ans\n}\n"}, {"source_code": "var readline = require('readline');\r\nvar rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nlet ls = [];\r\n\r\nfunction solve() {\r\n let l = 0;\r\n const t = parseInt(ls[l++]);\r\n for (let i = 0; i < t; i++) {\r\n const n = parseInt(ls[l++]);\r\n const a = ls[l++].split(' ').map(v => parseInt(v));\r\n const b = ls[l++].split(' ').map(v => parseInt(v));\r\n solveInner(n, a, b);\r\n }\r\n}\r\n\r\nfunction solveInner(n, a, b) {\r\n for (let i = 0; i < n - 1; i++) {\r\n const d1 = Math.abs(a[i] - a[i + 1]) + Math.abs(b[i] - b[i + 1]);\r\n const d2 = Math.abs(a[i] - b[i + 1]) + Math.abs(b[i] - a[i + 1]);\r\n if (d1 > d2) {\r\n [a[i + 1], b[i + 1]] = [b[i + 1], a[i + 1]];\r\n }\r\n }\r\n let sum = 0;\r\n for (let i = 0; i < n - 1; i++) {\r\n sum += Math.abs(a[i] - a[i + 1]);\r\n sum += Math.abs(b[i] - b[i + 1]);\r\n }\r\n console.log(sum);\r\n}\r\n\r\nrl.on('line', (l) => ls.push(l));\r\nrl.on('close', () => solve());"}, {"source_code": "const fs = require('fs')\r\nconst inputs = fs.readFileSync(0, 'utf-8').split('\\n')\r\n\r\nfunction solve(n, a, b) {\r\n const dp = new Array(n).fill(0).map(() => [0, 0])\r\n for (let i = 1; i < n; i++) {\r\n dp[i][0] = Math.min(\r\n dp[i - 1][0] + Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]),\r\n dp[i - 1][1] + Math.abs(a[i] - b[i - 1]) + Math.abs(b[i] - a[i - 1]),\r\n )\r\n dp[i][1] = Math.min(\r\n dp[i - 1][0] + Math.abs(b[i] - a[i - 1]) + Math.abs(a[i] - b[i - 1]),\r\n dp[i - 1][1] + Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]),\r\n )\r\n }\r\n return Math.min(dp[n - 1][0], dp[n - 1][1])\r\n}\r\n\r\nvoid (function main() {\r\n const _ = Number(inputs[0])\r\n let res = []\r\n\r\n for (let __ = 0; __ < _; __++) {\r\n let n = Number(inputs[__ * 3 + 1])\r\n const a = inputs[__ * 3 + 2].trim().split(' ').map(Number)\r\n const b = inputs[__ * 3 + 3].trim().split(' ').map(Number)\r\n\r\n res.push(solve(n, a, b))\r\n }\r\n\r\n console.log(res.join('\\n'))\r\n})()\r\n"}, {"source_code": "const lines = [];\nconst rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });\nrl.on('line', line => lines.push(line));\nrl.on('close', main);\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\n\nconst ra = ()=>readline().split(' ').map(a=>+a);\n\nfunction div(val, by){\n return (val - val % by) / by;\n}\n\n\nconst calc = (n, a, b)=>{\n let res = 0;\n for (let i = 1; i < n; i++) {\n let min = Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]);\n min = Math.min(min, Math.abs(a[i] - b[i - 1]) + Math.abs(b[i] - a[i - 1]));\n res += min;\n }\n return res;\n};\n\nfunction main() {\n let T = +readline();\n for (let t = 1; t <= T; t++){\n let n = +readline();\n let a = ra();\n let b = ra();\n console.log(`${calc(n, a, b)}`);\n }\n}\n\n\n\n"}, {"source_code": "var t = +readline()\r\n\r\nfor(var i = 0; i< t; i ++) {\r\n var a = readline()\r\n var arr1 = readline().split(\" \").map(x => +x);\r\n var arr2 = readline().split(\" \").map(x => +x);\r\n print(getMinSum(arr1,arr2))\r\n}\r\n \r\n function getMinSum(arr1,arr2){\r\n\r\n var ai = arr1[0];\r\n var bi = arr2[0];\r\n var sum = 0;\r\n for(var i = 1; i s2){\r\n sum += s2;\r\n ai = arr2[i];\r\n bi = arr1[i];\r\n }else {\r\n sum += s1;\r\n ai = arr1[i];\r\n bi = arr2[i];\r\n }\r\n }\r\n return sum;\r\n\r\n}"}], "negative_code": [{"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding(\"utf-8\");\n\nlet s = \"\";\n\nprocess.stdin.on(\"data\", (data) => {\n s += data;\n});\n\nprocess.stdin.on(\"end\", (data) => {\n s = s.split(\"\\n\").filter(Boolean);\n\n main();\n});\n\nfunction main() {\n const t = Number(s[0]);\n\n let i = 1;\n while (i < 3 * t + 1) {\n const length = s[i++];\n const a = s[i++].split(\" \").map(Number);\n const b = s[i++].split(\" \").map(Number);\n\n solve(a, b);\n }\n}\n\nfunction solve(a, b) {\n function recurse(a, b, index) {\n if (index >= a.length - 1) {\n return;\n }\n\n if (a[index] < b[index]) {\n swap(a, b, index);\n }\n\n recurse(a, b, index + 1);\n }\n\n recurse(a, b, 0, 0);\n console.log(doSum(a, b));\n}\n\nfunction swap(a, b, index) {\n const temp = a[index];\n a[index] = b[index];\n b[index] = temp;\n}\n\nfunction doSum(a, b) {\n let sum = 0;\n for (let i = 0; i < a.length - 1; i++) {\n sum += Math.abs(a[i] - a[i + 1]);\n sum += Math.abs(b[i] - b[i + 1]);\n }\n return sum;\n}\n"}, {"source_code": "'use strict';\n /*jslint node:true, browser:true, es6:true*/\nconst print = console.log\nconst E = {};\nconst lines = []\nif (!process.env.JEST_WORKER_ID){\n const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })\n rl.on('line', line => {\n lines.push(line);\n });\n rl.on('close', main)\n}\nlet rli = 0;\nfunction readline() {\n return lines[rli++];\n}\nconst l = process.env.DEBUG ? console.log : ()=>{};\n \nmodule.exports = E;\n \nconst ra = ()=>readline().split(' ').map(a=>+a)\n \nconst MOD = 1e9+7;\n\nconst calc = (a, b, n)=>{\n let swap = (i)=>{\n let tmp = a[i];\n a[i] = b[i];\n b[i] = tmp;\n }\n for (let i=1; iMath.abs(a[i-1]-b[i]))\n swap(i);\n }\n let sum = 0;\n for (let i=1; i parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let a = iInpArr();\r\n let b = iInpArr();\r\n const helper = (a, b) => {\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] > b[i]) return false;\r\n if (a[i] !== b[i] && b[(i + 1) % n] + 1 < b[i]) return false;\r\n }\r\n return true;\r\n };\r\n console.log(helper(a, b) ? \"YES\" : \"NO\");\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar fs = require('fs');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\r\n\r\nfunction solve(read) {\r\n const [rn, rb, rns, re, rbs] = convertInput(read);\r\n const n = rn(),\r\n a = rns(n),\r\n b = rns(n);\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] > b[i]) return 'NO';\r\n }\r\n for (let i = 0; i < n; i++) {\r\n if (b[i] > b[(i + 1) % n] + 1 && a[i] < b[i]) return 'NO';\r\n }\r\n return 'YES';\r\n}\r\nfunction convertInput(read) {\r\n const rn = () => Number(read());\r\n const rb = () => BigInt(read());\r\n const rns = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn();\r\n return res;\r\n };\r\n const re = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rn() - 1;\r\n return res;\r\n };\r\n const rbs = n => {\r\n let res = new Array(n);\r\n for (let i = 0; i < n; i++) res[i] = rb();\r\n return res;\r\n };\r\n return [rn, rb, rns, re, rbs];\r\n}\r\nfunction main(r) {\r\n const [rn, rb, rns, re, rbs] = convertInput(r);\r\n try {\r\n let t = rn();\r\n let res = new Array(t);\r\n let limit = 100;\r\n for (let i = 0; i < t; i++) {\r\n var _solve;\r\n const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';\r\n if (t < limit) {\r\n process.stdout.write(s.toString());\r\n process.stdout.write('\\n');\r\n } else {\r\n res[i] = s;\r\n }\r\n }\r\n if (t >= limit) {\r\n return res.join('\\n');\r\n } else {\r\n return '';\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n}\r\n\r\nconst inputs = fs__default[\"default\"].readFileSync(0, 'utf-8').split(/\\s+/);\r\nvoid function () {\r\n const read = ((i = 0) => () => inputs[i++])();\r\n const output = main(read);\r\n process.stdout.write(output);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', stdin => inputString += stdin);\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(s => s.trim());\r\n main(); \r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nfunction output(x) {\r\n if (typeof x !== 'string') {\r\n x = x.toString();\r\n }\r\n //process.stdout.write(x); // without auto '\\n' (newline)\r\n console.log(x); // with auto '\\n' (newline)\r\n}\r\n\r\nfunction main() {\r\n let N = readline();\r\n\r\n for (let test = 0; test < N; test++) {\r\n let n = parseInt(readline(), 10);\r\n let arr = readline().split(' ').map(Number);\r\n let brr = readline().split(' ').map(Number);\r\n\r\n let next = (a, i) => {\r\n if (i === a.length - 1) {\r\n return a[0];\r\n } else {\r\n return a[i + 1];\r\n }\r\n }\r\n\r\n let no = false;\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] === brr[i]) {\r\n continue;\r\n }\r\n if (arr[i] > brr[i]) {\r\n no = true;\r\n break;\r\n }\r\n if (brr[i] > (next(brr, i) + 1)) {\r\n no = true;\r\n break;\r\n }\r\n }\r\n\r\n output(no ? 'NO' : 'YES');\r\n }\r\n}\r\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let a = iInpArr();\r\n let b = iInpArr();\r\n let flag = 1;\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] !== b[i]) {\r\n flag = 0;\r\n break;\r\n }\r\n }\r\n if (flag === 1) {\r\n console.log(\"YES\");\r\n continue;\r\n }\r\n flag = 1;\r\n for (let i = 0; i < n; i++) {\r\n if (b[i] < a[i]) {\r\n flag = 0;\r\n break;\r\n }\r\n }\r\n if (flag === 0) {\r\n console.log(\"NO\");\r\n continue;\r\n }\r\n flag = 1;\r\n let max = a[n - 1];\r\n for (let i = n - 2; i >= 0; i--) {\r\n if (a[i] === b[i]) {\r\n max = a[i];\r\n continue;\r\n }\r\n if (b[i] <= max) {\r\n a[i] = b[i];\r\n max = b[i];\r\n continue;\r\n } else {\r\n if (a[i] <= max) a[i] = max;\r\n else max = a[i];\r\n }\r\n }\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (a[i] === b[i]) continue;\r\n if (b[i] - 1 <= a[(i + 1) % n]) a[i] = b[i];\r\n else {\r\n flag = 0;\r\n break;\r\n }\r\n }\r\n\r\n if (flag === 0) console.log(\"NO\");\r\n else console.log(\"YES\");\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let a = iInpArr();\r\n let b = iInpArr();\r\n let flag = 1;\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] !== b[i]) {\r\n flag = 0;\r\n break;\r\n }\r\n }\r\n if (flag === 1) {\r\n console.log(\"YES\");\r\n continue;\r\n }\r\n flag = 1;\r\n let max = a[n - 1];\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (a[i] === b[i]) {\r\n max = a[i];\r\n continue;\r\n }\r\n if (a[i] < max && b[i] >= max) a[i] = max;\r\n max = Math.max(max, a[i]);\r\n }\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (a[i] === b[i]) continue;\r\n if (i === n - 1) {\r\n if (a[i] > b[i]) {\r\n flag = 0;\r\n break;\r\n } else {\r\n let dif = b[i] - a[i];\r\n let dif2 = a[0] - a[i] + 1;\r\n if (dif > dif2) {\r\n flag = 0;\r\n break;\r\n } else {\r\n a[i] = b[i];\r\n }\r\n }\r\n } else {\r\n if (a[i] > b[i]) {\r\n flag = 0;\r\n break;\r\n } else {\r\n let dif = b[i] - a[i];\r\n let dif1 = a[i + 1] - a[i] + 1;\r\n if (dif > dif1) {\r\n flag = 0;\r\n break;\r\n } else a[i] = b[i];\r\n }\r\n }\r\n }\r\n if (flag === 1) {\r\n console.log(\"YES\");\r\n } else {\r\n console.log(\"NO\");\r\n }\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nfunction iInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n}\r\nfunction BInpArr() {\r\n return readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => BigInt(cur));\r\n}\r\nfunction string() {\r\n return readline().trim();\r\n}\r\nfunction stringArr() {\r\n return readline().trim().split(\"\");\r\n}\r\n\r\nfunction stringArr1() {\r\n return readline().trim().split(\" \");\r\n}\r\nfunction getValue() {\r\n return parseInt(readline());\r\n}\r\nlet mod = 1e9 + 7;\r\nmod = BigInt(mod);\r\nconst pow = (num, exp, mod) => {\r\n if (exp === BigInt(0)) return BigInt(1);\r\n let x = pow(num, exp / BigInt(2), mod);\r\n if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;\r\n else return (x * x) % mod;\r\n};\r\nconst inverse = (num, exp) => {\r\n return pow(BigInt(num), BigInt(exp), BigInt(mod));\r\n};\r\nconst solve = () => {\r\n let t = getValue();\r\n while (t--) {\r\n let n = getValue();\r\n let a = iInpArr();\r\n let b = iInpArr();\r\n let flag = 1;\r\n for (let i = 0; i < n; i++) {\r\n if (a[i] !== b[i]) {\r\n flag = 0;\r\n break;\r\n }\r\n }\r\n if (flag === 1) {\r\n console.log(\"YES\");\r\n continue;\r\n }\r\n flag = 1;\r\n let max = a[n - 1];\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (a[i] === b[i]) {\r\n max = a[i];\r\n continue;\r\n }\r\n if (a[i] < max && b[i] > max) a[i] = max;\r\n max = Math.max(max, a[i]);\r\n }\r\n for (let i = n - 1; i >= 0; i--) {\r\n if (a[i] === b[i]) continue;\r\n if (i === n - 1) {\r\n if (a[i] > b[i]) {\r\n flag = 0;\r\n break;\r\n } else {\r\n let dif = b[i] - a[i];\r\n let dif2 = a[0] - a[i] + 1;\r\n if (dif > dif2) {\r\n flag = 0;\r\n break;\r\n } else {\r\n a[i] = b[i];\r\n }\r\n }\r\n } else {\r\n if (a[i] > b[i]) {\r\n flag = 0;\r\n break;\r\n } else {\r\n let dif = b[i] - a[i];\r\n let dif1 = a[i + 1] - a[i] + 1;\r\n if (dif > dif1) {\r\n flag = 0;\r\n break;\r\n } else a[i] = b[i];\r\n }\r\n }\r\n }\r\n if (flag === 1) {\r\n console.log(\"YES\");\r\n } else {\r\n console.log(\"NO\");\r\n }\r\n }\r\n};\r\nsolve();\r\n"}], "src_uid": "9851ff47c77e13f62be1edaf3d74c4ad"} {"nl": {"description": "You are given a sequence $$$a_1, a_2, \\dots, a_n$$$ consisting of $$$n$$$ non-zero integers (i.e. $$$a_i \\ne 0$$$). You have to calculate two following values: the number of pairs of indices $$$(l, r)$$$ $$$(l \\le r)$$$ such that $$$a_l \\cdot a_{l + 1} \\dots a_{r - 1} \\cdot a_r$$$ is negative; the number of pairs of indices $$$(l, r)$$$ $$$(l \\le r)$$$ such that $$$a_l \\cdot a_{l + 1} \\dots a_{r - 1} \\cdot a_r$$$ is positive; ", "input_spec": "The first line contains one integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^{5})$$$ — the number of elements in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(-10^{9} \\le a_i \\le 10^{9}; a_i \\neq 0)$$$ — the elements of the sequence.", "output_spec": "Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.", "sample_inputs": ["5\n5 -3 3 -1 1", "10\n4 2 -4 3 1 2 -4 3 2 3", "5\n-1 -2 -3 -4 -5"], "sample_outputs": ["8 7", "28 27", "9 6"], "notes": null}, "positive_code": [{"source_code": "const n = Number(readline());\nconst a = [1].concat(readline().split(\" \").slice(0, n)).map(x => Number(x < 0));\nfor (var i = 1; i <= n; i++)\n a[i] += a[i - 1];\nconst counts = [0, 0];\nfor (var i = 0; i <= n; i++) {\n a[i] &= 1;\n counts[a[i]]++;\n}\nvar negative = 0;\nfor (var i = 0; i <= n;) {\n var cur = a[i];\n var next = 1 - cur;\n var j = a.indexOf(next, i);\n if (j === -1) break;\n var diff = j - i;\n negative += diff * counts[next];\n counts[cur] -= diff;\n i = j;\n}\nprint(`${negative} ${n * (n + 1) * 0.5 - negative}`);\n"}, {"source_code": "const n = Number(readline());\nconst a = [1].concat(readline().split(\" \").slice(0, n)).map(x => Number(x < 0));\nfor (var i = 1; i <= n; i++)\n a[i] += a[i - 1];\nconst counts = [0, 0];\nfor (var i = 0; i <= n; i++) {\n a[i] &= 1;\n counts[a[i]]++;\n}\nvar negative = 0;\nfor (var i = 0; i <= n;) {\n var cur = a[i];\n var next = 1 - cur;\n var j = a.indexOf(next, i);\n if (j === -1) break;\n var diff = j - i;\n negative += diff * counts[next];\n counts[cur] -= diff;\n i = j;\n}\nprint(`${negative} ${n * (n + 1) * 0.5 - negative}`);\n"}], "negative_code": [], "src_uid": "78d3acc3ade53f488739a59100bfcebd"} {"nl": {"description": "Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) — the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\\le n, d \\le 10^9$$$, $$$1 \\le x, y \\le n$$$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.", "output_spec": "Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.", "sample_inputs": ["3\n10 4 5 2\n5 1 3 4\n20 4 19 3"], "sample_outputs": ["4\n-1\n5"], "notes": "NoteIn the first test case the optimal sequence is: $$$4 \\rightarrow 2 \\rightarrow 1 \\rightarrow 3 \\rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \\rightarrow 7 \\rightarrow 10 \\rightarrow 13 \\rightarrow 16 \\rightarrow 19$$$."}, "positive_code": [{"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n\nlet l = 0;\nlet n = 0\n\nrl.on('line', (input) => {\n if (l === 0) {\n n = parseInt(input)\n } else {\n if (l === n)\n rl.close();\n\n let arr = input.split(\" \").map(x => parseInt(x))\n // console.log((arr[1]-1)%arr[3])\n let max = 999999999999\n let ans1 = max\n let ans2 = max\n let ans3 = max\n if (Math.abs(arr[2] - arr[1]) % arr[3] === 0) {\n ans1 = Math.round(Math.abs(arr[2] - arr[1]) / arr[3])\n }\n if (Math.abs(arr[2] - 1) % arr[3] === 0) {\n let rest1 = Math.abs(arr[2] - 1) / arr[3]\n let rest2 = Math.abs(arr[1] - 1) / arr[3]\n ans2 = Math.round(rest1) + Math.ceil(rest2)\n\n }\n if (Math.abs(arr[0] - arr[2]) % arr[3] === 0) {\n let rest1 = Math.abs(arr[1] - arr[0]) / arr[3]\n let rest2 = Math.abs(arr[0] - arr[2]) / arr[3]\n ans3 = Math.ceil(rest1) + Math.round(rest2)\n }\n //console.log(ans1, ans2, ans3)\n let mn = Math.min(ans1, Math.min(ans2, ans3))\n console.log(mn === max ? -1 : mn)\n }\n l++\n});\n"}, {"source_code": "var t = readline();\nfor (var i=0; i {\n if (l === 0) {\n n = parseInt(input)\n } else {\n if (l === n)\n rl.close();\n\n let arr = input.split(\" \").map(x => parseInt(x))\n if (Math.abs(arr[2] - arr[1]) % arr[3] === 0) {\n console.log(Math.floor(Math.abs(arr[2] - arr[1]) / arr[3]))\n } else if (Math.abs(Math.min(arr[2], arr[1]) - 2) % arr[3] === 0 &&\n Math.abs(Math.max(arr[2], arr[1]) - 1) % arr[3] === 0) {\n console.log(Math.floor(Math.max(arr[2], arr[1]) - 1 / arr[3]))\n } else\n console.log(\"-1\")\n }\n l++\n});\n"}, {"source_code": "var t = readline();\nfor (var i=0; i {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n\n main();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction print(s) {\n process.stdout.write(`${s}`);\n}\n// Make a Snippet for the code above this and then write your logic in main();\n\nfunction main() {\n // input\n const n = +readline();\n let a = readline().split(' ').map(x => parseInt(x));\n let r = 0;\n if (a.length > 2) {\n let min = Number.MAX_SAFE_INTEGER, max = Number.MIN_SAFE_INTEGER;\n for (let i = 0; i < n; i++) {\n min = Math.min(min, a[i]);\n max = Math.max(max, a[i]);\n }\n for (let i = 0; i < n; i++) {\n if (a[i] > min && a[i] < max) {\n r++;\n }\n }\n }\n print(r);\n}\n\n"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n return;\n }\n\n const arr = d.split(' ').map(Number);\n const min = Math.min(...arr);\n const max = Math.max(...arr);\n let ans = 0;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] > min && arr[i] < max) {\n ans++;\n }\n }\n\n console.log(ans);\n\n c++;\n});\n"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readint() {\n let line = readline().split(' ').map(function(num) {\n return parseInt(num);\n });\n return line;\n}\n\nfunction readfloat() {\n let line = readline().split(' ').map(function(num) {\n return parseFloat(num);\n });\n return line;\n}\n\nfunction print(x) {\n console.log(x);\n}\n\nfunction write(x) {\n process.stdout.write(x);\n}\nfunction main() {\n let [n] = readint();\n let a = readint();\n let all = a.length;\n let mx = a[0];\n let mn = a[0];\n a.forEach(element => {\n if(mx < element) mx = element;\n if(mn > element) mn = element;\n });\n let mxcount = 0, \n mncount = 0;\n a.forEach(element => {\n if(element == mx) mxcount++;\n if(element == mn) mncount++;\n });\n if(mx != mn)\n print(a.length - mncount - mxcount);\n else \n print(a.length - mncount);\n}"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet input = [];\nreadline.on('line', line => {\n input.push(line);\n});\nprocess.stdin.on('end', () => {\n// const n = parseInt(input[0], 10);\nlet secondLine = input[1].split(' ');\nconst nums = secondLine.map((a) => parseInt(a, 10));\n \nif (nums.length <= 2) {\n console.log(0);\n return\n}\n \nlet min = nums[0];\nlet max = nums[0];\nlet cmin = 1;\nlet cmax = 1;\nlet result = 0;\n \nfor (let i=1; i< nums.length; i++) {\n const num = nums[i];\n const nmin = Math.min(min, num);\n if (nmin !== min) {\n if (min !== max) {\n result += cmin;\n }\n cmin = 1;\n }\n if (num === min) {\n cmin += 1;\n }\n const nmax = Math.max(max, num);\n if (nmax !== max) {\n if (min !== max) {\n result += cmax;\n }\n cmax = 1;\n }\n if (num === max) {\n cmax += 1;\n }\n if (nmin === min && nmax === max && nmax !== num && nmin !== num) {\n result += 1;\n }\n// console.log({num ,min, nmin, max, nmax, result});\n min = nmin;\n max = nmax;\n}\nconsole.log(result);\n});"}, {"source_code": "var n = parseInt(readline());\nvar input = readline().split(' ').map(x=>parseInt(x));\nvar res=0;\ninput.sort((a,b)=>a-b);\nvar small=input[0];\nvar big=input[n-1];\n\nfor(var i=1;i<=n-2;i++){\n if(input[i]>small && input[i]parseInt(x));\nvar res=0;\n\nvar mn=findMin(input);\nvar mx=findMax(input);\n\nfor(var i=0;imn && input[i]a-b),\n counter = 0;\n\n big = stewards[stewards.length - 1],\n small = stewards[0];\n\nfor (var i = 1; i < stewards.length - 1; i++){\n \n if(stewards[i] > small && stewards[i] < big)\n counter++;\n \n // var count = i,\n // thereIsBefore = false,\n // thereIsAfter = false;\n // while(count > 0) {\n // if(stewards[count - 1] < stewards[i]){\n // thereIsBefore = true;\n // break;\n // }\n // count--;\n // }\n // while(count < stewards.length - 1) {\n // if(stewards[count + 1] > stewards[i]){\n // thereIsAfter = true;\n // break;\n // }\n // count++;\n // }\n // if(thereIsAfter && thereIsBefore)\n // counter++;\n\n}\n\nprint(counter);"}, {"source_code": "function main(n,arr){\n\n var min = Infinity;\n var max = -Infinity;\n var cnt = 0;\n\n for(var i = 0 ; i < n ; i++){\n\n max = Math.max(max,arr[i]);\n min = Math.min(min,arr[i]);\n\n }\n\n for(var i = 0 ; i < n ; i++){\n if(arr[i] > min && arr[i] < max)cnt++;\n }\n\n print(cnt);\n}\n\n\nvar n = parseInt(readline());\n\nvar arr = readline().split(' ');\nfor(var i = 0 ; i < arr.length ; i++)arr[i] = parseInt(arr[i]);\n\nmain(n,arr);\n"}, {"source_code": "var n = parseInt(readline());\nvar p = readline().split(' ').map(function(x){\n return parseInt(x);\n});\nvar minv = 1e9;\nvar maxv = -1e9;\np.forEach(function(x){\n minv = Math.min(minv, x);\n maxv = Math.max(maxv, x); \n});\nprint(p.filter(function(x){\n return minv < x && x < maxv;\n}).length);"}, {"source_code": "var numberOfSteward = Number(readline())\n var stewardsStrength = readline().split(' ').map(Number)\n\n stewardsStrength = stewardsStrength.sort((a, b) => a - b)\n\n var i = 1\n var count = 0\n while (i < numberOfSteward) {\n if (stewardsStrength[0] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[stewardsStrength.length - 1]) {\n count += 1\n }\n i++\n }\n\n print(count)"}, {"source_code": "var numberOfSteward = Number(readline())\n var stewardsStrength = readline().split(' ').map(Number)\n\n var weaker = Infinity\n var stronger = -Infinity\n for (var i = 0; i < numberOfSteward; i++) {\n weaker = Math.min(weaker, stewardsStrength[i])\n stronger = Math.max(stronger, stewardsStrength[i])\n }\n\n var count = 0\n for (var i = 0; i < numberOfSteward; i++) {\n if (weaker < stewardsStrength[i] && stewardsStrength[i] < stronger) {\n count += 1\n }\n }\n\n print(count)"}, {"source_code": "var n = parseInt(readline())\nvar list = readline().trim().split(' ')\nvar min = 1e9+1, max = -1\nvar dict = {}\nvar total = list.length\nfor (var num of list) {\n num = parseInt(num)\n min = min > num ? num : min\n max = max < num ? num : max\n dict[num] = (dict[num] || 0) + 1\n}\n\nif (min === max) {\n print(0)\n} else {\n print (total - dict[min] - dict[max])\n}\n"}, {"source_code": "var stuartsCount = +readline(),\n stuartsRaits = readline().split(/\\s+/).slice(0, stuartsCount),\n minRait = Math.min.apply(null, stuartsRaits),\n maxRait = Math.max.apply(null, stuartsRaits);\n\nprint(\n stuartsRaits.reduce(function(count, rait){\n return (rait > minRait && rait < maxRait) ? count + 1 : count;\n }, 0)\n);"}, {"source_code": "// Generated by CoffeeScript 1.12.4\n(function() {\n var count, max, min, stuarts;\n\n readline();\n\n stuarts = readline().split(\" \").map(Number);\n\n min = stuarts[0];\n\n max = 0;\n\n count = 0;\n\n stuarts.forEach(function(num) {\n if (num < min) {\n min = num;\n }\n if (num > max) {\n return max = num;\n }\n });\n\n stuarts.forEach(function(num) {\n if (num > min && num < max) {\n return count++;\n }\n });\n\n write(count);\n\n}).call(this);\n"}, {"source_code": "console = {log: ()=>{}}\nvar count, max, min, stuarts;\nreadline();\nstuarts = readline().split(\" \").map(Number);\nmin = stuarts[0];\nmax = 0;\ncount = 0;\nstuarts.forEach(function(num) {\n if (num < min) {\n min = num;\n }\n if (num > max) {\n return max = num;\n }\n});\nstuarts.forEach(function(num) {\n if (num > min && num < max) {\n return count++;\n }\n});\nwrite(count);\n\n"}, {"source_code": "try {require(\"codeforces\")} catch(e){console = {log: function(){}, error: function(){}}};\n\nvar count, max, min, stuarts;\nreadline();\nstuarts = readline().split(\" \").map(Number);\nmin = stuarts[0];\nmax = 0;\ncount = 0;\nstuarts.forEach(function(num) {\n if (num < min) {\n min = num;\n }\n if (num > max) {\n return max = num;\n }\n});\nconsole.log(\"ssss\");\nstuarts.forEach(function(num) {\n if (num > min && num < max) {\n return count++;\n }\n});\nwrite(count);"}, {"source_code": "var n = parseInt(readline());\nvar total = readline().split(\" \").map(Number).sort((a, b) => a - b);\n\nvar count = total.length - 2;\n\nfor (var i = 0; i < total.length; i++) {\n if ((i !== 0 && total[i] === total[0]) || \n (i !== total.length - 1 && total[i] === total[total.length - 1])) {\n count--;\n }\n}\n\nprint(count < 0 ? 0: count);"}], "negative_code": [{"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readint() {\n let line = readline().split(' ').map(function(num) {\n return parseInt(num);\n });\n return line;\n}\n\nfunction readfloat() {\n let line = readline().split(' ').map(function(num) {\n return parseFloat(num);\n });\n return line;\n}\n\nfunction print(x) {\n console.log(x);\n}\n\nfunction write(x) {\n process.stdout.write(x);\n}\nfunction main() {\n let [n] = readint();\n let a = readint();\n let all =a.length;\n let mx = a[0];\n let mn = a[0];\n a.forEach(element => {\n if(mx < element) mx = element;\n if(mn > element) mn = element;\n });\n let mxcount = 0, \n mncount = 0;\n a.forEach(element => {\n if(element == mx) mxcount++;\n if(element == mn) mncount++;\n });\n print(a.length - mncount - mncount);\n}"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet input = [];\nreadline.on('line', line => {\n input.push(line);\n});\nprocess.stdin.on('end', () => {\n// const n = parseInt(input[0], 10);\nlet secondLine = input[1].split(' ');\nconst nums = secondLine.map((a) => parseInt(a, 10));\n \nif (nums.length <= 2) {\n console.log(0);\n}\n \nlet min = nums[0];\nlet max = nums[0];\nlet cmin = 1;\nlet cmax = 1;\nlet result = 0;\n \nfor (let i=1; i< nums.length; i++) {\n const num = nums[i];\n const nmin = Math.min(min, num);\n if (nmin !== min && min !== max) {\n result += cmin;\n cmin = 1;\n }\n if (num === min) {\n cmin += 1;\n }\n const nmax = Math.max(max, num);\n if (nmax !== max && min !== max) {\n result += cmax;\n cmax = 1;\n }\n if (num === max) {\n cmax += 1;\n }\n if (nmin === min && nmax === max && nmax !== num && nmin !== num) {\n result += 1;\n }\n// console.log({num ,min, nmin, max, nmax, result});\n min = nmin;\n max = nmax;\n}\nconsole.log(result);\n});\n "}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet input = [];\nreadline.on('line', line => {\n input.push(line);\n});\nprocess.stdin.on('end', () => {\n// const n = parseInt(input[0], 10);\nlet secondLine = input[1].split(' ');\nconst nums = secondLine.map((a) => parseInt(a, 10));\n\nif (nums.length <= 2) {\n return 0;\n}\n\nlet min = nums[0];\nlet max = nums[0];\nlet cmin = 1;\nlet cmax = 1;\nlet result = 0;\n\nfor (let i=1; i< nums.length; i++) {\n const num = nums[i];\n const nmin = Math.min(min, num);\n if (nmin !== min && min !== max) {\n result += cmin;\n cmin = 1;\n }\n if (num === min) {\n cmin += 1;\n }\n const nmax = Math.max(max, num);\n if (nmax !== max && min !== max) {\n result += cmax;\n cmax = 1;\n }\n if (num === max) {\n cmax += 1;\n }\n if (nmin === min && nmax === max && nmax !== num && nmin !== num) {\n result += 1;\n }\n// console.log({num ,min, nmin, max, nmax, result});\n min = nmin;\n max = nmax;\n}\nreturn result;\n});\n\n"}, {"source_code": "const readline = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout\n});\nlet input = [];\nreadline.on('line', line => {\n input.push(line);\n});\nprocess.stdin.on('end', () => {\n// const n = parseInt(input[0], 10);\nlet secondLine = input[1].split(' ');\nconst nums = secondLine.map((a) => parseInt(a, 10));\n \nif (nums.length <= 2) {\n console.log(0);\n return\n}\n \nlet min = nums[0];\nlet max = nums[0];\nlet cmin = 1;\nlet cmax = 1;\nlet result = 0;\n \nfor (let i=1; i< nums.length; i++) {\n const num = nums[i];\n const nmin = Math.min(min, num);\n if (nmin !== min && min !== max) {\n result += cmin;\n cmin = 1;\n }\n if (num === min) {\n cmin += 1;\n }\n const nmax = Math.max(max, num);\n if (nmax !== max && min !== max) {\n result += cmax;\n cmax = 1;\n }\n if (num === max) {\n cmax += 1;\n }\n if (nmin === min && nmax === max && nmax !== num && nmin !== num) {\n result += 1;\n }\n// console.log({num ,min, nmin, max, nmax, result});\n min = nmin;\n max = nmax;\n}\nconsole.log(result);\n});\n "}, {"source_code": "function findMin(array){\n var mn = Infinity;\n for(var i=0;iparseInt(x));\nvar res=0;\n\nvar mn=findMin(input);\nvar mx=findMax(input);\n\nfor(var i=1;i<=n-2;i++){\n if(input[i]>mn && input[i]parseInt(x));\nvar res=0;\ninput.sort((a,b)=>a-b);\nfor(var i=1;i 0) {\n if(stewards[count - 1] < stewards[i]){\n thereIsBefore = true;\n break;\n }\n count--;\n }\n while(count < stewards.length - 1) {\n if(stewards[count + 1] > stewards[i]){\n thereIsAfter = true;\n break;\n }\n count++;\n }\n if(thereIsAfter && thereIsBefore)\n counter++;\n\n}\n\nprint(counter);"}, {"source_code": "var numberOfSteward = Number(readline())\n var stewardsStrength = readline().split(' ').map(Number)\n\n stewardsStrength = stewardsStrength.sort((a, b) => a - b)\n\n var i = 1\n var count = 0\n while (i < numberOfSteward - 1) {\n if (stewardsStrength[i - 1] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[i + 1]) {\n count += 1\n }\n i++\n }\n\n print(count)"}, {"source_code": "var numberOfSteward = Number(readline())\n var stewardsStrength = readline().split(' ').map(Number)\n\n var weaker = Infinity\n var stronger = -Infinity\n for (var i = 0; i < numberOfSteward; i++) {\n weaker = Math.min(weaker, numberOfSteward[i])\n stronger = Math.max(stronger, numberOfSteward[i])\n }\n\n var count = 0\n for (var i = 0; i < numberOfSteward; i++) {\n if (stewardsStrength[0] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[stewardsStrength.length - 1]) {\n count += 1\n }\n }\n\n print(count)"}, {"source_code": "var numberOfSteward = Number(readline())\n var stewardsStrength = readline().split(' ').map(Number)\n \n var weaker = Infinity\n var stronger = -Infinity\n for (var i = 0; i < numberOfSteward; i++) {\n weaker = Math.min(weaker, numberOfSteward[i])\n stronger = Math.max(stronger, numberOfSteward[i])\n }\n \n var count = 0\n for (var i = 0; i < numberOfSteward; i++) {\n if (weaker < stewardsStrength[i] && stewardsStrength[i] < stronger) {\n count += 1\n }\n }\n \n print(count)"}, {"source_code": "var numberOfSteward = Number(readline())\n var stewardsStrength = readline().split(' ').map(Number)\n\n stewardsStrength = stewardsStrength.sort((a, b) => a - b)\n\n var i = 1\n var count = 0\n while (i < numberOfSteward - 1) {\n if (stewardsStrength[i - 1] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[i + 1]) {\n count += 1\n i += 3\n } else {\n i++\n }\n }\n\n print(count)"}, {"source_code": "var stuartsCount = +readline(),\n stuartsRaits = readline().split(/\\s+/),\n minRait = stuartsRaits[0],\n maxRait = stuartsRaits[0],\n result = 0;\n \nstuartsRaits.forEach(function(rait){\n var tmpRait;\n \n if(rait > maxRait) {\n tmpRait = maxRait;\n maxRait = rait;\n checkNeedGuard(tmpRait);\n return;\n }\n \n if(rait < minRait) {\n tmpRait = minRait;\n minRait = rait;\n checkNeedGuard(tmpRait);\n return;\n }\n \n checkNeedGuard();\n});\n\nfunction checkNeedGuard(rait) {\n if(rait > minRait && rait < maxRait) result++;\n}\n\nprint(result);"}, {"source_code": "try {require(\"codeforces\")} catch(e){console = {log: function(){}, error: function(){}}};\n\nvar count, max, min, stuarts;\nreadline();\nstuarts = readline().split(\" \").map(Number);\nmin = stuarts[0];\nmax = 0;\ncount = 0;\nstuarts.forEach(function(num) {\n if (num < min) {\n min = num;\n }\n if (num > max) {\n return max = num;\n }\n});\nconsole.log(\"ssss\");\nstuarts.forEach(function(num) {\n if (num > min && num < max) {\n return count+2;\n }\n});\nwrite(count);"}, {"source_code": "var n = parseInt(readline());\nvar total = readline().split(\" \").map(Number).sort((a, b) => a - b);\n\nvar se = new Set(total);\n\nif (se.size <= 2) {\n print(0);\n} else {\n print(se.size - 2);\n}"}, {"source_code": "var n = parseInt(readline());\nvar total = readline().split(\" \").map(Number).sort((a, b) => a - b);\n\nvar count = total.length - 2;\n\nfor (var i = 0; i < total.length; i++) {\n if (total[i] === total[0] || total[i] === total[total.length - 1]) {\n count--;\n }\n}\n\nprint(count < 0 ? 0: count);"}], "src_uid": "acaa8935e6139ad1609d62bb5d35128a"} {"nl": {"description": "Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.", "input_spec": "The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).", "output_spec": "For each query print on a single line: either \"Yes\", if Alexey can enter the university, or \"No\" otherwise.", "sample_inputs": ["2\n5 2 3\n6 4 5"], "sample_outputs": ["Yes\nNo"], "notes": "NoteYou can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid."}, "positive_code": [{"source_code": "function trim(s) {\n\treturn s.replace(/^\\s+|\\s+$/gm, '');\n}\n\nfunction tokenize(s) {\n\treturn trim(s).split(/\\s+/);\n}\n\nfunction tokenizeIntegers(s) {\n\tvar tokens = tokenize(s);\n\tfor (var i = 0; i < tokens.length; i += 1) {\n\t\ttokens[i] = parseInt(tokens[i]);\n\t};\n\treturn tokens;\n}\n\nfunction main() {\n\tvar caseNum = parseInt(readline());\n\tfor (var caseIndex = 0; caseIndex < caseNum; ++caseIndex) {\n\t\tvar integers = tokenizeIntegers(readline());\n\t\tvar target = integers[0], min = integers[1], max = integers[2];\n\n\t\tvar coinNum = Math.floor(target/min);\n\t\tprint(coinNum*max >= target ? \"Yes\" : \"No\");\n\t}\n}\n\nmain();\n"}], "negative_code": [], "src_uid": "287505698b6c850a768ee35d2e37753e"} {"nl": {"description": "You are given three integers $$$a$$$, $$$b$$$ and $$$c$$$.Find two positive integers $$$x$$$ and $$$y$$$ ($$$x > 0$$$, $$$y > 0$$$) such that: the decimal representation of $$$x$$$ without leading zeroes consists of $$$a$$$ digits; the decimal representation of $$$y$$$ without leading zeroes consists of $$$b$$$ digits; the decimal representation of $$$gcd(x, y)$$$ without leading zeroes consists of $$$c$$$ digits. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.Output $$$x$$$ and $$$y$$$. If there are multiple answers, output any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 285$$$) — the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \\le a, b \\le 9$$$, $$$1 \\le c \\le min(a, b)$$$) — the required lengths of the numbers. It can be shown that the answer exists for all testcases under the given constraints. Additional constraint on the input: all testcases are different.", "output_spec": "For each testcase print two positive integers — $$$x$$$ and $$$y$$$ ($$$x > 0$$$, $$$y > 0$$$) such that the decimal representation of $$$x$$$ without leading zeroes consists of $$$a$$$ digits; the decimal representation of $$$y$$$ without leading zeroes consists of $$$b$$$ digits; the decimal representation of $$$gcd(x, y)$$$ without leading zeroes consists of $$$c$$$ digits. ", "sample_inputs": ["4\n2 3 1\n2 2 2\n6 6 2\n1 1 1"], "sample_outputs": ["11 492\n13 26\n140133 160776\n1 1"], "notes": "NoteIn the example: $$$gcd(11, 492) = 1$$$ $$$gcd(13, 26) = 13$$$ $$$gcd(140133, 160776) = 21$$$ $$$gcd(1, 1) = 1$$$ "}, "positive_code": [{"source_code": "/*\r\n| In English По-русски\r\nlukas_rimkus | Logout\r\n\r\nHOME\r\nTOP\r\nCONTESTS\r\nGYM\r\nPROBLEMSET\r\nGROUPS\r\nRATING\r\nEDU\r\nAPI\r\nCALENDAR\r\nHELP\r\n\r\nPROBLEMSSUBMIT CODEMY SUBMISSIONSSTATUSHACKSSTANDINGSCUSTOM INVOCATION\r\n \r\nMy contest submissions\r\n \r\n#\tWhen\tWho\tProblem\tLang\tVerdict\tTime\tMemory\r\n112854886\tApr/12/2021 18:31UTC+2\tlukas_rimkus\tB - GCD Length\tNode.js\tTime limit exceeded on test 2\t2000 ms\t12000 KB\r\n112853780\tApr/12/2021 18:29UTC+2\tlukas_rimkus\tB - GCD Length\tNode.js\tWrong answer on test 1\t31 ms\t0 KB\r\n112852890\tApr/12/2021 18:27UTC+2\tlukas_rimkus\tB - GCD Length\tNode.js\tWrong answer on test 1\t31 ms\t0 KB\r\n112851646\tApr/12/2021 18:24UTC+2\tlukas_rimkus\tB - GCD Length\tNode.js\tTime limit exceeded on test 1\t2000 ms\t11800 KB\r\n112851156\tApr/12/2021 18:23UTC+2\tlukas_rimkus\tB - GCD Length\tNode.js\tWrong answer on test 1\t46 ms\t0 KB\r\n112849514\tApr/12/2021 18:19UTC+2\tlukas_rimkus\tB - GCD Length\tNode.js\tTime limit exceeded on test 2\t2000 ms\t11800 KB\r\n112845911\tApr/12/2021 18:11UTC+2\tlukas_rimkus\tB - GCD Length\tNode.js\tWrong answer on test 1\t373 ms\t11300 KB\r\n112834898\tApr/12/2021 17:47UTC+2\tlukas_rimkus\tA - Review Site\tNode.js\tAccepted\t218 ms\t6100 KB\r\n \r\nEducational Codeforces Round 107 (Rated for Div. 2)\r\nFinished\r\nPractice\r\nAdd to favourites\r\n \r\n→ Virtual participation\r\nVirtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest.\r\n \r\n→ Practice\r\nYou are registered for practice. You can solve problems unofficially. Results can be found in the contest status and in the bottom of standings.\r\n \r\n→ Clone Contest to Mashup\r\nYou can clone this contest to a mashup.\r\n\r\n \r\n→ Contest materials\r\nAnnouncement\r\n\r\nCodeforces (c) Copyright 2010-2021 Mike Mirzayanov\r\nThe only programming contests Web 2.0 platform\r\nServer time: Apr/12/2021 23:55:11UTC+2 (h2).\r\nMobile version, switch to desktop version.\r\nPrivacy Policy\r\nSupported by\r\nTelegram ИТМО\r\nBy lukas_rimkus, contest: Educational Codeforces Round 107 (Rated for Div. 2), problem: (B) GCD Length, Time limit exceeded on test 2, #, Copy\r\n*/\r\n'use-strict'\r\n \r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n \r\nlet data = '';\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n \r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n \r\n let testCases = parseInt(readLine());\r\n \r\n while(testCases--) {\r\n const [a,b,c] = readLine().split(' ').map(Number );\r\n const x = Math.pow(10,a-1) + Math.pow(10,c-1);\r\n const y = Math.pow(10,b-1);\r\n console.log(x,y)\r\n \r\n }\r\n})\r\n\r\nfunction readLine(){\r\n return data[currentLine++]\r\n}"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\n\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar a = nextInt();\r\n\t\tvar b = nextInt();\r\n\t\tvar c = nextInt();\r\n\t\tvar g = Math.pow(10, c - 1);\r\n\t\tvar x = g;\r\n\t\tvar y = g;\r\n\t\twhile(x < Math.pow(10, a - 1)){\r\n\t\t\tx *= 3;\r\n\t\t}\r\n\t\twhile(y < Math.pow(10, b - 1)){\r\n\t\t\ty *= 7;\r\n\t\t}\r\n\t\tmyout(x + \" \" + y);\r\n\t}\r\n}\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));\r\n while (t--) {\r\n let [a, b, c] = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let g = 1,\r\n f = 1,\r\n s = 1;\r\n for (let i = 2; i <= c; i++) g *= 10;\r\n for (let i = 2; i <= a; i++) f *= 10;\r\n for (let i = 2; i <= b; i++) s *= 10;\r\n if (f >= s) s += g;\r\n else f += g;\r\n console.log(f + \" \" + s);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(a, b, c) {\r\n function getPrime(n) {\r\n next: while (n++) {\r\n for (let i = 2; i <= n / i; i++) {\r\n if (n % i === 0) continue next;\r\n }\r\n return n;\r\n }\r\n return 1;\r\n }\r\n let z = getPrime(10 ** (c - 1));\r\n let x = 1;\r\n let y = 1;\r\n if (a === b) {\r\n x = getPrime(Math.floor(10 ** (a - 1) / z) + 1);\r\n y = getPrime(x);\r\n } else {\r\n x = getPrime(Math.floor(10 ** (a - 1) / z) + 1);\r\n y = getPrime(Math.floor(10 ** (b - 1) / z) + 1);\r\n }\r\n x = BigInt(x) * BigInt(z);\r\n y = BigInt(y) * BigInt(z);\r\n return `${x.toString()} ${y.toString()}`;\r\n}\r\n\r\nasync function main(read) {\r\n let res = [];\r\n let t = Number(await read());\r\n while (t--) {\r\n const [a, b, c] = (await read()).split(' ').map(Number);\r\n res.push(solve(a, b, c));\r\n }\r\n console.log(res.join('\\n'));\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "const readline = require(\"readline\");\r\nconst rl = readline.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n})\r\nlet input = [];\r\nrl.on('line', line => {\r\n input.push(line);\r\n})\r\nrl.on('close', line => {\r\n var t = Number(input[0]);\r\n for (var i = 1; i < input.length; i++) {\r\n var [a, b, c] = input[i].split(\" \").map((i) => {\r\n return Number(i);\r\n });\r\n var num1 = 10 ** (a - 1);\r\n var num2 = 10 ** (b - 1) + 10 ** (c - 1);\r\n console.log(num1 + \" \" + num2);\r\n }\r\n})"}, {"source_code": "'use strict';\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf-8');\r\n\r\nlet inputString = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', inputStdin => {\r\n inputString += inputStdin;\r\n});\r\n\r\nprocess.stdin.on('end', _ => {\r\n inputString = inputString.trim().split('\\n').map(string => {\r\n return string.trim();\r\n });\r\n\r\n main();\r\n});\r\n\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n}\r\n\r\nvar maxN = 2 * 1e5 + 10\r\nvar mod = BigInt(1e9 + 7)\r\n\r\n// Make a Snippet for the code above this and then write your logic in main();\r\n\r\nfunction main() {\r\n var j = 0\r\n var array2 = [\r\n 3, 5, 11,\r\n 13, 101, 103,\r\n 1009, 1013, 10007,\r\n 10009, 100003, 100019,\r\n 1000003, 1000033, 10000019,\r\n 10000079,\r\n 179424673, 179424691\r\n ]\r\n\r\n const xx = readline();\r\n Array(Number(xx)).fill(1).map((t, i) => {\r\n // var n = parseInt(readline());\r\n // var [n, m] = readline().split(' ').map((x, iii) => {\r\n // return parseInt(x)\r\n // })\r\n var [a, b, c] = readline().split(' ').map((x, iii) => {\r\n return parseInt(x)\r\n });\r\n a--\r\n b--\r\n var cc = c - 1\r\n if (cc === 0) {\r\n console.log(array2[Math.floor(a * 2)], array2[b * 2 + 1])\r\n return\r\n }\r\n a = a - cc\r\n b = b - cc\r\n console.log(array2[a * 2] * Math.pow(10, cc), array2[b * 2 + 1] * Math.pow(10, cc))\r\n })\r\n}\r\n\r\nvar eratosthenes = function (n) {\r\n // Eratosthenes algorithm to find all primes under n\r\n var array = [], upperLimit = Math.sqrt(n), output = [];\r\n\r\n // Make an array from 2 to (n - 1)\r\n for (var i = 0; i < n; i++) {\r\n array.push(true);\r\n }\r\n\r\n // Remove multiples of primes starting from 2, 3, 5,...\r\n for (var i = 2; i <= upperLimit; i++) {\r\n if (array[i]) {\r\n for (var j = i * i; j < n; j += i) {\r\n array[j] = false;\r\n }\r\n }\r\n }\r\n\r\n // All array[i] set to true are primes\r\n for (var i = 2; i < n; i++) {\r\n if (array[i]) {\r\n output.push(i);\r\n }\r\n }\r\n\r\n return output;\r\n};\r\n"}], "negative_code": [{"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n let testCases = parseInt(readLine());\r\n\r\n while(testCases--) {\r\n\r\n const [a,b,c] = readLine().split(' ').map(Number);\r\n\r\n let xstart = '1';\r\n \r\n for(let i = 1 ; i < a; i++){\r\n xstart+= '0';\r\n }\r\n xstart = parseInt(xstart);\r\n let xend = '';\r\n for(let i = 0; i < a; i++){\r\n xend+= '9';\r\n }\r\n xend = parseInt(xend);\r\n\r\n let ystart = '1';\r\n for(let i = 1; i < b; i++){\r\n ystart += '0';\r\n }\r\n ystart = parseInt(ystart);\r\n\r\n let yend = '';\r\n for(let i = 0; i < b; i++){\r\n yend += '9';\r\n }\r\n yend = parseInt(yend);\r\n\r\n let cstart = '1';\r\n for(let i = 1; i < c; i++){\r\n cstart += '0';\r\n }\r\n cstart = parseInt(cstart);\r\n\r\n let cend = '';\r\n for(let i = 0; i < c; i++){\r\n cend += '9';\r\n }\r\n cend = parseInt(cend);\r\n \r\n let stop = false;\r\n for(let i = xstart; i <= xend; i++){\r\n if(Number(i.toString().split('').pop()) === 0) continue;\r\n for(let j = ystart; j <= yend; j++){\r\n if(Number(j.toString().split('').pop()) === 0) continue;\r\n var ans = gcd(i,j);\r\n if(ans.toString().length === c.toString().length && Number(ans.toString().split('').pop() !== 0)){\r\n console.log(i,j);\r\n stop = true;\r\n break;\r\n }\r\n }\r\n if(stop) break;\r\n }\r\n }\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if ((typeof x !== 'number') || (typeof y !== 'number')) \r\n return false;\r\n x = Math.abs(x);\r\n y = Math.abs(y);\r\n while(y) {\r\n var t = y;\r\n y = x % y;\r\n x = t;\r\n }\r\n return x;\r\n }\r\n "}, {"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n let testCases = parseInt(readLine());\r\n\r\n while(testCases--) {\r\n\r\n const [a,b,c] = readLine().split(' ').map(Number);\r\n\r\n let xstart = '1';\r\n \r\n for(let i = 1 ; i < a; i++){\r\n xstart+= '0';\r\n }\r\n xstart = parseInt(xstart);\r\n let xend = '';\r\n for(let i = 0; i < a; i++){\r\n xend+= '9';\r\n }\r\n xend = parseInt(xend);\r\n\r\n let ystart = '1';\r\n for(let i = 1; i < b; i++){\r\n ystart += '0';\r\n }\r\n ystart = parseInt(ystart);\r\n\r\n let yend = '';\r\n for(let i = 0; i < b; i++){\r\n yend += '9';\r\n }\r\n yend = parseInt(yend);\r\n\r\n let cstart = '1';\r\n for(let i = 1; i < c; i++){\r\n cstart += '0';\r\n }\r\n cstart = parseInt(cstart);\r\n\r\n let cend = '';\r\n for(let i = 0; i < c; i++){\r\n cend += '9';\r\n }\r\n cend = parseInt(cend);\r\n \r\n let stop = false;\r\n for(let i = xstart; i <= xend; i++){\r\n if(Number(i.toString().split('').pop()) === 0) continue;\r\n for(let j = ystart; j <= yend; j++){\r\n if(Number(j.toString().split('').pop()) === 0) continue;\r\n if(gcd(i,j).toString().length === c.toString().length){\r\n console.log(i,j);\r\n stop = true;\r\n break;\r\n }\r\n }\r\n if(stop) break;\r\n }\r\n }\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if ((typeof x !== 'number') || (typeof y !== 'number')) \r\n return false;\r\n x = Math.abs(x);\r\n y = Math.abs(y);\r\n while(y) {\r\n var t = y;\r\n y = x % y;\r\n x = t;\r\n }\r\n return x;\r\n }\r\n "}, {"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n let testCases = parseInt(readLine());\r\n\r\n while(testCases--) {\r\n\r\n const [a,b,c] = readLine().split(' ').map(Number);\r\n\r\n let xstart = '1';\r\n \r\n for(let i = 1 ; i < a; i++){\r\n xstart+= '0';\r\n }\r\n xstart = parseInt(xstart);\r\n let xend = '';\r\n for(let i = 0; i < a; i++){\r\n xend+= '9';\r\n }\r\n xend = parseInt(xend);\r\n\r\n let ystart = '1';\r\n for(let i = 1; i < b; i++){\r\n ystart += '0';\r\n }\r\n ystart = parseInt(ystart);\r\n\r\n let yend = '';\r\n for(let i = 0; i < b; i++){\r\n yend += '9';\r\n }\r\n yend = parseInt(yend);\r\n\r\n let cstart = '1';\r\n for(let i = 1; i < c; i++){\r\n cstart += '0';\r\n }\r\n cstart = parseInt(cstart);\r\n\r\n let cend = '';\r\n for(let i = 0; i < c; i++){\r\n cend += '9';\r\n }\r\n cend = parseInt(cend);\r\n \r\n let stop = false;\r\n for(let i = xstart; i <= xend; i++){\r\n if(Number(i.toString().split('').pop()) === 0) continue;\r\n for(let j = ystart; j <= yend; j++){\r\n if(Number(j.toString().split('').pop()) === 0) continue;\r\n if(gcd(i,j) === c.toString().length){\r\n console.log(i,j);\r\n stop = true;\r\n break;\r\n }\r\n\r\n }\r\n if(stop) break;\r\n }\r\n }\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if ((typeof x !== 'number') || (typeof y !== 'number')) \r\n return false;\r\n x = Math.abs(x);\r\n y = Math.abs(y);\r\n while(y) {\r\n var t = y;\r\n y = x % y;\r\n x = t;\r\n }\r\n return x;\r\n }\r\n "}, {"source_code": "'use-strict'\r\n\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding('utf8');\r\n\r\nlet data = '';\r\nlet currentLine = 0;\r\n\r\nprocess.stdin.on('data', chunk => {\r\ndata += chunk;\r\n});\r\n\r\nprocess.stdin.on('end', () =>{\r\n data = data.replace(/\\s*$/, '')\r\n .split('\\n')\r\n .map(str => str.replace(/\\s*$/, ''));\r\n\r\n let testCases = parseInt(readLine());\r\n\r\n while(testCases--) {\r\n\r\n const [a,b,c] = readLine().split(' ').map(Number);\r\n\r\n let xstart = '1';\r\n \r\n for(let i = 1 ; i < a; i++){\r\n xstart+= '0';\r\n }\r\n xstart = parseInt(xstart);\r\n let xend = '';\r\n for(let i = 0; i < a; i++){\r\n xend+= '9';\r\n }\r\n xend = parseInt(xend);\r\n\r\n let ystart = '1';\r\n for(let i = 1; i < b; i++){\r\n ystart += '0';\r\n }\r\n ystart = parseInt(ystart);\r\n\r\n let yend = '';\r\n for(let i = 0; i < b; i++){\r\n yend += '9';\r\n }\r\n yend = parseInt(yend);\r\n let stop = false;\r\n for(let i = xstart; i <= xend; i++){\r\n if(Number(i.toString().split('').pop()) === 0) continue;\r\n for(let j = ystart; j <= yend; j++){\r\n if(Number(j.toString().split('').pop()) === 0) continue;\r\n if(gcd(i,j) === c){\r\n console.log(i,j);\r\n stop = true;\r\n break;\r\n }\r\n }\r\n if(stop) break;\r\n }\r\n }\r\n});\r\n\r\nfunction get_ints() { \r\n return data.shift().split(' ').map(Number);\r\n}\r\n \r\nfunction readLine() { \r\n return data[currentLine++];\r\n}\r\n\r\nfunction gcd(x, y) {\r\n if ((typeof x !== 'number') || (typeof y !== 'number')) \r\n return false;\r\n x = Math.abs(x);\r\n y = Math.abs(y);\r\n while(y) {\r\n var t = y;\r\n y = x % y;\r\n x = t;\r\n }\r\n return x;\r\n }\r\n "}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\n\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar a = nextInt();\r\n\t\tvar b = nextInt();\r\n\t\tvar c = nextInt();\r\n\t\tvar g = Math.pow(10, c - 1);\r\n\t\tvar x = g;\r\n\t\tvar y = g;\r\n\t\twhile(x < Math.pow(10, a - 1)){\r\n\t\t\tx *= 2;\r\n\t\t}\r\n\t\twhile(y < Math.pow(10, b - 1)){\r\n\t\t\ty *= 2;\r\n\t\t}\r\n\t\tmyout(x + \" \" + y);\r\n\t}\r\n}\r\n"}, {"source_code": "//Don't have to see. start------------------------------------------\r\nvar read = require('readline').createInterface({\r\n\tinput: process.stdin, output: process.stdout\r\n});\r\nvar obj; var inLine = []; var outputList = [];var retcode = new Set();\r\nread.on('line', function(input){\r\n\tvar tmp = input.split(' ');\r\n\tfor(var i = 0; i < tmp.length; i++){\r\n\t\tinLine.push(tmp[i]);\r\n\t\tif(i == tmp.length - 1){\r\n\t\t\tretcode.add(inLine.length);\r\n\t\t}\r\n\t}\r\n});\r\nread.on('close', function(){\r\n\tobj = init(inLine);\r\n\tconsole.error('\\n↑入力 ↓出力');\r\n\tMain();\r\n\tconsole.log(myconv(outputList, 9));\r\n});\r\nfunction makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}\r\nfunction nextArray(size, code){\r\n\tvar ret = new Array(size);\r\n\tfor(var i = 0; i < size; i++){\r\n\t\tif(code == 'int'){\r\n\t\t\tret[i] = nextInt();\r\n\t\t}else{\r\n\t\t\tret[i] = next();\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\nfunction nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}\r\nfunction nextCharArray(){return myconv(next(),6);}\r\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}\r\nfunction getCountMap(list){\r\n\tvar map = {};\r\n\tfor(var i = 0; i < list.length; i++){\r\n\t\tif(map[list[i]] == null){\r\n\t\t\tmap[list[i]] = 0;\r\n\t\t}\r\n\t\tmap[list[i]]++;\r\n\t}\r\n\treturn map;\r\n}\r\nfunction init(input){ \r\n\treturn {\r\n\t\tlist : input, index : 0, max : input.length,\r\n\t\thasNext : function(){return (this.index < this.max);},\r\n\t\tnext : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},\r\n\t\tisReturn : function(){return retcode.has(this.index);}\r\n\t};\r\n}\r\nfunction myout(s){outputList.push(s);}\r\nfunction myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}\r\nfunction isReturn(){return obj.isReturn();}\r\n//param \"no\" is\r\n//unknown or outlier : return i. 1: parseInt.\r\n//2: split space. 4: split space and parseInt.\r\n//6: split 1 character. 7: split 1 character and parseInt.\r\n//8: join space. 9: join nextline. 0: join no character.\r\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}\r\n\r\n//Don't have to see. end------------------------------------------\r\n\r\nfunction Main(){\r\n\tvar t = nextInt();\r\n\tfor(var i = 0; i < t; i++){\r\n\t\tvar a = nextInt();\r\n\t\tvar b = nextInt();\r\n\t\tvar c = nextInt();\r\n\t\tvar g = Math.pow(10, c - 1);\r\n\t\tvar x = 1;\r\n\t\tvar y = 1;\r\n\t\twhile(x < Math.pow(10, a - 1)){\r\n\t\t\tx *= 2;\r\n\t\t}\r\n\t\twhile(y < Math.pow(10, b - 1)){\r\n\t\t\ty *= 2;\r\n\t\t}\r\n\t\tmyout(x + \" \" + y);\r\n\t}\r\n}\r\n"}], "src_uid": "04330cb392bcfd51d1acffd72c8004cb"} {"nl": {"description": "Slava plays his favorite game \"Peace Lightning\". Now he is flying a bomber on a very specific map.Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n - 1, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.Help Slava to destroy all tanks using as few bombs as possible.", "input_spec": "The first line contains a single integer n (2 ≤ n ≤ 100 000) — the size of the map.", "output_spec": "In the first line print m — the minimum number of bombs Slava needs to destroy all tanks. In the second line print m integers k1, k2, ..., km. The number ki means that the i-th bomb should be dropped at the cell ki. If there are multiple answers, you can print any of them.", "sample_inputs": ["2", "3"], "sample_outputs": ["3\n2 1 2", "4\n2 1 3 2"], "notes": null}, "positive_code": [{"source_code": "n=+readline()\nif (2==9)\n{\n print(3)\n print(\"1 2 1\")\n}\nelse\n{\n x=[]\n for (i=2;i<=n;i+=2)\n {\n x.push(i)\n }\n for (i=1;i<=n;i+=2)\n {\n x.push(i)\n }\n for (i=2;i<=n;i+=2)\n {\n x.push(i)\n }\n print(x.length)\n print(x.join(' '))\n}"}], "negative_code": [{"source_code": "n=+readline()\nif (2==n)\n{\n print(3)\n print(\"1 2 1\")\n}\nelse\n{\n print(n*2-2)\n x=[]\n for (i=2;i<=n-1;i++)\n {\n x.push(i)\n }\n for (i=1;i<=n;i++)\n {\n x.push(i)\n }\n print(x.join(' '))\n}"}, {"source_code": "n=+readline()\nif (2==n)\n{\n print(3)\n print(\"1 2 1\")\n}\nelse\n{\n x=[]\n for (i=2;i<=n;i++)\n {\n x.push(i)\n x.push(i-1)\n }\n print(x*2-2)\n print(x.join(' '))\n}"}, {"source_code": "n=+readline()\nif (2==n)\n{\n print(3)\n print(\"1 2 1\")\n}\nelse\n{\n x=[]\n for (i=2;i<=n;i++)\n {\n x.push(i)\n x.push(i-1)\n }\n print(n*2-2)\n print(x.join(' '))\n}"}], "src_uid": "c40cb0a89c2b604aa7384476b57e96b3"} {"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$$$) — 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$$$) — 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": "(function() {\n var read = {\n number: function() {\n return +readline();\n },\n arr: function(divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function(divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n \n var n = read.arrNumber(' ');\n var b = n[0];\n var k = n[1];\n\n var a = read.arrNumber(' ');\n\n var res = a[k - 1];\n var last = b;\n \n for(var i = k - 2; i >= 0; i--) {\n var number = a[i] * last;\n var str = number.toString();\n var y = +(str[str.length - 1]);\n var lastString = (last * b).toString();\n last = +lastString[lastString.length - 1];\n res += number;\n }\n print(res % 2 ? 'odd' : 'even');\n}());\n"}, {"source_code": "(function() {\n var read = {\n number: function() {\n return +readline();\n },\n arr: function(divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function(divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n \n var n = read.arrNumber(' ');\n var b = n[0];\n var k = n[1];\n\n var a = read.arrNumber(' ');\n\n var res = a[k - 1];\n var last = b;\n \n for(var i = k - 2; i >= 0; i--) {\n var number = a[i] * last;\n var str = number.toString();\n var y = +(str[str.length - 1]);\n var lastString = (last * b).toString();\n last = +lastString[lastString.length - 1];\n res += number;\n }\n print(res % 2 ? 'odd' : 'even');\n}());"}, {"source_code": "const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false\n});\nlet c = 0;\nlet b, k;\n\nrl.on('line', (d) => {\n if (c === 0) {\n c++;\n [b, k] = d.split(' ').map(Number);\n return;\n }\n\n const arr = d.split(' ').map(Number);\n let odd = arr[arr.length - 1] % 2;\n\n for (let i = 0; i < arr.length - 1; i++) {\n if ((arr[i] * b) % 2) {\n odd++;\n }\n }\n\n if (odd % 2) {\n console.log('odd');\n }\n else {\n console.log('even');\n }\n\n c++;\n});\n"}], "negative_code": [{"source_code": "(function() {\n var read = {\n number: function() {\n return +readline();\n },\n arr: function(divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function(divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n \n var n = read.arrNumber(' ');\n var b = n[0];\n var k = n[1];\n\n var a = read.arrNumber(' ');\n\n var res = 0;\n\n var hh = 0;\n var last = b;\n a.forEach(function(i){\n var str = (i * b).toString();\n var y = +(str[str.length - 1])\n res += y;\n last = y;\n hh++;\n });\n\n print(res % 2 ? 'odd' : 'even');\n}());"}], "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$$$)  — 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$$$)  — 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$$$)  — 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$$$)  — 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": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b) {\r\n const map = new Map();\r\n for (let i = 0; i < n; i++) {\r\n if (!map.has(a[i])) map.set(a[i], []);\r\n map.get(a[i]).push(i);\r\n }\r\n const flag = new Array(n).fill(0);\r\n new Array(n).fill(-1);\r\n const hasIndex = (i, j) => {\r\n let arr = map.get(i);\r\n while (arr.length && arr[arr.length - 1] > j) {\r\n arr.pop();\r\n }\r\n return !!arr.length;\r\n };\r\n for (let i = n - 1, j = n - 1; i >= 0; i--) {\r\n if (b[i] !== b[i + 1]) {\r\n if (!hasIndex(b[i], j)) {\r\n console.log('NO');\r\n return;\r\n }\r\n while (flag[j] && b[i] !== a[j]) {\r\n j--;\r\n }\r\n if (b[i] !== a[j]) {\r\n console.log('NO');\r\n return;\r\n }\r\n if (flag[j]) {\r\n const k = map.get(b[i]).pop();\r\n flag[k] = 1;\r\n }\r\n j--;\r\n } else {\r\n if (!hasIndex(b[i], j)) {\r\n console.log('NO');\r\n return;\r\n }\r\n const k = map.get(b[i]).pop();\r\n flag[k] = 1;\r\n }\r\n }\r\n console.log('YES');\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n solve(n, a, b);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "negative_code": [{"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b) {\r\n const map = new Map();\r\n for (let i = 0; i < n; i++) {\r\n if (!map.has(a[i])) map.set(a[i], []);\r\n map.get(a[i]).push(i);\r\n }\r\n const flag = new Array(n).fill(0);\r\n new Array(n).fill(-1);\r\n const hasIndex = (i, j) => {\r\n let arr = map.get(i);\r\n while (arr.length && arr[arr.length - 1] > j) {\r\n arr.pop();\r\n }\r\n return !!arr.length;\r\n };\r\n for (let i = n - 1, j = n - 1; i >= 0; i--) {\r\n if (flag[j]) {\r\n if (!hasIndex(b[i], j - 1)) {\r\n console.log('NO');\r\n return;\r\n }\r\n while (flag[j] && b[i] !== a[j]) {\r\n j--;\r\n }\r\n if (a[j] !== b[i]) {\r\n console.log('NO');\r\n return;\r\n }\r\n if (flag[j]) {\r\n const k = map.get(b[i]).pop();\r\n flag[k] = 1;\r\n }\r\n j--;\r\n } else {\r\n if (a[j] !== b[i]) {\r\n if (!hasIndex(b[i], j - 1) || b[i] !== b[i + 1]) {\r\n console.log('NO');\r\n return;\r\n }\r\n const k = map.get(b[i]).pop();\r\n flag[k] = 1;\r\n } else {\r\n j--;\r\n }\r\n }\r\n }\r\n console.log('YES');\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n solve(n, a, b);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}, {"source_code": "'use strict';\r\n\r\nvar readline = require('readline');\r\n\r\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\r\n\r\nvar readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);\r\n\r\nfunction solve(n, a, b) {\r\n const map = new Map();\r\n for (let i = 0; i < n; i++) {\r\n if (!map.has(a[i])) map.set(a[i], []);\r\n map.get(a[i]).push(i);\r\n }\r\n const flag = new Array(n).fill(0);\r\n new Array(n).fill(-1);\r\n const hasIndex = (i, j) => {\r\n let arr = map.get(i);\r\n while (arr.length && arr[arr.length - 1] > j) {\r\n arr.pop();\r\n }\r\n return !!arr.length;\r\n };\r\n for (let i = n - 1, j = n - 1; i >= 0; i--) {\r\n if (flag[j]) {\r\n if (!hasIndex(b[i], j - 1)) {\r\n console.log('NO');\r\n return;\r\n }\r\n while (flag[j] && b[i] !== a[j]) {\r\n j--;\r\n }\r\n if (a[j] !== b[i]) {\r\n console.log('NO');\r\n return;\r\n }\r\n if (flag[j]) {\r\n const k = map.get(b[i]).pop();\r\n flag[k] = 1;\r\n }\r\n j--;\r\n } else {\r\n if (a[j] !== b[i]) {\r\n if (!hasIndex(b[i], j - 1) || b[i] !== a[j + 1]) {\r\n console.log('NO');\r\n return;\r\n }\r\n const k = map.get(b[i]).pop();\r\n flag[k] = 1;\r\n } else {\r\n j--;\r\n }\r\n }\r\n }\r\n console.log('YES');\r\n}\r\n\r\nasync function main(read) {\r\n let t = Number(await read());\r\n while (t--) {\r\n const n = Number(await read());\r\n const a = (await read()).split(' ').map(Number);\r\n const b = (await read()).split(' ').map(Number);\r\n solve(n, a, b);\r\n }\r\n}\r\n\r\nconst rl = readline__default[\"default\"].createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\nvoid async function () {\r\n const inputs = [];\r\n let i = 0;\r\n for await (const line of rl) {\r\n inputs.push(line.trim());\r\n }\r\n function read() {\r\n return inputs[i++];\r\n }\r\n await main(read);\r\n}();\r\n"}], "src_uid": "158bd0ab8f4319f5fd1e6062caddad4e"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \\cdot a_j = i + j$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 2 \\cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. 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 number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \\cdot a_j = i + j$$$.", "sample_inputs": ["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"], "sample_outputs": ["1\n1\n3"], "notes": "NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \\cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$."}, "positive_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let bool = [];\r\n let k = Math.ceil(Math.sqrt(n + n - 1));\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] <= k) bool[i] = true;\r\n else bool[i] = false;\r\n }\r\n let cnt = 0,\r\n obj = {};\r\n for (let i = 0; i < n; i++) {\r\n if (bool[i]) {\r\n for (let j = 0; j < n; j++) {\r\n if (i === j) continue;\r\n let k = i + 1 + (j + 1);\r\n if (k === arr[i] * arr[j]) {\r\n let s1 = `${i + 1} ${j + 1}`;\r\n let s2 = `${j + 1} ${i + 1}`;\r\n if (!obj[s1] && !obj[s2]) cnt++;\r\n obj[s1] = 1;\r\n obj[s2] = 1;\r\n }\r\n }\r\n }\r\n }\r\n console.log(cnt);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\"; \r\n\r\n// import for reading input //\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"utf-8\");\r\n\r\nlet inputString = \"\";\r\nlet currentLine = 0;\r\n \r\nprocess.stdin.on(\"data\", (inputStdin) => {\r\n inputString += inputStdin;\r\n});\r\nprocess.stdin.on(\"end\", () => {\r\n inputString = inputString.split(\"\\n\");\r\n main();\r\n});\r\nfunction readline() {\r\n return inputString[currentLine++];\r\n} \r\n// //\r\nfunction main() {\r\n var t = +(readline());\r\n while (t--) {\r\n solution();\r\n } \r\n}\r\n\r\nfunction solution() {\r\n const n = +(readline());\r\n const arr = readline().split(' ').map((item) => +item);\r\n \r\n let counter = 0;\r\n for (let i = 0; i < n-1; i++) {\r\n let r = (i+1)%arr[i];\r\n let firstJ = (arr[i] - r > r) ? (i+1-2*r+arr[i]) : (i+1+2*(arr[i]-r));\r\n for (let j = firstJ-1; j < n; j += arr[i]) {\r\n if (arr[i]*arr[j] === i+j+2) counter++;\r\n }\r\n }\r\n console.log(counter);\r\n}\r\n\r\n"}, {"source_code": "const stdin = process.openStdin();\r\nlet content = '';\r\n\r\nstdin.addListener('data', (data) => {\r\n content += data;\r\n})\r\n\r\nstdin.addListener('end', () => {\r\n content = content.split('\\n');\r\n content.shift();\r\n content = content.map((string) => string.substring(0, string.length - 1));\r\n content.pop();\r\n content.forEach((str, i) => {\r\n if (i % 2 === 1) {\r\n str = str.split(' ').map(str => parseInt(str));\r\n console.log(pleasantPairs(str));\r\n }\r\n });\r\n})\r\n\r\nconst pleasantPairs = (arr) => {\r\n let pairCount = 0;\r\n for (let i = 0; i < arr.length - 1; i++) {\r\n let multiple = 1;\r\n let j = (arr[i] * multiple) - (i + 1) - 1;\r\n while (j < arr.length) {\r\n if ((arr[j] * arr[i]) === (i + j + 2) && i < j) {\r\n pairCount++;\r\n }\r\n multiple++;\r\n j = (arr[i] * multiple) - (i + 1) - 1;\r\n }\r\n }\r\n return pairCount;\r\n}"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = +lines[0]\n var l = 1;\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n var arr = lines[l++].split(' ').map(Number)\n console.log(solve(n, arr));\n }\n});\n\nfunction solve(n, arr) {\n let count = 0\n arr.forEach((a, i) => {\n i++\n const limit = Math.floor(2 * n / a)\n for (let j = 1; j <= limit; j++) {\n const p = a * j - i - 1\n if (p > i - 1 && arr[p] === j) count++\n }\n })\n return count\n}\n"}, {"source_code": "var dataitr;\r\nvar stdin_input = \"\";\r\nprocess.stdin.resume();\r\nprocess.stdin.setEncoding(\"ascii\");\r\nprocess.stdin.on(\"data\", function (input) { stdin_input += input; });\r\nprocess.stdin.on(\"end\", function () { dataitr = stdin_input.split('\\n').values(); main(); });\r\n\r\nconst rl = () => dataitr.next().value.trim();\r\nconst rn = () => Number(rl());\r\nconst ra = () => rl().split(' ');\r\nconst rna = () => ra().map(x => Number(x));\r\n\r\nfunction main () {\r\n\tlet T = rn();\r\n\twhile (T--) {\r\n\t\tconst n = rn();\r\n\t\tconst a = rna();\r\n\t\ta.unshift(0);\r\n\r\n\t\tlet ans = 0;\r\n\t\tfor (let i = 1; i <= n; i++) {\r\n\t\t\tconst start = Math.ceil((2*i+1)/a[i])*a[i] - i;\r\n\t\t\tfor(j = start; j <= n; j += a[i]) {\r\n\t\t\t\tans += a[i] * a[j] == i + j;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconsole.log(ans);\r\n\t}\r\n}\r\n\r\n"}, {"source_code": "const lib = require('readline');\r\nconst rl = lib.createInterface({\r\n input: process.stdin,\r\n output: process.stdout\r\n});\r\n\r\nconst getLine = (function () {\r\n const getLineGen = (async function* () {\r\n for await (const line of rl) {\r\n yield line;\r\n }\r\n })();\r\n return async () => {\r\n let next;\r\n do {\r\n next = (await getLineGen.next());\r\n } while (!next.done && next.value === '');\r\n return next.value;\r\n };\r\n})();\r\n\r\nlet solve = async () => {\r\n let nsc = parseInt(await getLine());\r\n for(let sc = 0; sc < nsc; sc++) {\r\n const n = parseInt(await getLine());\r\n const a = (await getLine()).split(' ').map(num => parseInt(num));\r\n let count = 0;\r\n for(let i = 0; i < n; i++) {\r\n let rem = (i + 1) % a[i];\r\n let need = (a[i] - rem) % a[i];\r\n let delta = (a[i] + need - rem) % a[i];\r\n for(let j = 0; i + 1 + delta + a[i] * j <= n; j++) {\r\n let ind2 = i + 1 + delta + a[i] * j;\r\n if (ind2 == i + 1)\r\n continue;\r\n if (a[i] * a[ind2-1] === i + 1 + ind2)\r\n count++;\r\n }\r\n }\r\n console.log(count);\r\n }\r\n}\r\n\r\nsolve();\r\n"}, {"source_code": "var t = +readline();\r\nfor (var tt = 0; tt < t; tt += 1) {\r\n var n = +readline();\r\n var arr = readline()\r\n .split(\" \")\r\n .map((num) => {\r\n return +num;\r\n });\r\n arr.unshift(0);\r\n var find = [];\r\n for (var k = 1; k <= n; k += 1) {\r\n var numToFind = 1;\r\n while (true) {\r\n var indexToFind = Math.abs(arr[k] * numToFind - k);\r\n if (indexToFind <= n) {\r\n if (indexToFind > k) find.push([numToFind, indexToFind]);\r\n } else {\r\n break;\r\n }\r\n numToFind += 1;\r\n }\r\n }\r\n var ans = 0;\r\n find.forEach((value) => {\r\n if (arr[value[1]] === value[0]) ans += 1;\r\n });\r\n print(ans);\r\n}\r\n"}], "negative_code": [{"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let bool = [];\r\n let k = Math.ceil(Math.sqrt(n + n - 1));\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] <= k) bool[i] = true;\r\n else bool[i] = false;\r\n }\r\n let cnt = 0,\r\n obj = {};\r\n for (let i = 0; i < n; i++) {\r\n if (bool[i]) {\r\n for (let j = 0; j < n; j++) {\r\n let k = i + 1 + (j + 1);\r\n if (k === arr[i] * arr[j]) {\r\n let s1 = `${i + 1} ${j + 1}`;\r\n let s2 = `${j + 1} ${i + 1}`;\r\n if (!obj[s1] && !obj[s2]) cnt++;\r\n obj[s1] = 1;\r\n obj[s2] = 1;\r\n }\r\n }\r\n }\r\n }\r\n console.log(cnt);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let bool = [];\r\n let k = Math.ceil(Math.sqrt(n));\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] <= k) bool[i] = true;\r\n else bool[i] = false;\r\n }\r\n let cnt = 0,\r\n obj = {};\r\n for (let i = 0; i < n; i++) {\r\n if (bool[i]) {\r\n for (let j = 0; j < n; j++) {\r\n let k = i + 1 + (j + 1);\r\n if (k === arr[i] * arr[j]) {\r\n let s1 = `${i + 1} ${j + 1}`;\r\n let s2 = `${j + 1} ${i + 1}`;\r\n if (!obj[s1] && !obj[s2]) cnt++;\r\n obj[s1] = 1;\r\n obj[s2] = 1;\r\n }\r\n }\r\n }\r\n }\r\n console.log(cnt);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let bool = [];\r\n let k = Math.ceil(Math.sqrt(n));\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] <= k) bool[i] = true;\r\n else bool[i] = false;\r\n }\r\n let cnt = 0,\r\n obj = {};\r\n for (let i = 0; i < n; i++) {\r\n if (bool[i]) {\r\n for (let j = 0; j < n; j++) {\r\n let k = i + 1 + (j + 1);\r\n if (k === arr[i] * arr[j]) {\r\n if (!obj[i + j + 2]) cnt++;\r\n obj[i + j + 2] = 1;\r\n }\r\n }\r\n }\r\n }\r\n console.log(cnt);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "\"use strict\";\r\nconst fs = require(\"fs\");\r\n//let filename = \"0.txt\";\r\nlet filename = 0;\r\nconst input = fs.readFileSync(filename, \"utf8\").trim().split(\"\\n\");\r\nlet line = 0;\r\nfunction readline() {\r\n return input[line++];\r\n}\r\nconst solve = () => {\r\n let t = parseInt(readline());\r\n while (t--) {\r\n let n = parseInt(readline());\r\n let arr = readline()\r\n .trim()\r\n .split(\" \")\r\n .map((cur) => parseInt(cur));\r\n let bool = [];\r\n let k = Math.floor(Math.sqrt(n));\r\n for (let i = 0; i < n; i++) {\r\n if (arr[i] <= k) bool[i] = true;\r\n else bool[i] = false;\r\n }\r\n let cnt = 0;\r\n for (let i = 0; i < n; i++) {\r\n if (bool[i]) {\r\n for (let j = 0; j < n; j++) {\r\n let k = i + 1 + (j + 1);\r\n if (k === arr[i] * arr[j]) cnt++;\r\n }\r\n }\r\n }\r\n console.log(cnt);\r\n }\r\n};\r\nsolve();\r\n"}, {"source_code": "var readline = require('readline');\n \nvar rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nvar lines = [];\nrl.on('line', function(input) {\n lines.push(input);\n});\nrl.on('close', function() {\n var t = +lines[0]\n var l = 1;\n for (var i = 0; i < t; i++) {\n var n = +lines[l++]\n var arr = lines[l++].split(' ').map(Number)\n console.log(solve(n, arr));\n }\n});\n\nfunction solve(n, arr) {\n let count = 0\n arr.forEach((a, i) => {\n i++\n const limit = Math.floor(2 * n / a)\n for (let j = 1; j <= limit; j++) {\n if (arr[a * j - i - 1] === j) count++\n }\n })\n return count / 2\n}\n"}], "src_uid": "0ce05499cd28f0825580ff48dae9e7a9"} {"nl": {"description": "You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array $$$a$$$ of length $$$n$$$ is called complete if all elements are positive and don't exceed $$$1000$$$, and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \\leq x,y,z \\leq n$$$), $$$a_{x}+a_{y} \\neq a_{z}$$$ (not necessarily distinct).You are given one integer $$$n$$$. Please find any complete array of length $$$n$$$. It is guaranteed that under given constraints such array exists.", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\le t \\le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.", "output_spec": "For each test case, print a complete array on a single line. All elements have to be integers between $$$1$$$ and $$$1000$$$ and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \\leq x,y,z \\leq n$$$) (not necessarily distinct), $$$a_{x}+a_{y} \\neq a_{z}$$$ must hold. If multiple solutions exist, you may print any.", "sample_inputs": ["2\n5\n4"], "sample_outputs": ["1 5 3 77 12\n384 384 44 44"], "notes": "NoteIt can be shown that the outputs above are valid for each test case. For example, $$$44+44 \\neq 384$$$.Below are some examples of arrays that are NOT complete for the 1st test case:$$$[1,2,3,4,5]$$$ Notice that $$$a_{1}+a_{2} = a_{3}$$$.$$$[1,3000,1,300,1]$$$ Notice that $$$a_{2} = 3000 > 1000$$$."}, "positive_code": [{"source_code": "var n = readline();\nvar b=n;\nvar res = [];\nwhile (n--){\n res.push(Array(parseInt(readline())).fill(1))\n}\nfor(var i =0;i {\n MEMORY = data.split('\\r\\n');\n init();\n });\n } else {\n var RL = require('readline').createInterface({\n input : process.stdin,\n output : process.stdout\n });\n \n RL.on('line', (line) => {\n MEMORY.push(line);\n });\n \n RL.on('close', init);\n }\n} else {\n init();\n}\n \nfunction write(value) {\n isNode ? console.log(value) : print(value);\n}\nfunction read() {\n return isNode ? MEMORY[MEMORY_INDEX++] : readline();\n}\n"}, {"source_code": "let inputString = \"\";\nlet currentLine = 0;\nprocess.stdin.on(\"data\", (data) => {\n inputString += data;\n});\nprocess.stdin.on(\"end\", function () {\n inputString = inputString\n .trim()\n .split(\"\\n\")\n .map((str) => str.trim());\n main();\n});\nfunction readLine() {\n return inputString[currentLine++];\n}\nfunction main() {\n let t = +readLine();\n while (t--) {\n const len = +readLine();\n const result = Array(len).fill(1).join(\" \");\n console.log(result);\n }\n}\n"}, {"source_code": "//Don't have to see. start------------------------------------------\nvar read = require('readline').createInterface({\n input: process.stdin, output: process.stdout\n});\nvar obj; var inLine = [];\nread.on('line', function(input){inLine.push(input);});\nread.on('close', function(){\n obj = init(inLine);\n console.error(\"\\n\");\n var start = Date.now();\n Main();\n var end = Date.now() - start;\n myerr(\"time : \" + (end) + \"ms\");\n myerr(\"memory : \" + Math.round(process.memoryUsage().heapTotal / 1024) + \"KB\");\n});\nfunction makeClone(obj){return JSON.parse(JSON.stringify(obj));}\nfunction nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}\nfunction nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}\nfunction next(){return obj.next();} function hasNext(){return obj.hasNext();}\nfunction init(input){ \n return {\n list : input, index : 0, max : input.length,\n hasNext : function(){return (this.index < this.max);},\n next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw \"ArrayIndexOutOfBoundsException ‚There is no more input\";}}\n };\n}\nfunction myout(s){console.log(s);}\nfunction myerr(s){console.error(\"debug:\" + require(\"util\").inspect(s,false,null));}\n//param \"no\" is\n//unknown or outlier : return i. 1: parseInt.\n//2: split space. 4: split space and parseInt.\n//6: split 1 character. 7: split 1 character and parseInt.\n//8: join space. 9: join nextline. 0: join no character.\nfunction myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(\" \");case 4:return i.split(\" \").map(Number);case 6:return i.split(\"\");case 7:return i.split(\"\").map(Number);case 8:return i.join(\" \");case 9:return i.join(\"\\n\");case 0:return i.join(\"\");default:return i;}}catch(e){return i;}}\n\n//Don't have to see. end------------------------------------------\nfunction Main(){\n var t = nextInt();\n var output = new Array(t);\n for(var i = 0; i < t; i++){\n var N = nextInt();\n var list = new Array(N).fill(1);\n output[i] = myconv(list, 8);\n }\n myout(myconv(output, 9));\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet stdinInput = '';\n \nprocess.stdin.on('data', input => {\n stdinInput += input;\n});\n \nprocess.stdin.on('end', () => {\n main(stdinInput);\n});\n \nfunction main(data) {\n\tdata = data.split('\\n');\n\tconst testCases = data[0] * 1;\n\tlet i = 1;\n\twhile (i <= testCases) {\n\t let n = data[i] * 1;\n\t let arr = Array(n).fill(1);\n\t arr = arr.join(' ');\n\t console.log(arr);\n\t i += 1;\n\t}\n}"}, {"source_code": "'use strict';\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readint() {\n let line = readline().split(' ').map(function(num) {\n return parseInt(num);\n });\n return line;\n}\n\nfunction readfloat() {\n let line = readline().split(' ').map(function(num) {\n return parseFloat(num);\n });\n return line;\n}\n\nfunction print(x) {\n console.log(x);\n}\n\nfunction write(x) {\n process.stdout.write(x);\n}\nfunction main() {\n let t = parseInt(readline());\n //go go bro!!!\n while(t--) {\n let n = readint();\n while(n--) {\n write(1 + \" \");\n }\n write(\"\\n\");\n }\n \n}"}, {"source_code": "// node template.js < A-small.in > A-small.out\n\nfunction main() {\n var tests = 1;\n tests = nextInt();\n\n for (let t = 1; t <= tests; t++) {\n let N = nextInt();\n\n for(let i = 0; i < N; i++) {\n process.stdout.write(N + \" \");\n }\n print(\"\");\n }\n}\n\n// ------- Template ------------------\nfunction newTensor(dimensions, value) {\n let res = [];\n let dim = dimensions[0], subdim = dimensions.slice(1);\n if (subdim.length == 0) {\n for(let i = 0; i < dim; i++) {\n res.push(value);\n }\n } else {\n for(let i = 0; i < dim; i++) {\n res.push(newTensor(subdim, value));\n }\n }\n return res;\n}\n\nif (!String.prototype.startsWith) {\n Object.defineProperty(String.prototype, 'startsWith', {\n value: function(search, rawPos) {\n var pos = rawPos > 0 ? rawPos|0 : 0;\n return this.substring(pos, pos + search.length) === search;\n }\n });\n}\nif (!String.prototype.endsWith) {\n String.prototype.endsWith = function(search, this_len) {\n if (this_len === undefined || this_len > this.length) {\n this_len = this.length;\n }\n return this.substring(this_len - search.length, this_len) === search;\n };\n}\n\nvar curTokens = [], curToken = 0;\n\nfunction next() {\n while (curToken >= curTokens.length) {\n curTokens = readline().split(/[\\s]+/);\n curToken = 0;\n }\n return curTokens[curToken++];\n}\n\nfunction nextInt() {\n return parseInt(next());\n}\n\n// code for nodejs\nvar inputBuffer = '', curLine = 0;\n\nfunction readline() {\n return inputBuffer[curLine++];\n}\n\nfunction print(data) {\n process.stdout.write(data + '\\n');\n}\n\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n inputBuffer += chunk;\n});\n\nprocess.stdin.on('end', function () {\n inputBuffer = inputBuffer.split(/[\\s]+/);\n main();\n});"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let ans = '';\n for(let i = 0; i < n; i++){\n ans += '1 ';\n }\n console.log(ans);\n }\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n4\n3\n1 2 3\n4\n3 1 2 4\n3\n2 3 1\n6\n2 4 6 1 3 5\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r= n / 2 && a.length < n) {\n a.push(44);\n }\n\n console.log(a.join(\" \"));\n}\n\n"}], "negative_code": [{"source_code": "var n = readline();\nvar b=n;\nvar res = [];\nwhile (n--){\n res.push(Array(parseInt(readline())).fill(1))\n}\nfor(var i =0;i {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction readint() {\n let line = readline().split(' ').map(function(num) {\n return parseInt(num);\n });\n return line;\n}\n\nfunction readfloat() {\n let line = readline().split(' ').map(function(num) {\n return parseFloat(num);\n });\n return line;\n}\n\nfunction print(x) {\n console.log(x);\n}\n\nfunction write(x) {\n process.stdout.write(x);\n}\nfunction main() {\n let t = parseInt(readline());\n //go go bro!!!\n while(t--) {\n let n = readint();\n while(n--) {\n write(1 + \" \");\n }\n print('\\n');\n }\n \n}"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let res = [];\n res.push(1);\n res.push(3);\n let last = 1+2;\n for(let i = 2; i < n; i++){\n res.push(res[res.length-1]+res[res.length-2]+1);\n }\n\n let ans = '';\n for(let i of res)\n ans += `${i} `;\n console.log(ans);\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let res = [];\n res.push(1);\n res.push(2);\n let last = 1+2;\n for(let i = 2; i < n; i++){\n res.push(res[res.length-1]+res[res.length-2]+1);\n }\n\n for(let i of res)\n console.log(i);\n }\n}\n"}, {"source_code": "process.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n\nlet inputString = '';\nlet currentLine = 0;\n\nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n\nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n A();\n});\n\nfunction readline() {\n return inputString[currentLine++];\n}\n\nfunction pi(a) {\n return parseInt(a);\n}\n\nfunction ti(a){\n for(let i = 0; i < a.length; i++)\n a[i] = pi(a[i]);\n\n return a;\n}\n\nfunction A(){\n let t = pi(readline());\n while(t > 0){\n t--;\n let n = pi(readline());\n let res = [];\n res.push(1);\n res.push(2);\n let last = 1+2;\n for(let i = 2; i < n; i++){\n res.push(res[res.length-1]+res[res.length-2]+1);\n }\n\n let ans = '';\n for(let i of res)\n ans += `${i} `;\n console.log(ans);\n }\n}\n"}, {"source_code": "'use strict';\n \nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\n \nlet inputString = '';\nlet currentLine = 0;\n \nprocess.stdin.on('data', inputStdin => {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n4\n3\n1 2 3\n4\n3 1 2 4\n3\n2 3 1\n6\n2 4 6 1 3 5\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r {\n inputString += inputStdin;\n});\n \nprocess.stdin.on('end', _ => {\n inputString = inputString.trim().split('\\n').map(string => {\n return string.trim();\n });\n \n main(); \n});\n \nfunction readline() {\n return inputString[currentLine++];\n}\n/**\n4\n3\n1 2 3\n4\n3 1 2 4\n3\n2 3 1\n6\n2 4 6 1 3 5\n\n\n**/\n\nfunction gcd(a, b) {\n if (!b) {\n return a;\n }\n\n return gcd(b, a % b);\n};\n\nfunction main() { \n let n = Number(readline());\n\n for(let r=0;r cursor) {\n\t\tbreak;\n\t}\n\tif (right > cursor) {\n\t\tcursor = right;\n\t}\n}\n\nif (cursor >= m) {\n\tprint('YES');\n} else {\n\tprint('NO');\n}\n"}, {"source_code": "\nvar read = readline().split(\" \").map(Number);\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar found = false;\nvar lst = 0;\nfunction getPt( loop, limit ){\n\t\t while( loop ){\n\t\t\t loop--;\n\t\t\t\tvar arr = readline().split(\" \").map(Number);\n\t\t\t\tvar x = arr[0];var y = arr[1];\n\t\t\t\tif ( x > lst ){\n\t\t\t\t\t reject = true;\n\t\t\t\t\t break;\n\t\t\t\t}\n\t\t\t\tif ( y > lst ){\n\t\t\t\t\t lst = y;\n\t\t\t\t\t if( lst == limit ){\n\t\t\t\t\t\t\t found = true;\n\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t}\n\t\t\t }\n\n\t\t }\n\t\t \n\t\t if(reject)\n\t\t\t\twrite(\"NO\\n\");\n\t\t if(found)\n\t\t\t\twrite(\"YES\\n\");\n\t\t if(!reject && !found)\n\t\t\t\twrite( lst == limit ? \"YES\" : \"NO\");\n}\n\ngetPt( loop, limit);\n"}, {"source_code": "// FUCK IT I FORGOT, VALUES IN ARRAY SHOULD\n// BE PARSEINT SO THAT I USED .map(Number);\nvar read = readline().split(\" \").map(Number);\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar found = false;\nvar lst = 0;\ngetPt( loop, limit);\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = readline().split(\" \").map(Number);\n\t\t\t\t\t\t\t\tvar x = arr[0];var y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst ){\n\t\t\t\t\t\t\t\t\t\t\t reject = true;\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif ( y > lst ){\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\t\t\t\t\t\t\t\t\t\t\t if( lst == limit ){\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t found = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t }\n\t\t\t\t if(reject)\n\t\t\t\t \t\t\t write(\"NO\\n\");\n\t\t\t\t if(found)\n\t\t\t\t \t\t\t write(\"YES\\n\");\n\t\t\t\t if(!reject && !found){\n\t\t\t\t\t \t\t write( lst == limit ? \"YES\" : \"NO\");\n\t\t\t\t }\n}\n"}, {"source_code": "var x=readline().split(' ')\nn=Number(x[0])\nm=Number(x[1])\nA=[]\nB=[]\nfor (var i=0;ileft ){\n\t\tleft = b[i];\n\t}\n}\n\nif(M <= left){\n\tprint(\"YES\");\n}else{\n\tprint(\"NO\");\n}\n\n"}, {"source_code": "one=readline();\nn=parseInt(one.split(' ')[0]);\nm=parseInt(one.split(' ')[1]);\nmas=[];\nfunction compareNumeric(x, y) {\n if (x.a > y.a) return 1;\n if (x.a < y.a) return -1;\n if (x.a === y.a) {\n if (x.b > y.b) return 1;\n if (x.b < y.b) return -1;\n }\n}\nfor(i=0;i max) {\n max = mas[i].b;\n if (max >= m) {\n f = true;\n break;\n }\n }\n } else {\n break;\n }\n}\nif (f) {print('YES');} else {print('NO');}"}], "negative_code": [{"source_code": "// write by lpy in 2017/12/21\n//title is Visting a Friend\n/*\n\tthe input of this argument\n*/\nvar arr = readline().split(\" \");\nvar n = arr[0];\nvar m = arr[1];\n\n//var array = [[0,4],[2,6],[6,7]];\n\nfunction f(n,m){// n is the number of input, m is the friend's house\n\t\n\t//the [left,right]is existing range\n\tvar str = readline().split(\" \");\n\tvar left = str[0], right = str[1];\n\tvar result = 'YES'; \n\tfor(var i = 1; i < n; i++){\n\t\tvar array = readline().split(\" \");\n\t\tvar a1 = left, b1 = right;\n\t\t// var a2 = array[i][0], b2 = array[i][1];\n\t\tvar a2 = array[0],b2 = array[1];\n\t\tif(a1 <= a2){\n\t\t\tleft = a1;\n\t\t\tif(a2 <= b1){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tresult = 'NO';\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleft = a2;\n\t\t\tif(a1 <= b2){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse result = 'NO';\n\t\t}\n\t}\n\treturn result;\n}\nprint(f(n, m));\n// console.log(f(3,5));\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "// write by lpy in 2017/12/21\n//title is Visting a Friend\n/*\n\tthe input of this argument\n*/\nvar arr = readline().split(\" \");\nvar n = arr[0];\nvar m = arr[1];\n\n// var array = [[1,1],[0,0]];\n\nfunction f(n,m){// n is the number of input, m is the friend's house\n\t\n\t//the [left,right]is existing range\n\tvar str = readline().split(\" \");\n\tvar left = str[0], right = str[1];\n\t// var left = array[0][0],right = array[0][1];\n\t// console.log(left, right);\n\tvar result = true; \n\tfor(var i = 1; i < n; i++){\n\t\tvar array = readline().split(\" \");\n\t\tvar a1 = left, b1 = right;\n\t\t// console.log(a1, b1);\n\t\t// var a2 = array[i][0], b2 = array[i][1];\n\t\t// console.log(a2, b2);\n\t\tvar a2 = array[0],b2 = array[1];\n\t\tif(a1 <= a2){\n\t\t\tleft = a1;\n\t\t\tif(a2 <= b1){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tresult = false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleft = a2;\n\t\t\tif(a1 <= b2){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse result = false;\n\t\t}\n\t}\n\tvar ans;\n\tif(result){\n\t\tif(left === 0 && right === m)\n\t\t\tans = 'YES';\n\t\telse ans = 'NO';\n\t}\n\telse ans = 'NO';\n\treturn ans;\n}\nprint(f(n, m));\n// console.log(f(2,1));\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "// write by lpy in 2017/12/21\n//title is Visting a Friend\n/*\n\tthe input of this argument\n*/\nvar arr = readline().split(\" \");\nvar n = arr[0];\nvar m = arr[1];\n\n// var array = [[1,1],[0,0]];\n\nfunction f(n,m){// n is the number of input, m is the friend's house\n\t\n\t//the [left,right]is existing range\n\tvar str = readline().split(\" \");\n\tvar left = str[0], right = str[1];\n\t// var left = array[0][0],right = array[0][1];\n\t// console.log(left, right);\n\tvar result = true; \n\tfor(var i = 1; i < n; i++){\n\t\tvar array = readline().split(\" \");\n\t\tvar a1 = left, b1 = right;\n\t\t// console.log(a1, b1);\n\t\t// var a2 = array[i][0], b2 = array[i][1];\n\t\t// console.log(a2, b2);\n\t\tvar a2 = array[0],b2 = array[1];\n\t\tif(a1 <= a2){\n\t\t\tleft = a1;\n\t\t\tif(a2 <= b1){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tresult = false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleft = a2;\n\t\t\tif(a1 <= b2){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse result = false;\n\t\t}\n\t}\n\tvar ans;\n\tif(result===true){\n\t\tif(left === 0 && right === m)\n\t\t\tans = 'YES';\n\t\telse ans = 'NO';\n\t}\n\telse ans = 'NO';\n\treturn ans;\n}\nprint(f(n, m));\n// console.log(f(2,1));\n"}, {"source_code": "// write by lpy in 2017/12/21\n//title is Visting a Friend\n/*\n\tthe input of this argument\n*/\nvar arr = readline().split(\" \");\nvar n = arr[0];\nvar m = arr[1];\n\n//var array = [[0,4],[2,6],[6,7]];\n\nfunction f(n,m){// n is the number of input, m is the friend's house\n\tvar left = 0, right = 0;\n\t//the [left,right]is existing range\n\tvar result = 'YES'; \n\tfor(var i = 0; i < n; i++){\n\t\tvar array = readline().split(\" \");\n\t\tvar a1 = left, b1 = right;\n\t\t// var a2 = array[i][0], b2 = array[i][1];\n\t\tvar a2 = array[0],b2 = array[1];\n\t\tif(a1 <= a2){\n\t\t\tleft = a1;\n\t\t\tif(a2 <= b1){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tresult = 'NO';\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleft = a2;\n\t\t\tif(a1 <= b2){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse result = 'NO';\n\t\t}\n\t}\n\treturn result;\n}\nprint(f(n, m));\n// console.log(f(3,5));\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar lst = 0;\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \tloop--;\n\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\tx = arr[0],y = arr[1];\n\t\t\t\t\t\tif ( x > lst ){\n\t \t\t\t\t\t reject = true;\n\t\t\t\t\t\t \t break;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ( y > lst )\n\t\t\t\t\t\t\t lst = y;\n\t\t\t\t }\n\t\t\t\t if(reject)\n\t\t\t\t \t write(\"NO\\n\");\n\n\t\t\t\t return lst;\n}\n\nwrite(getPt(loop, limit));\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar lst = 0;\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\t\t\tvar x = arr[0];\n\t\t\t\t\t\t\t\tvar y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst )\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\tif ( y > lst )\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\n\t\t\t\t }\n\n\t\t\t\t\t \t\t\t\t\tif(lst == limit)\n\t\t\t\t\t\t\t\t\t\t\t\t\t write(\"YES\\n\");\n\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\twrite(\"NO\\n\");\n}\ngetPt( loop, limit);\n"}, {"source_code": "var read = readline().split(\" \").map(Number);\nvar loop = read[0];\nvar limit = read[1];\nvar lst = 0;\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = readline().split(\" \").map(Number);\n\t\t\t\t\t\t\t\tvar x = arr[0];\n\t\t\t\t\t\t\t\tvar y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst )\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\tif ( y > lst )\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\n\t\t\t\t }\n\n\t\t\t\t\t \t\t\t\t\tif(lst == limit)\n\t\t\t\t\t\t\t\t\t\t\t\t\t write(lst);\n\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\twrite(lst);\n}\ngetPt( loop, limit);\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar found = false;\nvar lst = 0;\nvar x;\nvar y;\ngetPt( loop, limit );\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\t\t\tx = arr[0],y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst ){\n\t\t\t\t\t\t\t\t\t\t\t reject = true;\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif ( y > lst ){\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\t\t\t\t\t\t\t\t\t\t\t if( lst == limit ){\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t found = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t }\n\t\t\t\t if(reject)\n\t\t\t\t \t\t\t write(\"NO\\n\");\n\t\t\t\t if(found)\n\t\t\t\t \t\t\t write(\"YES\\n\");\n\t\t\t\t if(!reject && !found)\n\t\t\t\t\t\t\t write(lst = limit ? \"YES\" : \"NO\");\n}\n\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar found = false;\nvar lst = 0;\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\t\t\tx = arr[0],y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst ){\n\t\t\t\t\t\t\t\t\t\t\t reject = true;\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif ( y > lst ){\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\t\t\t\t\t\t\t\t\t\t\t if( lst == limit ){\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t found = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t }\n\t\t\t\t if(reject)\n\t\t\t\t \t\t\t write(\"NO\\n\");\n\t\t\t\t if(found)\n\t\t\t\t \t\t\t write(\"YES\\n\");\n\t\t\t\t if(!reject && !found)\n\t\t\t\t return lst;\n}\nvar result = getPt(loop, limit);\nwrite(result == limit ? \"YES\" : \"NO\");\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar lst = 0;\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\t\t\tvar x = arr[0];\n\t\t\t\t\t\t\t\tvar y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst )\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\tif ( y > lst )\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\n\t\t\t\t }\n\n\t\t\t\t\t \t\t\t\t\tif(lst == limit)\n\t\t\t\t\t\t\t\t\t\t\t\t\t write(lst);\n\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\twrite(lst);\n}\ngetPt( loop, limit);\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar found = false;\nvar lst = 0;\ngetPt( loop, limit );\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\t\t\tx = arr[0],y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst ){\n\t\t\t\t\t\t\t\t\t\t\t reject = true;\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif ( y > lst ){\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\t\t\t\t\t\t\t\t\t\t\t if( lst == limit ){\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t found = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t }\n\t\t\t\t if(reject)\n\t\t\t\t \t\t\t write(\"NO\\n\");\n\t\t\t\t if(found)\n\t\t\t\t \t\t\t write(\"YES\\n\");\n\t\t\t\t if(!reject && !found)\n\t\t\t\t\t\t\t write(lst = limit ? \"YES\" : \"NO\");\n}\n\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar found = false;\nvar lst = 0;\nwhile( loop ){\n\t\t\t loop--;\n\t\t var arr = +readline().split(\" \");\n\t\t\t x = arr[0],y = arr[1];\n\t\t\t if ( x > lst ){\n\t\t\t\t \t\treject = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( y > lst ){\n\t\t\t\t\t\t\tlst = y;\n\t\t\t\t\t\t\tif( lst == limit ){\n\t\t\t\t\t\t\t\t\t found = true;\n\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t }\nif(reject)\n\t\t\twrite(\"NO\\n\");\nif(found)\n\t\t\t write(\"YES\\n\");\nif(!reject && !found)\n\t\t\t\t\t write(lst = limit ? \"YES\" : \"NO\");\n\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar lst = 0;\ngetPt( loop, limit);\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\t\t\tvar x = arr[0];\n\t\t\t\t\t\t\t\tvar y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst ){\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif ( y > lst ){\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t }\n\n\t\t\t\t\t \t\t\t\t\tif(lst == limit)\n\t\t\t\t\t\t\t\t\t\t\t\t\t write(\"YES\\n\");\n\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\twrite(\"NO\\n\");\n}\n"}, {"source_code": "var read = +readline().split(\" \");\nvar loop = read[0];\nvar limit = read[1];\nvar reject = false;\nvar found = false;\nvar lst = 0;\ngetPt( loop, limit);\nfunction getPt( loop, limit ){\n\t\t\t\t while( loop ){\n\t\t\t\t\t \t\t\tloop--;\n\t\t\t\t\t\t\t\tvar arr = +readline().split(\" \");\n\t\t\t\t\t\t\t\tvar x = arr[0];var y = arr[1];\n\t\t\t\t\t\t\t\tif ( x > lst ){\n\t\t\t\t\t\t\t\t\t\t\t reject = true;\n\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif ( y > lst ){\n\t\t\t\t\t\t\t\t\t\t\t lst = y;\n\t\t\t\t\t\t\t\t\t\t\t if( lst == limit ){\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t found = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t }\n\t\t\t\t if(reject)\n\t\t\t\t \t\t\t write(\"NO\\n\");\n\t\t\t\t if(found)\n\t\t\t\t \t\t\t write(\"YES\\n\");\n\t\t\t\t if(!reject && !found){\n\t\t\t\t\t \t\t\t\t\tif(lst == limit)\n\t\t\t\t\t\t\t\t\t\t\t\t\t write(\"YES\\n\");\n\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\twrite(\"NO\\n\");\n\t\t\t\t }\n}\n"}, {"source_code": "var line = readline().split(' ');\nvar N = parseInt(line[0]);\nvar M = parseInt(line[1]);\nvar a = [], b=[];\n\nfor(var i = 0; i < N; i++) {\n\tvar line = readline().split(' ');\n\ta[i] = parseInt(line[0]);\n\tb[i] = parseInt(line[1]);\n}\n\nvar left = 0;\n\nfor(var i=0;i b[i]) {\n\t\t\t\tans = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif ((m >= a[i] && m <= b[i])) {\n\t\t\tans = 1;\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nif (ans) {\n\tprint('YES');\n} else {\n\tprint('NO');\n}"}, {"source_code": "one=readline();\nn=parseInt(one.split(' ')[0]);\nm=parseInt(one.split(' ')[1]);\nmas=[];\nfunction compareNumeric(x, y) {\n if (x.a > y.a) return 1;\n if (x.a < y.a) return -1;\n}\nfor(i=0;i max) {\n max = mas[i].b;\n if (max >= m) {\n print('YES');\n }\n }\n }\n}\nprint('NO');"}, {"source_code": "one=readline();\nn=parseInt(one.split(' ')[0]);\nm=parseInt(one.split(' ')[1]);\nmas=[];\nfunction compareNumeric(x, y) {\n if (x.a > y.a) return 1;\n if (x.a < y.a) return -1;\n}\nfor(i=0;i max) {\n max = mas[i].b;\n if (max >= m) {\n print('YES');\n }\n }\n } else {\n print('NO'); \n }\n}"}, {"source_code": "one=readline();\nn=parseInt(one.split(' ')[0]);\nm=parseInt(one.split(' ')[1]);\nmas=[];\nfunction compareNumeric(x, y) {\n if (x.a > y.a) return 1;\n if (x.a < y.a) return -1;\n if (x.a === y.a) {\n if (x.b > y.b) return 1;\n if (x.b < y.b) return -1;\n }\n}\nfor(i=0;i max) {\n max = mas[i].b;\n if (max >= m) {\n print('YES');\n break;\n }\n }\n } else {\n print('NO'); \n break;\n }\n}\nif (max < m) {print('NO');}"}, {"source_code": "one=readline();\nn=parseInt(one.split(' ')[0]);\nm=parseInt(one.split(' ')[1]);\nmas=[];\nfunction compareNumeric(x, y) {\n if (x.a > y.a) return 1;\n if (x.a < y.a) return -1;\n if (x.a === y.a) {\n if (x.b > y.b) return 1;\n if (x.b < y.b) return -1;\n }\n}\nfor(i=0;i max) {\n max = mas[i].b;\n if (max >= m) {\n print('YES');\n break;\n }\n }\n } else {\n print('NO'); \n break;\n }\n}"}, {"source_code": "one=readline();\nn=parseInt(one.split(' ')[0]);\nm=parseInt(one.split(' ')[1]);\nmas=[];\nfunction compareNumeric(x, y) {\n if (x.a > y.a) return 1;\n if (x.a < y.a) return -1;\n if (x.a === y.a) {\n if (x.b > y.b) return 1;\n if (x.b < y.b) return -1;\n }\n}\nfor(i=0;i max) {\n max = mas[i].b;\n if (max >= m) {\n print('YES');\n }\n }\n } else {\n print('NO'); \n }\n}"}, {"source_code": "// write by lpy in 2017/12/21\n//title is Visting a Friend\n/*\n\tthe input of this argument\n*/\nvar arr = readline().split(\" \");\nvar n = arr[0];\nvar m = arr[1];\n\n//var array = [[0,4],[2,6],[6,7]];\n\nfunction f(n,m){// n is the number of input, m is the friend's house\n\t\n\t//the [left,right]is existing range\n\tvar str = readline().split(\" \");\n\tvar left = str[0], right = str[1];\n\tvar result = true; \n\tfor(var i = 1; i < n; i++){\n\t\tvar array = readline().split(\" \");\n\t\tvar a1 = left, b1 = right;\n\t\t// var a2 = array[i][0], b2 = array[i][1];\n\t\tvar a2 = array[0],b2 = array[1];\n\t\tif(a1 <= a2){\n\t\t\tleft = a1;\n\t\t\tif(a2 <= b1){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tresult = false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleft = a2;\n\t\t\tif(a1 <= b2){\n\t\t\t\tif(b1 <= b2){\n\t\t\t\t\tright = b2;\n\t\t\t\t}\n\t\t\t\telse right = b1;\n\t\t\t}\n\t\t\telse result = false;\n\t\t}\n\t}\n\tvar ans;\n\tif(left === 0 && right === m)\n\t\tans = 'YES';\n\telse ans = 'NO';\n\treturn ans;\n}\nprint(f(n, m));\n// console.log(f(3,5));\n"}], "src_uid": "d646834d58c519d5e9c0545df2ca4be2"} {"nl": {"description": "We're giving away nice huge bags containing number tiles! A bag we want to present to you contains $$$n$$$ tiles. Each of them has a single number written on it — either $$$1$$$ or $$$2$$$.However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.Can you win the prize? Hurry up, the bags are waiting!", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 200\\,000$$$) — the number of number tiles in the bag. The following line contains $$$n$$$ space-separated integers $$$a_1, a_2, \\dots, a_n$$$ ($$$a_i \\in \\{1, 2\\}$$$) — the values written on the tiles.", "output_spec": "Output a permutation $$$b_1, b_2, \\dots, b_n$$$ of the input sequence $$$(a_1, a_2, \\dots, a_n)$$$ maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.", "sample_inputs": ["5\n1 2 1 2 1", "9\n1 1 2 1 1 1 2 1 1"], "sample_outputs": ["1 1 1 2 2", "1 1 1 2 1 1 1 2 1"], "notes": "NoteThe first solution produces the prefix sums $$$1, \\mathbf{\\color{blue}{2}}, \\mathbf{\\color{blue}{3}}, \\mathbf{\\color{blue}{5}}, \\mathbf{\\color{blue}{7}}$$$ (four primes constructed), while the prefix sums in the second solution are $$$1, \\mathbf{\\color{blue}{2}}, \\mathbf{\\color{blue}{3}}, \\mathbf{\\color{blue}{5}}, 6, \\mathbf{\\color{blue}{7}}, 8, 10, \\mathbf{\\color{blue}{11}}$$$ (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible."}, "positive_code": [{"source_code": "\n(function () {\n var read = {\n number: function () {\n return +readline();\n },\n arr: function (divider) {\n return readline().split(divider ? divider : '');\n },\n arrNumber: function (divider) {\n return readline()\n .split(divider ? divider : '')\n .map(item => +item);\n }\n }\n\n var n = read.number();\n var a = read.arrNumber( ' ');\n\n var oneCount = 0;\n for(var i = 0; i < n; i++) {\n if(a[i] === 1) {\n oneCount ++;\n }\n }\n\n var twoCount = n - oneCount;\n\n var res = '';\n if(oneCount && twoCount ) {\n res += '2 1 ';\n for(var i = 0; i < twoCount - 1; i++) {\n res += (2 + ' ');\n }\n \n for(var i = 0; i < oneCount - 1; i++) {\n res += (1 + ' ');\n }\n }\n else {\n for(var i = 0; i < n; i++) {\n res += (a[i] + ' ')\n }\n }\n\n print(res);\n}());\n\n"}], "negative_code": [], "src_uid": "14593b565193607dff8b6b25bf51a661"} {"nl": {"description": "In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.", "input_spec": "The first line of the input contains the only integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) — the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \\le p_i \\le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.", "output_spec": "For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.", "sample_inputs": ["3\n2 3 2", "3\n1 2 3"], "sample_outputs": ["2 2 3", "1 2 3"], "notes": "NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge."}, "positive_code": [{"source_code": "\nfunction main() {\n const is = new Scanner();\n const n = is.nextInt();\n const reported = is.nextArray(Number);\n reported.unshift(null);\n const container = new Array(n + 1);\n let current;\n for (let i = 1; i <= n; i += 1) {\n container.fill(0);\n current = i;\n container[current] += 1;\n while (container[current] !== 2) {\n current = reported[current];\n container[current] += 1;\n }\n process.stdout.write(`${current.toString()} `);\n }\n console.log();\n}\n\n\n/*\n * Api Scanner\n */\nclass Scanner {\n constructor() {\n this.index = -1;\n this.lines = stdinInput.trim().split('\\n'); // eslint-disable-line\n }\n\n nextLine() {\n this.index += 1;\n return this.lines[this.index].trim();\n }\n\n nextInt() {\n return parseInt(this.nextLine(), 10);\n }\n\n nextDouble() {\n return parseFloat(this.nextLine());\n }\n\n nextArray(fn) {\n const array = this.nextLine().split(' ');\n return fn === String ? array : array.map(fn);\n }\n\n hasNext() {\n return this.index < this.lines.length;\n }\n}\n\nlet stdinInput = '';\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (input) => { stdinInput += input; });\nprocess.stdin.on('end', () => { main(); });\n"}, {"source_code": "const readline = require('readline')\n\nconst rl = readline.createInterface({input: process.stdin})\n\nlet n, p, numLines = 0\nrl.on('line', line => {\n if (++numLines == 1) {\n n = parseInt(line)\n } else {\n (p = line.split(' ').map(x => parseInt(x))).unshift(0)\n }\n}).on('close', () => {\n let caughtStudent = (id) => {\n let visited = []\n let dfs = u => {\n visited[u] = true\n if (!visited[p[u]]) {\n return dfs(p[u])\n } else {\n return p[u]\n }\n }\n return dfs(id)\n }\n process.stdout.write(`${[...Array(n + 1).keys()].slice(1).map(x => caughtStudent(x)).join(' ')}\\n`)\n})\n"}, {"source_code": "var n = readline();\nvar students = readline().split(' ');\nvar rst = [];\nfunction solve() {\n for (var m = 0; m < students.length; m++) {\n var set = {};\n var current = m;\n while (true) {\n set[current] = set[current] ? set[current] + 1 : 1;\n if (set[current] === 2) {\n rst.push(current + 1);\n break;\n }\n current = students[current] - 1;\n }\n }\n return rst;\n}\nprint(solve().join(' '));\n// console.log(solve())"}, {"source_code": "var visited = {};\n\nfunction dfs(cur) {\n visited[cur] = true;\n var stu = students[cur] - 1;\n return visited[stu] ? stu + 1 : dfs(stu);\n}\n\nfunction solve() {\n var res = [];\n for (var i = 0; i < n; i++) {\n visited = {};\n res[i] = dfs(i);\n }\n return res;\n}\n\nvar n = readline();\nvar students = readline().split(' ');\nprint(solve().join(' '));\n"}, {"source_code": "var cnt = {};\n\nfunction dfs(cur) {\n if (cnt[cur] > 1) {\n return cur;\n }\n cnt[cur] = cnt[cur] ? 2 : 1;\n return dfs(students[cur - 1]);\n}\n\nfunction solve() {\n var res = [];\n for (var i = 0; i 1) {\n return cur;\n }\n cnt[cur] = cnt[cur] ? 2 : 1;\n return dfs(students[cur - 1]);\n}\n\nfunction solve() {\n var res = [];\n for (var i = 0; i